]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/ipfw/tables.c
MFC r317666:
[FreeBSD/FreeBSD.git] / sbin / ipfw / tables.c
1 /*
2  * Copyright (c) 2014 Yandex LLC
3  * Copyright (c) 2014 Alexander V. Chernikov
4  *
5  * Redistribution and use in source forms, with and without modification,
6  * are permitted provided that this entire comment appears intact.
7  *
8  * Redistribution in binary form may occur without any restrictions.
9  * Obviously, it would be nice if you gave credit where credit is due
10  * but requiring it would be too onerous.
11  *
12  * This software is provided ``AS IS'' without any warranties of any kind.
13  *
14  * in-kernel ipfw tables support.
15  *
16  * $FreeBSD$
17  */
18
19
20 #include <sys/types.h>
21 #include <sys/param.h>
22 #include <sys/socket.h>
23 #include <sys/sysctl.h>
24
25 #include <ctype.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <netdb.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sysexits.h>
33
34 #include <net/if.h>
35 #include <netinet/in.h>
36 #include <netinet/ip_fw.h>
37 #include <arpa/inet.h>
38 #include <netdb.h>
39
40 #include "ipfw2.h"
41
42 static void table_modify_record(ipfw_obj_header *oh, int ac, char *av[],
43     int add, int quiet, int update, int atomic);
44 static int table_flush(ipfw_obj_header *oh);
45 static int table_destroy(ipfw_obj_header *oh);
46 static int table_do_create(ipfw_obj_header *oh, ipfw_xtable_info *i);
47 static int table_do_modify(ipfw_obj_header *oh, ipfw_xtable_info *i);
48 static int table_do_swap(ipfw_obj_header *oh, char *second);
49 static void table_create(ipfw_obj_header *oh, int ac, char *av[]);
50 static void table_modify(ipfw_obj_header *oh, int ac, char *av[]);
51 static void table_lookup(ipfw_obj_header *oh, int ac, char *av[]);
52 static void table_lock(ipfw_obj_header *oh, int lock);
53 static int table_swap(ipfw_obj_header *oh, char *second);
54 static int table_get_info(ipfw_obj_header *oh, ipfw_xtable_info *i);
55 static int table_show_info(ipfw_xtable_info *i, void *arg);
56
57 static int table_destroy_one(ipfw_xtable_info *i, void *arg);
58 static int table_flush_one(ipfw_xtable_info *i, void *arg);
59 static int table_show_one(ipfw_xtable_info *i, void *arg);
60 static int table_do_get_list(ipfw_xtable_info *i, ipfw_obj_header **poh);
61 static void table_show_list(ipfw_obj_header *oh, int need_header);
62 static void table_show_entry(ipfw_xtable_info *i, ipfw_obj_tentry *tent);
63
64 static void tentry_fill_key(ipfw_obj_header *oh, ipfw_obj_tentry *tent,
65     char *key, int add, uint8_t *ptype, uint32_t *pvmask, ipfw_xtable_info *xi);
66 static void tentry_fill_value(ipfw_obj_header *oh, ipfw_obj_tentry *tent,
67     char *arg, uint8_t type, uint32_t vmask);
68 static void table_show_value(char *buf, size_t bufsize, ipfw_table_value *v,
69     uint32_t vmask, int print_ip);
70
71 typedef int (table_cb_t)(ipfw_xtable_info *i, void *arg);
72 static int tables_foreach(table_cb_t *f, void *arg, int sort);
73
74 #ifndef s6_addr32
75 #define s6_addr32 __u6_addr.__u6_addr32
76 #endif
77
78 static struct _s_x tabletypes[] = {
79       { "addr",         IPFW_TABLE_ADDR },
80       { "iface",        IPFW_TABLE_INTERFACE },
81       { "number",       IPFW_TABLE_NUMBER },
82       { "flow",         IPFW_TABLE_FLOW },
83       { NULL, 0 }
84 };
85
86 static struct _s_x tablevaltypes[] = {
87       { "skipto",       IPFW_VTYPE_SKIPTO },
88       { "pipe",         IPFW_VTYPE_PIPE },
89       { "fib",          IPFW_VTYPE_FIB },
90       { "nat",          IPFW_VTYPE_NAT },
91       { "dscp",         IPFW_VTYPE_DSCP },
92       { "tag",          IPFW_VTYPE_TAG },
93       { "divert",       IPFW_VTYPE_DIVERT },
94       { "netgraph",     IPFW_VTYPE_NETGRAPH },
95       { "limit",        IPFW_VTYPE_LIMIT },
96       { "ipv4",         IPFW_VTYPE_NH4 },
97       { "ipv6",         IPFW_VTYPE_NH6 },
98       { NULL, 0 }
99 };
100
101 static struct _s_x tablecmds[] = {
102       { "add",          TOK_ADD },
103       { "delete",       TOK_DEL },
104       { "create",       TOK_CREATE },
105       { "destroy",      TOK_DESTROY },
106       { "flush",        TOK_FLUSH },
107       { "modify",       TOK_MODIFY },
108       { "swap",         TOK_SWAP },
109       { "info",         TOK_INFO },
110       { "detail",       TOK_DETAIL },
111       { "list",         TOK_LIST },
112       { "lookup",       TOK_LOOKUP },
113       { "atomic",       TOK_ATOMIC },
114       { "lock",         TOK_LOCK },
115       { "unlock",       TOK_UNLOCK },
116       { NULL, 0 }
117 };
118
119 static int
120 lookup_host (char *host, struct in_addr *ipaddr)
121 {
122         struct hostent *he;
123
124         if (!inet_aton(host, ipaddr)) {
125                 if ((he = gethostbyname(host)) == NULL)
126                         return(-1);
127                 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
128         }
129         return(0);
130 }
131
132 /*
133  * This one handles all table-related commands
134  *      ipfw table NAME create ...
135  *      ipfw table NAME modify ...
136  *      ipfw table {NAME | all} destroy
137  *      ipfw table NAME swap NAME
138  *      ipfw table NAME lock
139  *      ipfw table NAME unlock
140  *      ipfw table NAME add addr[/masklen] [value] 
141  *      ipfw table NAME add [addr[/masklen] value] [addr[/masklen] value] ..
142  *      ipfw table NAME delete addr[/masklen] [addr[/masklen]] ..
143  *      ipfw table NAME lookup addr
144  *      ipfw table {NAME | all} flush
145  *      ipfw table {NAME | all} list
146  *      ipfw table {NAME | all} info
147  *      ipfw table {NAME | all} detail
148  */
149 void
150 ipfw_table_handler(int ac, char *av[])
151 {
152         int do_add, is_all;
153         int atomic, error, tcmd;
154         ipfw_xtable_info i;
155         ipfw_obj_header oh;
156         char *tablename;
157         uint8_t set;
158         void *arg;
159
160         memset(&oh, 0, sizeof(oh));
161         is_all = 0;
162         if (co.use_set != 0)
163                 set = co.use_set - 1;
164         else
165                 set = 0;
166
167         ac--; av++;
168         NEED1("table needs name");
169         tablename = *av;
170
171         if (table_check_name(tablename) == 0) {
172                 table_fill_ntlv(&oh.ntlv, *av, set, 1);
173                 oh.idx = 1;
174         } else {
175                 if (strcmp(tablename, "all") == 0)
176                         is_all = 1;
177                 else
178                         errx(EX_USAGE, "table name %s is invalid", tablename);
179         }
180         ac--; av++;
181         NEED1("table needs command");
182
183         tcmd = get_token(tablecmds, *av, "table command");
184         /* Check if atomic operation was requested */
185         atomic = 0;
186         if (tcmd == TOK_ATOMIC) {
187                 ac--; av++;
188                 NEED1("atomic needs command");
189                 tcmd = get_token(tablecmds, *av, "table command");
190                 switch (tcmd) {
191                 case TOK_ADD:
192                         break;
193                 default:
194                         errx(EX_USAGE, "atomic is not compatible with %s", *av);
195                 }
196                 atomic = 1;
197         }
198
199         switch (tcmd) {
200         case TOK_LIST:
201         case TOK_INFO:
202         case TOK_DETAIL:
203         case TOK_FLUSH:
204         case TOK_DESTROY:
205                 break;
206         default:
207                 if (is_all != 0)
208                         errx(EX_USAGE, "table name required");
209         }
210
211         switch (tcmd) {
212         case TOK_ADD:
213         case TOK_DEL:
214                 do_add = **av == 'a';
215                 ac--; av++;
216                 table_modify_record(&oh, ac, av, do_add, co.do_quiet,
217                     co.do_quiet, atomic);
218                 break;
219         case TOK_CREATE:
220                 ac--; av++;
221                 table_create(&oh, ac, av);
222                 break;
223         case TOK_MODIFY:
224                 ac--; av++;
225                 table_modify(&oh, ac, av);
226                 break;
227         case TOK_DESTROY:
228                 if (is_all == 0) {
229                         if (table_destroy(&oh) == 0)
230                                 break;
231                         if (errno != ESRCH)
232                                 err(EX_OSERR, "failed to destroy table %s",
233                                     tablename);
234                         /* ESRCH isn't fatal, warn if not quiet mode */
235                         if (co.do_quiet == 0)
236                                 warn("failed to destroy table %s", tablename);
237                 } else {
238                         error = tables_foreach(table_destroy_one, &oh, 1);
239                         if (error != 0)
240                                 err(EX_OSERR,
241                                     "failed to destroy tables list");
242                 }
243                 break;
244         case TOK_FLUSH:
245                 if (is_all == 0) {
246                         if ((error = table_flush(&oh)) == 0)
247                                 break;
248                         if (errno != ESRCH)
249                                 err(EX_OSERR, "failed to flush table %s info",
250                                     tablename);
251                         /* ESRCH isn't fatal, warn if not quiet mode */
252                         if (co.do_quiet == 0)
253                                 warn("failed to flush table %s info",
254                                     tablename);
255                 } else {
256                         error = tables_foreach(table_flush_one, &oh, 1);
257                         if (error != 0)
258                                 err(EX_OSERR, "failed to flush tables list");
259                         /* XXX: we ignore errors here */
260                 }
261                 break;
262         case TOK_SWAP:
263                 ac--; av++;
264                 NEED1("second table name required");
265                 table_swap(&oh, *av);
266                 break;
267         case TOK_LOCK:
268         case TOK_UNLOCK:
269                 table_lock(&oh, (tcmd == TOK_LOCK));
270                 break;
271         case TOK_DETAIL:
272         case TOK_INFO:
273                 arg = (tcmd == TOK_DETAIL) ? (void *)1 : NULL;
274                 if (is_all == 0) {
275                         if ((error = table_get_info(&oh, &i)) != 0)
276                                 err(EX_OSERR, "failed to request table info");
277                         table_show_info(&i, arg);
278                 } else {
279                         error = tables_foreach(table_show_info, arg, 1);
280                         if (error != 0)
281                                 err(EX_OSERR, "failed to request tables list");
282                 }
283                 break;
284         case TOK_LIST:
285                 if (is_all == 0) {
286                         ipfw_xtable_info i;
287                         if ((error = table_get_info(&oh, &i)) != 0)
288                                 err(EX_OSERR, "failed to request table info");
289                         table_show_one(&i, NULL);
290                 } else {
291                         error = tables_foreach(table_show_one, NULL, 1);
292                         if (error != 0)
293                                 err(EX_OSERR, "failed to request tables list");
294                 }
295                 break;
296         case TOK_LOOKUP:
297                 ac--; av++;
298                 table_lookup(&oh, ac, av);
299                 break;
300         }
301 }
302
303 void
304 table_fill_ntlv(ipfw_obj_ntlv *ntlv, const char *name, uint8_t set,
305     uint16_t uidx)
306 {
307
308         ntlv->head.type = IPFW_TLV_TBL_NAME;
309         ntlv->head.length = sizeof(ipfw_obj_ntlv);
310         ntlv->idx = uidx;
311         ntlv->set = set;
312         strlcpy(ntlv->name, name, sizeof(ntlv->name));
313 }
314
315 static void
316 table_fill_objheader(ipfw_obj_header *oh, ipfw_xtable_info *i)
317 {
318
319         oh->idx = 1;
320         table_fill_ntlv(&oh->ntlv, i->tablename, i->set, 1);
321 }
322
323 static struct _s_x tablenewcmds[] = {
324       { "type",         TOK_TYPE },
325       { "valtype",      TOK_VALTYPE },
326       { "algo",         TOK_ALGO },
327       { "limit",        TOK_LIMIT },
328       { "locked",       TOK_LOCK },
329       { NULL, 0 }
330 };
331
332 static struct _s_x flowtypecmds[] = {
333       { "src-ip",       IPFW_TFFLAG_SRCIP },
334       { "proto",        IPFW_TFFLAG_PROTO },
335       { "src-port",     IPFW_TFFLAG_SRCPORT },
336       { "dst-ip",       IPFW_TFFLAG_DSTIP },
337       { "dst-port",     IPFW_TFFLAG_DSTPORT },
338       { NULL, 0 }
339 };
340
341 int
342 table_parse_type(uint8_t ttype, char *p, uint8_t *tflags)
343 {
344         uint32_t fset, fclear;
345         char *e;
346
347         /* Parse type options */
348         switch(ttype) {
349         case IPFW_TABLE_FLOW:
350                 fset = fclear = 0;
351                 if (fill_flags(flowtypecmds, p, &e, &fset, &fclear) != 0)
352                         errx(EX_USAGE,
353                             "unable to parse flow option %s", e);
354                 *tflags = fset;
355                 break;
356         default:
357                 return (EX_USAGE);
358         }
359
360         return (0);
361 }
362
363 void
364 table_print_type(char *tbuf, size_t size, uint8_t type, uint8_t tflags)
365 {
366         const char *tname;
367         int l;
368
369         if ((tname = match_value(tabletypes, type)) == NULL)
370                 tname = "unknown";
371
372         l = snprintf(tbuf, size, "%s", tname);
373         tbuf += l;
374         size -= l;
375
376         switch(type) {
377         case IPFW_TABLE_FLOW:
378                 if (tflags != 0) {
379                         *tbuf++ = ':';
380                         l--;
381                         print_flags_buffer(tbuf, size, flowtypecmds, tflags);
382                 }
383                 break;
384         }
385 }
386
387 /*
388  * Creates new table
389  *
390  * ipfw table NAME create [ type { addr | iface | number | flow } ]
391  *     [ algo algoname ]
392  */
393 static void
394 table_create(ipfw_obj_header *oh, int ac, char *av[])
395 {
396         ipfw_xtable_info xi;
397         int error, tcmd, val;
398         uint32_t fset, fclear;
399         char *e, *p;
400         char tbuf[128];
401
402         memset(&xi, 0, sizeof(xi));
403
404         while (ac > 0) {
405                 tcmd = get_token(tablenewcmds, *av, "option");
406                 ac--; av++;
407
408                 switch (tcmd) {
409                 case TOK_LIMIT:
410                         NEED1("limit value required");
411                         xi.limit = strtol(*av, NULL, 10);
412                         ac--; av++;
413                         break;
414                 case TOK_TYPE:
415                         NEED1("table type required");
416                         /* Type may have suboptions after ':' */
417                         if ((p = strchr(*av, ':')) != NULL)
418                                 *p++ = '\0';
419                         val = match_token(tabletypes, *av);
420                         if (val == -1) {
421                                 concat_tokens(tbuf, sizeof(tbuf), tabletypes,
422                                     ", ");
423                                 errx(EX_USAGE,
424                                     "Unknown tabletype: %s. Supported: %s",
425                                     *av, tbuf);
426                         }
427                         xi.type = val;
428                         if (p != NULL) {
429                                 error = table_parse_type(val, p, &xi.tflags);
430                                 if (error != 0)
431                                         errx(EX_USAGE,
432                                             "Unsupported suboptions: %s", p);
433                         }
434                         ac--; av++;
435                         break;
436                 case TOK_VALTYPE:
437                         NEED1("table value type required");
438                         fset = fclear = 0;
439                         val = fill_flags(tablevaltypes, *av, &e, &fset, &fclear);
440                         if (val != -1) {
441                                 xi.vmask = fset;
442                                 ac--; av++;
443                                 break;
444                         }
445                         concat_tokens(tbuf, sizeof(tbuf), tablevaltypes, ", ");
446                         errx(EX_USAGE, "Unknown value type: %s. Supported: %s",
447                             e, tbuf);
448                         break;
449                 case TOK_ALGO:
450                         NEED1("table algorithm name required");
451                         if (strlen(*av) > sizeof(xi.algoname))
452                                 errx(EX_USAGE, "algorithm name too long");
453                         strlcpy(xi.algoname, *av, sizeof(xi.algoname));
454                         ac--; av++;
455                         break;
456                 case TOK_LOCK:
457                         xi.flags |= IPFW_TGFLAGS_LOCKED;
458                         break;
459                 }
460         }
461
462         /* Set some defaults to preserve compatibility. */
463         if (xi.algoname[0] == '\0' && xi.type == 0)
464                 xi.type = IPFW_TABLE_ADDR;
465         if (xi.vmask == 0)
466                 xi.vmask = IPFW_VTYPE_LEGACY;
467
468         if ((error = table_do_create(oh, &xi)) != 0)
469                 err(EX_OSERR, "Table creation failed");
470 }
471
472 /*
473  * Creates new table
474  *
475  * Request: [ ipfw_obj_header ipfw_xtable_info ]
476  *
477  * Returns 0 on success.
478  */
479 static int
480 table_do_create(ipfw_obj_header *oh, ipfw_xtable_info *i)
481 {
482         char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_xtable_info)];
483         int error;
484
485         memcpy(tbuf, oh, sizeof(*oh));
486         memcpy(tbuf + sizeof(*oh), i, sizeof(*i));
487         oh = (ipfw_obj_header *)tbuf;
488
489         error = do_set3(IP_FW_TABLE_XCREATE, &oh->opheader, sizeof(tbuf));
490
491         return (error);
492 }
493
494 /*
495  * Modifies existing table
496  *
497  * ipfw table NAME modify [ limit number ]
498  */
499 static void
500 table_modify(ipfw_obj_header *oh, int ac, char *av[])
501 {
502         ipfw_xtable_info xi;
503         int tcmd;
504
505         memset(&xi, 0, sizeof(xi));
506
507         while (ac > 0) {
508                 tcmd = get_token(tablenewcmds, *av, "option");
509                 ac--; av++;
510
511                 switch (tcmd) {
512                 case TOK_LIMIT:
513                         NEED1("limit value required");
514                         xi.limit = strtol(*av, NULL, 10);
515                         xi.mflags |= IPFW_TMFLAGS_LIMIT;
516                         ac--; av++;
517                         break;
518                 default:
519                         errx(EX_USAGE, "cmd is not supported for modificatiob");
520                 }
521         }
522
523         if (table_do_modify(oh, &xi) != 0)
524                 err(EX_OSERR, "Table modification failed");
525 }
526
527 /*
528  * Modifies existing table.
529  *
530  * Request: [ ipfw_obj_header ipfw_xtable_info ]
531  *
532  * Returns 0 on success.
533  */
534 static int
535 table_do_modify(ipfw_obj_header *oh, ipfw_xtable_info *i)
536 {
537         char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_xtable_info)];
538         int error;
539
540         memcpy(tbuf, oh, sizeof(*oh));
541         memcpy(tbuf + sizeof(*oh), i, sizeof(*i));
542         oh = (ipfw_obj_header *)tbuf;
543
544         error = do_set3(IP_FW_TABLE_XMODIFY, &oh->opheader, sizeof(tbuf));
545
546         return (error);
547 }
548
549 /*
550  * Locks or unlocks given table
551  */
552 static void
553 table_lock(ipfw_obj_header *oh, int lock)
554 {
555         ipfw_xtable_info xi;
556
557         memset(&xi, 0, sizeof(xi));
558
559         xi.mflags |= IPFW_TMFLAGS_LOCK;
560         xi.flags |= (lock != 0) ? IPFW_TGFLAGS_LOCKED : 0;
561
562         if (table_do_modify(oh, &xi) != 0)
563                 err(EX_OSERR, "Table %s failed", lock != 0 ? "lock" : "unlock");
564 }
565
566 /*
567  * Destroys given table specified by @oh->ntlv.
568  * Returns 0 on success.
569  */
570 static int
571 table_destroy(ipfw_obj_header *oh)
572 {
573
574         if (do_set3(IP_FW_TABLE_XDESTROY, &oh->opheader, sizeof(*oh)) != 0)
575                 return (-1);
576
577         return (0);
578 }
579
580 static int
581 table_destroy_one(ipfw_xtable_info *i, void *arg)
582 {
583         ipfw_obj_header *oh;
584
585         oh = (ipfw_obj_header *)arg;
586         table_fill_ntlv(&oh->ntlv, i->tablename, i->set, 1);
587         if (table_destroy(oh) != 0) {
588                 if (co.do_quiet == 0)
589                         warn("failed to destroy table(%s) in set %u",
590                             i->tablename, i->set);
591                 return (-1);
592         }
593         return (0);
594 }
595
596 /*
597  * Flushes given table specified by @oh->ntlv.
598  * Returns 0 on success.
599  */
600 static int
601 table_flush(ipfw_obj_header *oh)
602 {
603
604         if (do_set3(IP_FW_TABLE_XFLUSH, &oh->opheader, sizeof(*oh)) != 0)
605                 return (-1);
606
607         return (0);
608 }
609
610 static int
611 table_do_swap(ipfw_obj_header *oh, char *second)
612 {
613         char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_obj_ntlv)];
614         int error;
615
616         memset(tbuf, 0, sizeof(tbuf));
617         memcpy(tbuf, oh, sizeof(*oh));
618         oh = (ipfw_obj_header *)tbuf;
619         table_fill_ntlv((ipfw_obj_ntlv *)(oh + 1), second, oh->ntlv.set, 1);
620
621         error = do_set3(IP_FW_TABLE_XSWAP, &oh->opheader, sizeof(tbuf));
622
623         return (error);
624 }
625
626 /*
627  * Swaps given table with @second one.
628  */
629 static int
630 table_swap(ipfw_obj_header *oh, char *second)
631 {
632
633         if (table_check_name(second) != 0)
634                 errx(EX_USAGE, "table name %s is invalid", second);
635
636         if (table_do_swap(oh, second) == 0)
637                 return (0);
638
639         switch (errno) {
640         case EINVAL:
641                 errx(EX_USAGE, "Unable to swap table: check types");
642         case EFBIG:
643                 errx(EX_USAGE, "Unable to swap table: check limits");
644         }
645
646         return (0);
647 }
648
649
650 /*
651  * Retrieves table in given table specified by @oh->ntlv.
652  * it inside @i.
653  * Returns 0 on success.
654  */
655 static int
656 table_get_info(ipfw_obj_header *oh, ipfw_xtable_info *i)
657 {
658         char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_xtable_info)];
659         size_t sz;
660
661         sz = sizeof(tbuf);
662         memset(tbuf, 0, sizeof(tbuf));
663         memcpy(tbuf, oh, sizeof(*oh));
664         oh = (ipfw_obj_header *)tbuf;
665
666         if (do_get3(IP_FW_TABLE_XINFO, &oh->opheader, &sz) != 0)
667                 return (errno);
668
669         if (sz < sizeof(tbuf))
670                 return (EINVAL);
671
672         *i = *(ipfw_xtable_info *)(oh + 1);
673
674         return (0);
675 }
676
677 static struct _s_x tablealgoclass[] = {
678       { "hash",         IPFW_TACLASS_HASH },
679       { "array",        IPFW_TACLASS_ARRAY },
680       { "radix",        IPFW_TACLASS_RADIX },
681       { NULL, 0 }
682 };
683
684 struct ta_cldata {
685         uint8_t         taclass;
686         uint8_t         spare4;
687         uint16_t        itemsize;
688         uint16_t        itemsize6;
689         uint32_t        size;   
690         uint32_t        count;
691 };
692
693 /*
694  * Print global/per-AF table @i algorithm info.
695  */
696 static void
697 table_show_tainfo(ipfw_xtable_info *i, struct ta_cldata *d,
698     const char *af, const char *taclass)
699 {
700
701         switch (d->taclass) {
702         case IPFW_TACLASS_HASH:
703         case IPFW_TACLASS_ARRAY:
704                 printf(" %salgorithm %s info\n", af, taclass);
705                 if (d->itemsize == d->itemsize6)
706                         printf("  size: %u items: %u itemsize: %u\n",
707                             d->size, d->count, d->itemsize);
708                 else
709                         printf("  size: %u items: %u "
710                             "itemsize4: %u itemsize6: %u\n",
711                             d->size, d->count,
712                             d->itemsize, d->itemsize6);
713                 break;
714         case IPFW_TACLASS_RADIX:
715                 printf(" %salgorithm %s info\n", af, taclass);
716                 if (d->itemsize == d->itemsize6)
717                         printf("  items: %u itemsize: %u\n",
718                             d->count, d->itemsize);
719                 else
720                         printf("  items: %u "
721                             "itemsize4: %u itemsize6: %u\n",
722                             d->count, d->itemsize, d->itemsize6);
723                 break;
724         default:
725                 printf(" algo class: %s\n", taclass);
726         }
727 }
728
729 static void
730 table_print_valheader(char *buf, size_t bufsize, uint32_t vmask)
731 {
732
733         if (vmask == IPFW_VTYPE_LEGACY) {
734                 snprintf(buf, bufsize, "legacy");
735                 return;
736         }
737
738         memset(buf, 0, bufsize);
739         print_flags_buffer(buf, bufsize, tablevaltypes, vmask);
740 }
741
742 /*
743  * Prints table info struct @i in human-readable form.
744  */
745 static int
746 table_show_info(ipfw_xtable_info *i, void *arg)
747 {
748         const char *vtype;
749         ipfw_ta_tinfo *tainfo;
750         int afdata, afitem;
751         struct ta_cldata d;
752         char ttype[64], tvtype[64];
753
754         table_print_type(ttype, sizeof(ttype), i->type, i->tflags);
755         table_print_valheader(tvtype, sizeof(tvtype), i->vmask);
756
757         printf("--- table(%s), set(%u) ---\n", i->tablename, i->set);
758         if ((i->flags & IPFW_TGFLAGS_LOCKED) != 0)
759                 printf(" kindex: %d, type: %s, locked\n", i->kidx, ttype);
760         else
761                 printf(" kindex: %d, type: %s\n", i->kidx, ttype);
762         printf(" references: %u, valtype: %s\n", i->refcnt, tvtype);
763         printf(" algorithm: %s\n", i->algoname);
764         printf(" items: %u, size: %u\n", i->count, i->size);
765         if (i->limit > 0)
766                 printf(" limit: %u\n", i->limit);
767
768         /* Print algo-specific info if requested & set  */
769         if (arg == NULL)
770                 return (0);
771
772         if ((i->ta_info.flags & IPFW_TATFLAGS_DATA) == 0)
773                 return (0);
774         tainfo = &i->ta_info;
775
776         afdata = 0;
777         afitem = 0;
778         if (tainfo->flags & IPFW_TATFLAGS_AFDATA)
779                 afdata = 1;
780         if (tainfo->flags & IPFW_TATFLAGS_AFITEM)
781                 afitem = 1;
782
783         memset(&d, 0, sizeof(d));
784         d.taclass = tainfo->taclass4;
785         d.size = tainfo->size4;
786         d.count = tainfo->count4;
787         d.itemsize = tainfo->itemsize4;
788         if (afdata == 0 && afitem != 0)
789                 d.itemsize6 = tainfo->itemsize6;
790         else
791                 d.itemsize6 = d.itemsize;
792         if ((vtype = match_value(tablealgoclass, d.taclass)) == NULL)
793                 vtype = "unknown";
794
795         if (afdata == 0) {
796                 table_show_tainfo(i, &d, "", vtype);
797         } else {
798                 table_show_tainfo(i, &d, "IPv4 ", vtype);
799                 memset(&d, 0, sizeof(d));
800                 d.taclass = tainfo->taclass6;
801                 if ((vtype = match_value(tablealgoclass, d.taclass)) == NULL)
802                         vtype = "unknown";
803                 d.size = tainfo->size6;
804                 d.count = tainfo->count6;
805                 d.itemsize = tainfo->itemsize6;
806                 d.itemsize6 = d.itemsize;
807                 table_show_tainfo(i, &d, "IPv6 ", vtype);
808         }
809
810         return (0);
811 }
812
813
814 /*
815  * Function wrappers which can be used either
816  * as is or as foreach function parameter.
817  */
818
819 static int
820 table_show_one(ipfw_xtable_info *i, void *arg)
821 {
822         ipfw_obj_header *oh;
823         int error;
824
825         if ((error = table_do_get_list(i, &oh)) != 0) {
826                 err(EX_OSERR, "Error requesting table %s list", i->tablename);
827                 return (error);
828         }
829
830         table_show_list(oh, 1);
831
832         free(oh);
833         return (0);     
834 }
835
836 static int
837 table_flush_one(ipfw_xtable_info *i, void *arg)
838 {
839         ipfw_obj_header *oh;
840
841         oh = (ipfw_obj_header *)arg;
842
843         table_fill_ntlv(&oh->ntlv, i->tablename, i->set, 1);
844
845         return (table_flush(oh));
846 }
847
848 static int
849 table_do_modify_record(int cmd, ipfw_obj_header *oh,
850     ipfw_obj_tentry *tent, int count, int atomic)
851 {
852         ipfw_obj_ctlv *ctlv;
853         ipfw_obj_tentry *tent_base;
854         caddr_t pbuf;
855         char xbuf[sizeof(*oh) + sizeof(ipfw_obj_ctlv) + sizeof(*tent)];
856         int error, i;
857         size_t sz;
858
859         sz = sizeof(*ctlv) + sizeof(*tent) * count;
860         if (count == 1) {
861                 memset(xbuf, 0, sizeof(xbuf));
862                 pbuf = xbuf;
863         } else {
864                 if ((pbuf = calloc(1, sizeof(*oh) + sz)) == NULL)
865                         return (ENOMEM);
866         }
867
868         memcpy(pbuf, oh, sizeof(*oh));
869         oh = (ipfw_obj_header *)pbuf;
870         oh->opheader.version = 1;
871
872         ctlv = (ipfw_obj_ctlv *)(oh + 1);
873         ctlv->count = count;
874         ctlv->head.length = sz;
875         if (atomic != 0)
876                 ctlv->flags |= IPFW_CTF_ATOMIC;
877
878         tent_base = tent;
879         memcpy(ctlv + 1, tent, sizeof(*tent) * count);
880         tent = (ipfw_obj_tentry *)(ctlv + 1);
881         for (i = 0; i < count; i++, tent++) {
882                 tent->head.length = sizeof(ipfw_obj_tentry);
883                 tent->idx = oh->idx;
884         }
885
886         sz += sizeof(*oh);
887         error = do_get3(cmd, &oh->opheader, &sz);
888         tent = (ipfw_obj_tentry *)(ctlv + 1);
889         /* Copy result back to provided buffer */
890         memcpy(tent_base, ctlv + 1, sizeof(*tent) * count);
891
892         if (pbuf != xbuf)
893                 free(pbuf);
894
895         return (error);
896 }
897
898 static void
899 table_modify_record(ipfw_obj_header *oh, int ac, char *av[], int add,
900     int quiet, int update, int atomic)
901 {
902         ipfw_obj_tentry *ptent, tent, *tent_buf;
903         ipfw_xtable_info xi;
904         uint8_t type;
905         uint32_t vmask;
906         int cmd, count, error, i, ignored;
907         char *texterr, *etxt, *px;
908
909         if (ac == 0)
910                 errx(EX_USAGE, "address required");
911         
912         if (add != 0) {
913                 cmd = IP_FW_TABLE_XADD;
914                 texterr = "Adding record failed";
915         } else {
916                 cmd = IP_FW_TABLE_XDEL;
917                 texterr = "Deleting record failed";
918         }
919
920         /*
921          * Calculate number of entries:
922          * Assume [key val] x N for add
923          * and
924          * key x N for delete
925          */
926         count = (add != 0) ? ac / 2 + 1 : ac;
927
928         if (count <= 1) {
929                 /* Adding single entry with/without value */
930                 memset(&tent, 0, sizeof(tent));
931                 tent_buf = &tent;
932         } else {
933                 
934                 if ((tent_buf = calloc(count, sizeof(tent))) == NULL)
935                         errx(EX_OSERR,
936                             "Unable to allocate memory for all entries");
937         }
938         ptent = tent_buf;
939
940         memset(&xi, 0, sizeof(xi));
941         count = 0;
942         while (ac > 0) {
943                 tentry_fill_key(oh, ptent, *av, add, &type, &vmask, &xi);
944
945                 /*
946                  * Compatibility layer: auto-create table if not exists.
947                  */
948                 if (xi.tablename[0] == '\0') {
949                         xi.type = type;
950                         xi.vmask = vmask;
951                         strlcpy(xi.tablename, oh->ntlv.name,
952                             sizeof(xi.tablename));
953                         if (quiet == 0)
954                                 warnx("DEPRECATED: inserting data into "
955                                     "non-existent table %s. (auto-created)",
956                                     xi.tablename);
957                         table_do_create(oh, &xi);
958                 }
959         
960                 oh->ntlv.type = type;
961                 ac--; av++;
962         
963                 if (add != 0 && ac > 0) {
964                         tentry_fill_value(oh, ptent, *av, type, vmask);
965                         ac--; av++;
966                 }
967
968                 if (update != 0)
969                         ptent->head.flags |= IPFW_TF_UPDATE;
970
971                 count++;
972                 ptent++;
973         }
974
975         error = table_do_modify_record(cmd, oh, tent_buf, count, atomic);
976
977         /*
978          * Compatibility stuff: do not yell on duplicate keys or
979          * failed deletions.
980          */
981         if (error == 0 || (error == EEXIST && add != 0) ||
982             (error == ENOENT && add == 0)) {
983                 if (quiet != 0) {
984                         if (tent_buf != &tent)
985                                 free(tent_buf);
986                         return;
987                 }
988         }
989
990         /* Report results back */
991         ptent = tent_buf;
992         for (i = 0; i < count; ptent++, i++) {
993                 ignored = 0;
994                 switch (ptent->result) {
995                 case IPFW_TR_ADDED:
996                         px = "added";
997                         break;
998                 case IPFW_TR_DELETED:
999                         px = "deleted";
1000                         break;
1001                 case IPFW_TR_UPDATED:
1002                         px = "updated";
1003                         break;
1004                 case IPFW_TR_LIMIT:
1005                         px = "limit";
1006                         ignored = 1;
1007                         break;
1008                 case IPFW_TR_ERROR:
1009                         px = "error";
1010                         ignored = 1;
1011                         break;
1012                 case IPFW_TR_NOTFOUND:
1013                         px = "notfound";
1014                         ignored = 1;
1015                         break;
1016                 case IPFW_TR_EXISTS:
1017                         px = "exists";
1018                         ignored = 1;
1019                         break;
1020                 case IPFW_TR_IGNORED:
1021                         px = "ignored";
1022                         ignored = 1;
1023                         break;
1024                 default:
1025                         px = "unknown";
1026                         ignored = 1;
1027                 }
1028
1029                 if (error != 0 && atomic != 0 && ignored == 0)
1030                         printf("%s(reverted): ", px);
1031                 else
1032                         printf("%s: ", px);
1033
1034                 table_show_entry(&xi, ptent);
1035         }
1036
1037         if (tent_buf != &tent)
1038                 free(tent_buf);
1039
1040         if (error == 0)
1041                 return;
1042         /* Get real OS error */
1043         error = errno;
1044
1045         /* Try to provide more human-readable error */
1046         switch (error) {
1047         case EEXIST:
1048                 etxt = "record already exists";
1049                 break;
1050         case EFBIG:
1051                 etxt = "limit hit";
1052                 break;
1053         case ESRCH:
1054                 etxt = "table not found";
1055                 break;
1056         case ENOENT:
1057                 etxt = "record not found";
1058                 break;
1059         case EACCES:
1060                 etxt = "table is locked";
1061                 break;
1062         default:
1063                 etxt = strerror(error);
1064         }
1065
1066         errx(EX_OSERR, "%s: %s", texterr, etxt);
1067 }
1068
1069 static int
1070 table_do_lookup(ipfw_obj_header *oh, char *key, ipfw_xtable_info *xi,
1071     ipfw_obj_tentry *xtent)
1072 {
1073         char xbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_obj_tentry)];
1074         ipfw_obj_tentry *tent;
1075         uint8_t type;
1076         uint32_t vmask;
1077         size_t sz;
1078
1079         memcpy(xbuf, oh, sizeof(*oh));
1080         oh = (ipfw_obj_header *)xbuf;
1081         tent = (ipfw_obj_tentry *)(oh + 1);
1082
1083         memset(tent, 0, sizeof(*tent));
1084         tent->head.length = sizeof(*tent);
1085         tent->idx = 1;
1086
1087         tentry_fill_key(oh, tent, key, 0, &type, &vmask, xi);
1088         oh->ntlv.type = type;
1089
1090         sz = sizeof(xbuf);
1091         if (do_get3(IP_FW_TABLE_XFIND, &oh->opheader, &sz) != 0)
1092                 return (errno);
1093
1094         if (sz < sizeof(xbuf))
1095                 return (EINVAL);
1096
1097         *xtent = *tent;
1098
1099         return (0);
1100 }
1101
1102 static void
1103 table_lookup(ipfw_obj_header *oh, int ac, char *av[])
1104 {
1105         ipfw_obj_tentry xtent;
1106         ipfw_xtable_info xi;
1107         char key[64];
1108         int error;
1109
1110         if (ac == 0)
1111                 errx(EX_USAGE, "address required");
1112
1113         strlcpy(key, *av, sizeof(key));
1114
1115         memset(&xi, 0, sizeof(xi));
1116         error = table_do_lookup(oh, key, &xi, &xtent);
1117
1118         switch (error) {
1119         case 0:
1120                 break;
1121         case ESRCH:
1122                 errx(EX_UNAVAILABLE, "Table %s not found", oh->ntlv.name);
1123         case ENOENT:
1124                 errx(EX_UNAVAILABLE, "Entry %s not found", *av);
1125         case ENOTSUP:
1126                 errx(EX_UNAVAILABLE, "Table %s algo does not support "
1127                     "\"lookup\" method", oh->ntlv.name);
1128         default:
1129                 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XFIND)");
1130         }
1131
1132         table_show_entry(&xi, &xtent);
1133 }
1134
1135 static void
1136 tentry_fill_key_type(char *arg, ipfw_obj_tentry *tentry, uint8_t type,
1137     uint8_t tflags)
1138 {
1139         char *p, *pp;
1140         int mask, af;
1141         struct in6_addr *paddr, tmp;
1142         struct tflow_entry *tfe;
1143         uint32_t key, *pkey;
1144         uint16_t port;
1145         struct protoent *pent;
1146         struct servent *sent;
1147         int masklen;
1148
1149         masklen = 0;
1150         af = 0;
1151         paddr = (struct in6_addr *)&tentry->k;
1152
1153         switch (type) {
1154         case IPFW_TABLE_ADDR:
1155                 /* Remove / if exists */
1156                 if ((p = strchr(arg, '/')) != NULL) {
1157                         *p = '\0';
1158                         mask = atoi(p + 1);
1159                 }
1160
1161                 if (inet_pton(AF_INET, arg, paddr) == 1) {
1162                         if (p != NULL && mask > 32)
1163                                 errx(EX_DATAERR, "bad IPv4 mask width: %s",
1164                                     p + 1);
1165
1166                         masklen = p ? mask : 32;
1167                         af = AF_INET;
1168                 } else if (inet_pton(AF_INET6, arg, paddr) == 1) {
1169                         if (IN6_IS_ADDR_V4COMPAT(paddr))
1170                                 errx(EX_DATAERR,
1171                                     "Use IPv4 instead of v4-compatible");
1172                         if (p != NULL && mask > 128)
1173                                 errx(EX_DATAERR, "bad IPv6 mask width: %s",
1174                                     p + 1);
1175
1176                         masklen = p ? mask : 128;
1177                         af = AF_INET6;
1178                 } else {
1179                         /* Assume FQDN */
1180                         if (lookup_host(arg, (struct in_addr *)paddr) != 0)
1181                                 errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
1182
1183                         masklen = 32;
1184                         type = IPFW_TABLE_ADDR;
1185                         af = AF_INET;
1186                 }
1187                 break;
1188         case IPFW_TABLE_INTERFACE:
1189                 /* Assume interface name. Copy significant data only */
1190                 mask = MIN(strlen(arg), IF_NAMESIZE - 1);
1191                 memcpy(paddr, arg, mask);
1192                 /* Set mask to exact match */
1193                 masklen = 8 * IF_NAMESIZE;
1194                 break;
1195         case IPFW_TABLE_NUMBER:
1196                 /* Port or any other key */
1197                 key = strtol(arg, &p, 10);
1198                 if (*p != '\0')
1199                         errx(EX_DATAERR, "Invalid number: %s", arg);
1200
1201                 pkey = (uint32_t *)paddr;
1202                 *pkey = key;
1203                 masklen = 32;
1204                 break;
1205         case IPFW_TABLE_FLOW:
1206                 /* Assume [src-ip][,proto][,src-port][,dst-ip][,dst-port] */
1207                 tfe = &tentry->k.flow;
1208                 af = 0;
1209
1210                 /* Handle <ipv4|ipv6> */
1211                 if ((tflags & IPFW_TFFLAG_SRCIP) != 0) {
1212                         if ((p = strchr(arg, ',')) != NULL)
1213                                 *p++ = '\0';
1214                         /* Determine family using temporary storage */
1215                         if (inet_pton(AF_INET, arg, &tmp) == 1) {
1216                                 if (af != 0 && af != AF_INET)
1217                                         errx(EX_DATAERR,
1218                                             "Inconsistent address family\n");
1219                                 af = AF_INET;
1220                                 memcpy(&tfe->a.a4.sip, &tmp, 4);
1221                         } else if (inet_pton(AF_INET6, arg, &tmp) == 1) {
1222                                 if (af != 0 && af != AF_INET6)
1223                                         errx(EX_DATAERR,
1224                                             "Inconsistent address family\n");
1225                                 af = AF_INET6;
1226                                 memcpy(&tfe->a.a6.sip6, &tmp, 16);
1227                         }
1228
1229                         arg = p;
1230                 }
1231
1232                 /* Handle <proto-num|proto-name> */
1233                 if ((tflags & IPFW_TFFLAG_PROTO) != 0) {
1234                         if (arg == NULL)
1235                                 errx(EX_DATAERR, "invalid key: proto missing");
1236                         if ((p = strchr(arg, ',')) != NULL)
1237                                 *p++ = '\0';
1238
1239                         key = strtol(arg, &pp, 10);
1240                         if (*pp != '\0') {
1241                                 if ((pent = getprotobyname(arg)) == NULL)
1242                                         errx(EX_DATAERR, "Unknown proto: %s",
1243                                             arg);
1244                                 else
1245                                         key = pent->p_proto;
1246                         }
1247                         
1248                         if (key > 255)
1249                                 errx(EX_DATAERR, "Bad protocol number: %u",key);
1250
1251                         tfe->proto = key;
1252
1253                         arg = p;
1254                 }
1255
1256                 /* Handle <port-num|service-name> */
1257                 if ((tflags & IPFW_TFFLAG_SRCPORT) != 0) {
1258                         if (arg == NULL)
1259                                 errx(EX_DATAERR, "invalid key: src port missing");
1260                         if ((p = strchr(arg, ',')) != NULL)
1261                                 *p++ = '\0';
1262
1263                         if ((port = htons(strtol(arg, NULL, 10))) == 0) {
1264                                 if ((sent = getservbyname(arg, NULL)) == NULL)
1265                                         errx(EX_DATAERR, "Unknown service: %s",
1266                                             arg);
1267                                 else
1268                                         key = sent->s_port;
1269                         }
1270                         
1271                         tfe->sport = port;
1272
1273                         arg = p;
1274                 }
1275
1276                 /* Handle <ipv4|ipv6>*/
1277                 if ((tflags & IPFW_TFFLAG_DSTIP) != 0) {
1278                         if (arg == NULL)
1279                                 errx(EX_DATAERR, "invalid key: dst ip missing");
1280                         if ((p = strchr(arg, ',')) != NULL)
1281                                 *p++ = '\0';
1282                         /* Determine family using temporary storage */
1283                         if (inet_pton(AF_INET, arg, &tmp) == 1) {
1284                                 if (af != 0 && af != AF_INET)
1285                                         errx(EX_DATAERR,
1286                                             "Inconsistent address family");
1287                                 af = AF_INET;
1288                                 memcpy(&tfe->a.a4.dip, &tmp, 4);
1289                         } else if (inet_pton(AF_INET6, arg, &tmp) == 1) {
1290                                 if (af != 0 && af != AF_INET6)
1291                                         errx(EX_DATAERR,
1292                                             "Inconsistent address family");
1293                                 af = AF_INET6;
1294                                 memcpy(&tfe->a.a6.dip6, &tmp, 16);
1295                         }
1296
1297                         arg = p;
1298                 }
1299
1300                 /* Handle <port-num|service-name> */
1301                 if ((tflags & IPFW_TFFLAG_DSTPORT) != 0) {
1302                         if (arg == NULL)
1303                                 errx(EX_DATAERR, "invalid key: dst port missing");
1304                         if ((p = strchr(arg, ',')) != NULL)
1305                                 *p++ = '\0';
1306
1307                         if ((port = htons(strtol(arg, NULL, 10))) == 0) {
1308                                 if ((sent = getservbyname(arg, NULL)) == NULL)
1309                                         errx(EX_DATAERR, "Unknown service: %s",
1310                                             arg);
1311                                 else
1312                                         key = sent->s_port;
1313                         }
1314                         
1315                         tfe->dport = port;
1316
1317                         arg = p;
1318                 }
1319
1320                 tfe->af = af;
1321
1322                 break;
1323         
1324         default:
1325                 errx(EX_DATAERR, "Unsupported table type: %d", type);
1326         }
1327
1328         tentry->subtype = af;
1329         tentry->masklen = masklen;
1330 }
1331
1332 /*
1333  * Tries to guess table key type.
1334  * This procedure is used in legacy table auto-create
1335  * code AND in `ipfw -n` ruleset checking.
1336  *
1337  * Imported from old table_fill_xentry() parse code.
1338  */
1339 static int
1340 guess_key_type(char *key, uint8_t *ptype)
1341 {
1342         char *p;
1343         struct in6_addr addr;
1344         uint32_t kv;
1345
1346         if (ishexnumber(*key) != 0 || *key == ':') {
1347                 /* Remove / if exists */
1348                 if ((p = strchr(key, '/')) != NULL)
1349                         *p = '\0';
1350
1351                 if ((inet_pton(AF_INET, key, &addr) == 1) ||
1352                     (inet_pton(AF_INET6, key, &addr) == 1)) {
1353                         *ptype = IPFW_TABLE_CIDR;
1354                         if (p != NULL)
1355                                 *p = '/';
1356                         return (0);
1357                 } else {
1358                         /* Port or any other key */
1359                         /* Skip non-base 10 entries like 'fa1' */
1360                         kv = strtol(key, &p, 10);
1361                         if (*p == '\0') {
1362                                 *ptype = IPFW_TABLE_NUMBER;
1363                                 return (0);
1364                         } else if ((p != key) && (*p == '.')) {
1365                                 /*
1366                                  * Warn on IPv4 address strings
1367                                  * which are "valid" for inet_aton() but not
1368                                  * in inet_pton().
1369                                  *
1370                                  * Typical examples: '10.5' or '10.0.0.05'
1371                                  */
1372                                 return (1);
1373                         }
1374                 }
1375         }
1376
1377         if (strchr(key, '.') == NULL) {
1378                 *ptype = IPFW_TABLE_INTERFACE;
1379                 return (0);
1380         }
1381
1382         if (lookup_host(key, (struct in_addr *)&addr) != 0)
1383                 return (1);
1384
1385         *ptype = IPFW_TABLE_CIDR;
1386         return (0);
1387 }
1388
1389 static void
1390 tentry_fill_key(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *key,
1391     int add, uint8_t *ptype, uint32_t *pvmask, ipfw_xtable_info *xi)
1392 {
1393         uint8_t type, tflags;
1394         uint32_t vmask;
1395         int error;
1396
1397         type = 0;
1398         tflags = 0;
1399         vmask = 0;
1400
1401         if (xi->tablename[0] == '\0')
1402                 error = table_get_info(oh, xi);
1403         else
1404                 error = 0;
1405
1406         if (error == 0) {
1407                 if (co.test_only == 0) {
1408                         /* Table found */
1409                         type = xi->type;
1410                         tflags = xi->tflags;
1411                         vmask = xi->vmask;
1412                 } else {
1413                         /*
1414                          * We're running `ipfw -n`
1415                          * Compatibility layer: try to guess key type
1416                          * before failing.
1417                          */
1418                         if (guess_key_type(key, &type) != 0) {
1419                                 /* Inknown key */
1420                                 errx(EX_USAGE, "Cannot guess "
1421                                     "key '%s' type", key);
1422                         }
1423                         vmask = IPFW_VTYPE_LEGACY;
1424                 }
1425         } else {
1426                 if (error != ESRCH)
1427                         errx(EX_OSERR, "Error requesting table %s info",
1428                             oh->ntlv.name);
1429                 if (add == 0)
1430                         errx(EX_DATAERR, "Table %s does not exist",
1431                             oh->ntlv.name);
1432                 /*
1433                  * Table does not exist
1434                  * Compatibility layer: try to guess key type before failing.
1435                  */
1436                 if (guess_key_type(key, &type) != 0) {
1437                         /* Inknown key */
1438                         errx(EX_USAGE, "Table %s does not exist, cannot guess "
1439                             "key '%s' type", oh->ntlv.name, key);
1440                 }
1441
1442                 vmask = IPFW_VTYPE_LEGACY;
1443         }
1444
1445         tentry_fill_key_type(key, tent, type, tflags);
1446
1447         *ptype = type;
1448         *pvmask = vmask;
1449 }
1450
1451 static void
1452 set_legacy_value(uint32_t val, ipfw_table_value *v)
1453 {
1454         v->tag = val;
1455         v->pipe = val;
1456         v->divert = val;
1457         v->skipto = val;
1458         v->netgraph = val;
1459         v->fib = val;
1460         v->nat = val;
1461         v->nh4 = val;
1462         v->dscp = (uint8_t)val;
1463         v->limit = val;
1464 }
1465
1466 static void
1467 tentry_fill_value(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *arg,
1468     uint8_t type, uint32_t vmask)
1469 {
1470         struct addrinfo hints, *res;
1471         uint32_t a4, flag, val;
1472         ipfw_table_value *v;
1473         uint32_t i;
1474         int dval;
1475         char *comma, *e, *etype, *n, *p;
1476
1477         v = &tent->v.value;
1478
1479         /* Compat layer: keep old behavior for legacy value types */
1480         if (vmask == IPFW_VTYPE_LEGACY) {
1481                 /* Try to interpret as number first */
1482                 val = strtoul(arg, &p, 0);
1483                 if (*p == '\0') {
1484                         set_legacy_value(val, v);
1485                         return;
1486                 }
1487                 if (inet_pton(AF_INET, arg, &val) == 1) {
1488                         set_legacy_value(ntohl(val), v);
1489                         return;
1490                 }
1491                 /* Try hostname */
1492                 if (lookup_host(arg, (struct in_addr *)&val) == 0) {
1493                         set_legacy_value(val, v);
1494                         return;
1495                 }
1496                 errx(EX_OSERR, "Unable to parse value %s", arg);
1497         }
1498
1499         /*
1500          * Shorthands: handle single value if vmask consists
1501          * of numbers only. e.g.:
1502          * vmask = "fib,skipto" -> treat input "1" as "1,1"
1503          */
1504
1505         n = arg;
1506         etype = NULL;
1507         for (i = 1; i < (1 << 31); i *= 2) {
1508                 if ((flag = (vmask & i)) == 0)
1509                         continue;
1510                 vmask &= ~flag;
1511
1512                 if ((comma = strchr(n, ',')) != NULL)
1513                         *comma = '\0';
1514
1515                 switch (flag) {
1516                 case IPFW_VTYPE_TAG:
1517                         v->tag = strtol(n, &e, 10);
1518                         if (*e != '\0')
1519                                 etype = "tag";
1520                         break;
1521                 case IPFW_VTYPE_PIPE:
1522                         v->pipe = strtol(n, &e, 10);
1523                         if (*e != '\0')
1524                                 etype = "pipe";
1525                         break;
1526                 case IPFW_VTYPE_DIVERT:
1527                         v->divert = strtol(n, &e, 10);
1528                         if (*e != '\0')
1529                                 etype = "divert";
1530                         break;
1531                 case IPFW_VTYPE_SKIPTO:
1532                         v->skipto = strtol(n, &e, 10);
1533                         if (*e != '\0')
1534                                 etype = "skipto";
1535                         break;
1536                 case IPFW_VTYPE_NETGRAPH:
1537                         v->netgraph = strtol(n, &e, 10);
1538                         if (*e != '\0')
1539                                 etype = "netgraph";
1540                         break;
1541                 case IPFW_VTYPE_FIB:
1542                         v->fib = strtol(n, &e, 10);
1543                         if (*e != '\0')
1544                                 etype = "fib";
1545                         break;
1546                 case IPFW_VTYPE_NAT:
1547                         v->nat = strtol(n, &e, 10);
1548                         if (*e != '\0')
1549                                 etype = "nat";
1550                         break;
1551                 case IPFW_VTYPE_LIMIT:
1552                         v->limit = strtol(n, &e, 10);
1553                         if (*e != '\0')
1554                                 etype = "limit";
1555                         break;
1556                 case IPFW_VTYPE_NH4:
1557                         if (strchr(n, '.') != NULL &&
1558                             inet_pton(AF_INET, n, &a4) == 1) {
1559                                 v->nh4 = ntohl(a4);
1560                                 break;
1561                         }
1562                         if (lookup_host(n, (struct in_addr *)&v->nh4) == 0)
1563                                 break;
1564                         etype = "ipv4";
1565                         break;
1566                 case IPFW_VTYPE_DSCP:
1567                         if (isalpha(*n)) {
1568                                 if ((dval = match_token(f_ipdscp, n)) != -1) {
1569                                         v->dscp = dval;
1570                                         break;
1571                                 } else
1572                                         etype = "DSCP code";
1573                         } else {
1574                                 v->dscp = strtol(n, &e, 10);
1575                                 if (v->dscp > 63 || *e != '\0')
1576                                         etype = "DSCP value";
1577                         }
1578                         break;
1579                 case IPFW_VTYPE_NH6:
1580                         if (strchr(n, ':') != NULL) {
1581                                 memset(&hints, 0, sizeof(hints));
1582                                 hints.ai_family = AF_INET6;
1583                                 hints.ai_flags = AI_NUMERICHOST;
1584                                 if (getaddrinfo(n, NULL, &hints, &res) == 0) {
1585                                         v->nh6 = ((struct sockaddr_in6 *)
1586                                             res->ai_addr)->sin6_addr;
1587                                         v->zoneid = ((struct sockaddr_in6 *)
1588                                             res->ai_addr)->sin6_scope_id;
1589                                         freeaddrinfo(res);
1590                                         break;
1591                                 }
1592                         }
1593                         etype = "ipv6";
1594                         break;
1595                 }
1596
1597                 if (etype != NULL)
1598                         errx(EX_USAGE, "Unable to parse %s as %s", n, etype);
1599
1600                 if (comma != NULL)
1601                         *comma++ = ',';
1602
1603                 if ((n = comma) != NULL)
1604                         continue;
1605
1606                 /* End of input. */
1607                 if (vmask != 0)
1608                         errx(EX_USAGE, "Not enough fields inside value");
1609         }
1610 }
1611
1612 /*
1613  * Compare table names.
1614  * Honor number comparison.
1615  */
1616 static int
1617 tablename_cmp(const void *a, const void *b)
1618 {
1619         ipfw_xtable_info *ia, *ib;
1620
1621         ia = (ipfw_xtable_info *)a;
1622         ib = (ipfw_xtable_info *)b;
1623
1624         return (stringnum_cmp(ia->tablename, ib->tablename));
1625 }
1626
1627 /*
1628  * Retrieves table list from kernel,
1629  * optionally sorts it and calls requested function for each table.
1630  * Returns 0 on success.
1631  */
1632 static int
1633 tables_foreach(table_cb_t *f, void *arg, int sort)
1634 {
1635         ipfw_obj_lheader *olh;
1636         ipfw_xtable_info *info;
1637         size_t sz;
1638         int i, error;
1639
1640         /* Start with reasonable default */
1641         sz = sizeof(*olh) + 16 * sizeof(ipfw_xtable_info);
1642
1643         for (;;) {
1644                 if ((olh = calloc(1, sz)) == NULL)
1645                         return (ENOMEM);
1646
1647                 olh->size = sz;
1648                 if (do_get3(IP_FW_TABLES_XLIST, &olh->opheader, &sz) != 0) {
1649                         sz = olh->size;
1650                         free(olh);
1651                         if (errno != ENOMEM)
1652                                 return (errno);
1653                         continue;
1654                 }
1655
1656                 if (sort != 0)
1657                         qsort(olh + 1, olh->count, olh->objsize,
1658                             tablename_cmp);
1659
1660                 info = (ipfw_xtable_info *)(olh + 1);
1661                 for (i = 0; i < olh->count; i++) {
1662                         if (co.use_set == 0 || info->set == co.use_set - 1)
1663                                 error = f(info, arg);
1664                         info = (ipfw_xtable_info *)((caddr_t)info +
1665                             olh->objsize);
1666                 }
1667                 free(olh);
1668                 break;
1669         }
1670         return (0);
1671 }
1672
1673
1674 /*
1675  * Retrieves all entries for given table @i in
1676  * eXtended format. Allocate buffer large enough
1677  * to store result. Called needs to free it later.
1678  *
1679  * Returns 0 on success.
1680  */
1681 static int
1682 table_do_get_list(ipfw_xtable_info *i, ipfw_obj_header **poh)
1683 {
1684         ipfw_obj_header *oh;
1685         size_t sz;
1686         int c;
1687
1688         sz = 0;
1689         oh = NULL;
1690         for (c = 0; c < 8; c++) {
1691                 if (sz < i->size)
1692                         sz = i->size + 44;
1693                 if (oh != NULL)
1694                         free(oh);
1695                 if ((oh = calloc(1, sz)) == NULL)
1696                         continue;
1697                 table_fill_objheader(oh, i);
1698                 oh->opheader.version = 1; /* Current version */
1699                 if (do_get3(IP_FW_TABLE_XLIST, &oh->opheader, &sz) == 0) {
1700                         *poh = oh;
1701                         return (0);
1702                 }
1703
1704                 if (errno != ENOMEM)
1705                         break;
1706         }
1707         free(oh);
1708
1709         return (errno);
1710 }
1711
1712 /*
1713  * Shows all entries from @oh in human-readable format
1714  */
1715 static void
1716 table_show_list(ipfw_obj_header *oh, int need_header)
1717 {
1718         ipfw_obj_tentry *tent;
1719         uint32_t count;
1720         ipfw_xtable_info *i;
1721
1722         i = (ipfw_xtable_info *)(oh + 1);
1723         tent = (ipfw_obj_tentry *)(i + 1);
1724
1725         if (need_header)
1726                 printf("--- table(%s), set(%u) ---\n", i->tablename, i->set);
1727
1728         count = i->count;
1729         while (count > 0) {
1730                 table_show_entry(i, tent);
1731                 tent = (ipfw_obj_tentry *)((caddr_t)tent + tent->head.length);
1732                 count--;
1733         }
1734 }
1735
1736 static void
1737 table_show_value(char *buf, size_t bufsize, ipfw_table_value *v,
1738     uint32_t vmask, int print_ip)
1739 {
1740         char abuf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1741         struct sockaddr_in6 sa6;
1742         uint32_t flag, i, l;
1743         size_t sz;
1744         struct in_addr a4;
1745
1746         sz = bufsize;
1747
1748         /*
1749          * Some shorthands for printing values:
1750          * legacy assumes all values are equal, so keep the first one.
1751          */
1752         if (vmask == IPFW_VTYPE_LEGACY) {
1753                 if (print_ip != 0) {
1754                         flag = htonl(v->tag);
1755                         inet_ntop(AF_INET, &flag, buf, sz);
1756                 } else
1757                         snprintf(buf, sz, "%u", v->tag);
1758                 return;
1759         }
1760
1761         for (i = 1; i < (1 << 31); i *= 2) {
1762                 if ((flag = (vmask & i)) == 0)
1763                         continue;
1764                 l = 0;
1765
1766                 switch (flag) {
1767                 case IPFW_VTYPE_TAG:
1768                         l = snprintf(buf, sz, "%u,", v->tag);
1769                         break;
1770                 case IPFW_VTYPE_PIPE:
1771                         l = snprintf(buf, sz, "%u,", v->pipe);
1772                         break;
1773                 case IPFW_VTYPE_DIVERT:
1774                         l = snprintf(buf, sz, "%d,", v->divert);
1775                         break;
1776                 case IPFW_VTYPE_SKIPTO:
1777                         l = snprintf(buf, sz, "%d,", v->skipto);
1778                         break;
1779                 case IPFW_VTYPE_NETGRAPH:
1780                         l = snprintf(buf, sz, "%u,", v->netgraph);
1781                         break;
1782                 case IPFW_VTYPE_FIB:
1783                         l = snprintf(buf, sz, "%u,", v->fib);
1784                         break;
1785                 case IPFW_VTYPE_NAT:
1786                         l = snprintf(buf, sz, "%u,", v->nat);
1787                         break;
1788                 case IPFW_VTYPE_LIMIT:
1789                         l = snprintf(buf, sz, "%u,", v->limit);
1790                         break;
1791                 case IPFW_VTYPE_NH4:
1792                         a4.s_addr = htonl(v->nh4);
1793                         inet_ntop(AF_INET, &a4, abuf, sizeof(abuf));
1794                         l = snprintf(buf, sz, "%s,", abuf);
1795                         break;
1796                 case IPFW_VTYPE_DSCP:
1797                         l = snprintf(buf, sz, "%d,", v->dscp);
1798                         break;
1799                 case IPFW_VTYPE_NH6:
1800                         sa6.sin6_family = AF_INET6;
1801                         sa6.sin6_len = sizeof(sa6);
1802                         sa6.sin6_addr = v->nh6;
1803                         sa6.sin6_port = 0;
1804                         sa6.sin6_scope_id = v->zoneid;
1805                         if (getnameinfo((const struct sockaddr *)&sa6,
1806                             sa6.sin6_len, abuf, sizeof(abuf), NULL, 0,
1807                             NI_NUMERICHOST) == 0)
1808                                 l = snprintf(buf, sz, "%s,", abuf);
1809                         break;
1810                 }
1811
1812                 buf += l;
1813                 sz -= l;
1814         }
1815
1816         if (sz != bufsize)
1817                 *(buf - 1) = '\0';
1818 }
1819
1820 static void
1821 table_show_entry(ipfw_xtable_info *i, ipfw_obj_tentry *tent)
1822 {
1823         char *comma, tbuf[128], pval[128];
1824         void *paddr;
1825         struct tflow_entry *tfe;
1826
1827         table_show_value(pval, sizeof(pval), &tent->v.value, i->vmask,
1828             co.do_value_as_ip);
1829
1830         switch (i->type) {
1831         case IPFW_TABLE_ADDR:
1832                 /* IPv4 or IPv6 prefixes */
1833                 inet_ntop(tent->subtype, &tent->k, tbuf, sizeof(tbuf));
1834                 printf("%s/%u %s\n", tbuf, tent->masklen, pval);
1835                 break;
1836         case IPFW_TABLE_INTERFACE:
1837                 /* Interface names */
1838                 printf("%s %s\n", tent->k.iface, pval);
1839                 break;
1840         case IPFW_TABLE_NUMBER:
1841                 /* numbers */
1842                 printf("%u %s\n", tent->k.key, pval);
1843                 break;
1844         case IPFW_TABLE_FLOW:
1845                 /* flows */
1846                 tfe = &tent->k.flow;
1847                 comma = "";
1848
1849                 if ((i->tflags & IPFW_TFFLAG_SRCIP) != 0) {
1850                         if (tfe->af == AF_INET)
1851                                 paddr = &tfe->a.a4.sip;
1852                         else
1853                                 paddr = &tfe->a.a6.sip6;
1854
1855                         inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1856                         printf("%s%s", comma, tbuf);
1857                         comma = ",";
1858                 }
1859
1860                 if ((i->tflags & IPFW_TFFLAG_PROTO) != 0) {
1861                         printf("%s%d", comma, tfe->proto);
1862                         comma = ",";
1863                 }
1864
1865                 if ((i->tflags & IPFW_TFFLAG_SRCPORT) != 0) {
1866                         printf("%s%d", comma, ntohs(tfe->sport));
1867                         comma = ",";
1868                 }
1869                 if ((i->tflags & IPFW_TFFLAG_DSTIP) != 0) {
1870                         if (tfe->af == AF_INET)
1871                                 paddr = &tfe->a.a4.dip;
1872                         else
1873                                 paddr = &tfe->a.a6.dip6;
1874
1875                         inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1876                         printf("%s%s", comma, tbuf);
1877                         comma = ",";
1878                 }
1879
1880                 if ((i->tflags & IPFW_TFFLAG_DSTPORT) != 0) {
1881                         printf("%s%d", comma, ntohs(tfe->dport));
1882                         comma = ",";
1883                 }
1884
1885                 printf(" %s\n", pval);
1886         }
1887 }
1888
1889 static int
1890 table_do_get_stdlist(uint16_t opcode, ipfw_obj_lheader **polh)
1891 {
1892         ipfw_obj_lheader req, *olh;
1893         size_t sz;
1894
1895         memset(&req, 0, sizeof(req));
1896         sz = sizeof(req);
1897
1898         if (do_get3(opcode, &req.opheader, &sz) != 0)
1899                 if (errno != ENOMEM)
1900                         return (errno);
1901
1902         sz = req.size;
1903         if ((olh = calloc(1, sz)) == NULL)
1904                 return (ENOMEM);
1905
1906         olh->size = sz;
1907         if (do_get3(opcode, &olh->opheader, &sz) != 0) {
1908                 free(olh);
1909                 return (errno);
1910         }
1911
1912         *polh = olh;
1913         return (0);
1914 }
1915
1916 static int
1917 table_do_get_algolist(ipfw_obj_lheader **polh)
1918 {
1919
1920         return (table_do_get_stdlist(IP_FW_TABLES_ALIST, polh));
1921 }
1922
1923 static int
1924 table_do_get_vlist(ipfw_obj_lheader **polh)
1925 {
1926
1927         return (table_do_get_stdlist(IP_FW_TABLE_VLIST, polh));
1928 }
1929
1930 void
1931 ipfw_list_ta(int ac, char *av[])
1932 {
1933         ipfw_obj_lheader *olh;
1934         ipfw_ta_info *info;
1935         int error, i;
1936         const char *atype;
1937
1938         error = table_do_get_algolist(&olh);
1939         if (error != 0)
1940                 err(EX_OSERR, "Unable to request algorithm list");
1941
1942         info = (ipfw_ta_info *)(olh + 1);
1943         for (i = 0; i < olh->count; i++) {
1944                 if ((atype = match_value(tabletypes, info->type)) == NULL)
1945                         atype = "unknown";
1946                 printf("--- %s ---\n", info->algoname);
1947                 printf(" type: %s\n refcount: %u\n", atype, info->refcnt);
1948
1949                 info = (ipfw_ta_info *)((caddr_t)info + olh->objsize);
1950         }
1951
1952         free(olh);
1953 }
1954
1955
1956 /* Copy of current kernel table_value structure */
1957 struct _table_value {
1958         uint32_t        tag;            /* O_TAG/O_TAGGED */
1959         uint32_t        pipe;           /* O_PIPE/O_QUEUE */
1960         uint16_t        divert;         /* O_DIVERT/O_TEE */
1961         uint16_t        skipto;         /* skipto, CALLRET */
1962         uint32_t        netgraph;       /* O_NETGRAPH/O_NGTEE */
1963         uint32_t        fib;            /* O_SETFIB */
1964         uint32_t        nat;            /* O_NAT */
1965         uint32_t        nh4;
1966         uint8_t         dscp;
1967         uint8_t         spare0;
1968         uint16_t        spare1;
1969         /* -- 32 bytes -- */
1970         struct in6_addr nh6;
1971         uint32_t        limit;          /* O_LIMIT */
1972         uint32_t        zoneid;
1973         uint64_t        refcnt;         /* Number of references */
1974 };
1975
1976 int
1977 compare_values(const void *_a, const void *_b)
1978 {
1979         struct _table_value *a, *b;
1980
1981         a = (struct _table_value *)_a;
1982         b = (struct _table_value *)_b;
1983
1984         if (a->spare1 < b->spare1)
1985                 return (-1);
1986         else if (a->spare1 > b->spare1)
1987                 return (1);
1988
1989         return (0);
1990 }
1991
1992 void
1993 ipfw_list_values(int ac, char *av[])
1994 {
1995         ipfw_obj_lheader *olh;
1996         struct _table_value *v;
1997         int error, i;
1998         uint32_t vmask;
1999         char buf[128];
2000
2001         error = table_do_get_vlist(&olh);
2002         if (error != 0)
2003                 err(EX_OSERR, "Unable to request value list");
2004
2005         vmask = 0x7FFFFFFF; /* Similar to IPFW_VTYPE_LEGACY */
2006
2007         table_print_valheader(buf, sizeof(buf), vmask);
2008         printf("HEADER: %s\n", buf);
2009         v = (struct _table_value *)(olh + 1);
2010         qsort(v, olh->count, olh->objsize, compare_values);
2011         for (i = 0; i < olh->count; i++) {
2012                 table_show_value(buf, sizeof(buf), (ipfw_table_value *)v,
2013                     vmask, 0);
2014                 printf("[%u] refs=%lu %s\n", v->spare1, (u_long)v->refcnt, buf);
2015                 v = (struct _table_value *)((caddr_t)v + olh->objsize);
2016         }
2017
2018         free(olh);
2019 }
2020
2021 int
2022 table_check_name(const char *tablename)
2023 {
2024
2025         if (ipfw_check_object_name(tablename) != 0)
2026                 return (EINVAL);
2027         /* Restrict some 'special' names */
2028         if (strcmp(tablename, "all") == 0)
2029                 return (EINVAL);
2030         return (0);
2031 }
2032