1 /* Library which manipulates firewall rules. Version $Revision$ */
3 /* Architecture of firewall rules is as follows:
5 * Chains go INPUT, FORWARD, OUTPUT then user chains.
6 * Each user chain starts with an ERROR node.
7 * Every chain ends with an unconditional jump: a RETURN for user chains,
8 * and a POLICY for built-ins.
11 /* (C) 1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See
12 * COPYING for details).
13 * (C) 2000-2004 by the Netfilter Core Team <coreteam@netfilter.org>
15 * 2003-Jun-20: Harald Welte <laforge@netfilter.org>:
16 * - Reimplementation of chain cache to use offsets instead of entries
17 * 2003-Jun-23: Harald Welte <laforge@netfilter.org>:
18 * - performance optimization, sponsored by Astaro AG (http://www.astaro.com/)
19 * don't rebuild the chain cache after every operation, instead fix it
20 * up after a ruleset change.
21 * 2004-Aug-18: Harald Welte <laforge@netfilter.org>:
22 * - futher performance work: total reimplementation of libiptc.
23 * - libiptc now has a real internal (linked-list) represntation of the
24 * ruleset and a parser/compiler from/to this internal representation
25 * - again sponsored by Astaro AG (http://www.astaro.com/)
27 #include <sys/types.h>
28 #include <sys/socket.h>
31 #include "linux_list.h"
33 //#define IPTC_DEBUG2 1
37 #define DEBUGP(x, args...) fprintf(stderr, "%s: " x, __FUNCTION__, ## args)
38 #define DEBUGP_C(x, args...) fprintf(stderr, x, ## args)
40 #define DEBUGP(x, args...)
41 #define DEBUGP_C(x, args...)
45 #define debug(x, args...) fprintf(stderr, x, ## args)
47 #define debug(x, args...)
50 static int sockfd = -1;
51 static int sockfd_use = 0;
52 static void *iptc_fn = NULL;
54 static const char *hooknames[] = {
55 [HOOK_PRE_ROUTING] = "PREROUTING",
56 [HOOK_LOCAL_IN] = "INPUT",
57 [HOOK_FORWARD] = "FORWARD",
58 [HOOK_LOCAL_OUT] = "OUTPUT",
59 [HOOK_POST_ROUTING] = "POSTROUTING",
61 [HOOK_DROPPING] = "DROPPING"
65 /* Convenience structures */
66 struct ipt_error_target
68 STRUCT_ENTRY_TARGET t;
69 char error[TABLE_MAXNAMELEN];
79 COUNTER_MAP_NORMAL_MAP,
86 enum iptcc_rule_type {
87 IPTCC_R_STANDARD, /* standard target (ACCEPT, ...) */
88 IPTCC_R_MODULE, /* extension module (SNAT, ...) */
89 IPTCC_R_FALLTHROUGH, /* fallthrough rule */
90 IPTCC_R_JUMP, /* jump to other chain */
95 struct list_head list;
96 struct chain_head *chain;
97 struct counter_map counter_map;
99 unsigned int index; /* index (needed for counter_map) */
100 unsigned int offset; /* offset in rule blob */
102 enum iptcc_rule_type type;
103 struct chain_head *jump; /* jump target, if IPTCC_R_JUMP */
105 unsigned int size; /* size of entry data */
106 STRUCT_ENTRY entry[0];
111 struct list_head list;
112 char name[TABLE_MAXNAMELEN];
113 unsigned int hooknum; /* hook number+1 if builtin */
114 unsigned int references; /* how many jumps reference us */
115 int verdict; /* verdict if builtin */
117 STRUCT_COUNTERS counters; /* per-chain counters */
118 struct counter_map counter_map;
120 unsigned int num_rules; /* number of rules in list */
121 struct list_head rules; /* list of rules */
123 unsigned int index; /* index (needed for jump resolval) */
124 unsigned int head_offset; /* offset in rule blob */
125 unsigned int foot_index; /* index (needed for counter_map) */
126 unsigned int foot_offset; /* offset in rule blob */
131 int changed; /* Have changes been made? */
133 struct list_head chains;
135 struct chain_head *chain_iterator_cur;
136 struct rule_head *rule_iterator_cur;
138 unsigned int num_chains; /* number of user defined chains */
140 struct chain_head **chain_index; /* array for fast chain list access*/
141 unsigned int chain_index_sz;/* size of chain index array */
144 STRUCT_GET_ENTRIES *entries;
147 /* allocate a new chain head for the cache */
148 static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum)
150 struct chain_head *c = malloc(sizeof(*c));
153 memset(c, 0, sizeof(*c));
155 strncpy(c->name, name, TABLE_MAXNAMELEN);
156 c->hooknum = hooknum;
157 INIT_LIST_HEAD(&c->rules);
162 /* allocate and initialize a new rule for the cache */
163 static struct rule_head *iptcc_alloc_rule(struct chain_head *c, unsigned int size)
165 struct rule_head *r = malloc(sizeof(*r)+size);
168 memset(r, 0, sizeof(*r));
176 /* notify us that the ruleset has been modified by the user */
178 set_changed(TC_HANDLE_T h)
184 static void do_check(TC_HANDLE_T h, unsigned int line);
185 #define CHECK(h) do { if (!getenv("IPTC_NO_CHECK")) do_check((h), __LINE__); } while(0)
191 /**********************************************************************
192 * iptc blob utility functions (iptcb_*)
193 **********************************************************************/
196 iptcb_get_number(const STRUCT_ENTRY *i,
197 const STRUCT_ENTRY *seek,
207 iptcb_get_entry_n(STRUCT_ENTRY *i,
212 if (*pos == number) {
220 static inline STRUCT_ENTRY *
221 iptcb_get_entry(TC_HANDLE_T h, unsigned int offset)
223 return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset);
227 iptcb_entry2index(const TC_HANDLE_T h, const STRUCT_ENTRY *seek)
229 unsigned int pos = 0;
231 if (ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
232 iptcb_get_number, seek, &pos) == 0) {
233 fprintf(stderr, "ERROR: offset %u not an entry!\n",
234 (unsigned int)((char *)seek - (char *)h->entries->entrytable));
240 static inline STRUCT_ENTRY *
241 iptcb_offset2entry(TC_HANDLE_T h, unsigned int offset)
243 return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset);
247 static inline unsigned long
248 iptcb_entry2offset(const TC_HANDLE_T h, const STRUCT_ENTRY *e)
250 return (void *)e - (void *)h->entries->entrytable;
253 static inline unsigned int
254 iptcb_offset2index(const TC_HANDLE_T h, unsigned int offset)
256 return iptcb_entry2index(h, iptcb_offset2entry(h, offset));
259 /* Returns 0 if not hook entry, else hooknumber + 1 */
260 static inline unsigned int
261 iptcb_ent_is_hook_entry(STRUCT_ENTRY *e, TC_HANDLE_T h)
265 for (i = 0; i < NUMHOOKS; i++) {
266 if ((h->info.valid_hooks & (1 << i))
267 && iptcb_get_entry(h, h->info.hook_entry[i]) == e)
274 /**********************************************************************
275 * Chain index (cache utility) functions
276 **********************************************************************
277 * The chain index is an array with pointers into the chain list, with
278 * CHAIN_INDEX_BUCKET_LEN spacing. This facilitates the ability to
279 * speedup chain list searching, by find a more optimal starting
280 * points when searching the linked list.
282 * The starting point can be found fast by using a binary search of
283 * the chain index. Thus, reducing the previous search complexity of
284 * O(n) to O(log(n/k) + k) where k is CHAIN_INDEX_BUCKET_LEN.
286 * A nice property of the chain index, is that the "bucket" list
287 * length is max CHAIN_INDEX_BUCKET_LEN (when just build, inserts will
288 * change this). Oppose to hashing, where the "bucket" list length can
291 #ifndef CHAIN_INDEX_BUCKET_LEN
292 #define CHAIN_INDEX_BUCKET_LEN 40
295 /* Another nice property of the chain index is that inserting/creating
296 * chains in chain list don't change the correctness of the chain
297 * index, it only causes longer lists in the buckets.
299 * To mitigate the performance penalty of longer bucket lists and the
300 * penalty of rebuilding, the chain index is rebuild only when
301 * CHAIN_INDEX_INSERT_MAX chains has been added.
303 #ifndef CHAIN_INDEX_INSERT_MAX
304 #define CHAIN_INDEX_INSERT_MAX 355
307 static inline unsigned int iptcc_is_builtin(struct chain_head *c);
310 /* Use binary search in the chain index array, to find a chain_head
311 * pointer closest to the place of the searched name element.
313 * Notes that, binary search (obviously) requires that the chain list
316 static struct list_head *
317 iptcc_bsearch_chain_index(const char *name, unsigned int *idx, TC_HANDLE_T handle)
319 unsigned int pos, end;
322 struct list_head *list_pos;
323 list_pos=&handle->chains;
325 /* Check for empty array, e.g. no user defined chains */
326 if (handle->chain_index_sz == 0) {
327 debug("WARNING: handle->chain_index_sz == 0\n");
332 end = handle->chain_index_sz;
335 debug("bsearch Find chain:%s (pos:%d end:%d)\n", name, pos, end);
339 if (!handle->chain_index[pos]) {
340 fprintf(stderr, "ERROR: NULL pointer chain_index[%d]\n", pos);
341 return &handle->chains; /* Be safe, return orig start pos */
344 res = strcmp(name, handle->chain_index[pos]->name);
345 list_pos = &handle->chain_index[pos]->list;
348 debug("bsearch Index[%d] name:%s res:%d ",
349 pos, handle->chain_index[pos]->name, res);
351 if (res == 0) { /* Found element, by direct hit */
352 debug("[found] Direct hit pos:%d end:%d\n", pos, end);
354 } else if (res < 0) { /* Too far, jump back */
358 /* Exit case: First element of array */
360 debug("[found] Reached first array elem (end%d)\n",end);
363 debug("jump back to pos:%d (end:%d)\n", pos, end);
365 } else if (res > 0 ){ /* Not far enough, jump forward */
367 /* Exit case: Last element of array */
368 if (pos == handle->chain_index_sz-1) {
369 debug("[found] Last array elem (end:%d)\n", end);
373 /* Exit case: Next index less, thus elem in this list section */
374 res = strcmp(name, handle->chain_index[pos+1]->name);
376 debug("[found] closest list (end:%d)\n", end);
381 debug("jump forward to pos:%d (end:%d)\n", pos, end);
389 /* Trivial linear search of chain index. Function used for verifying
390 the output of bsearch function */
391 static struct list_head *
392 iptcc_linearly_search_chain_index(const char *name, TC_HANDLE_T handle)
397 struct list_head *list_pos;
398 list_pos = &handle->chains;
400 if (handle->chain_index_sz)
401 list_pos = &handle->chain_index[0]->list;
403 /* Linearly walk of chain index array */
405 for (i=0; i < handle->chain_index_sz; i++) {
406 if (handle->chain_index[i]) {
407 res = strcmp(handle->chain_index[i]->name, name);
409 break; // One step too far
410 list_pos = &handle->chain_index[i]->list;
420 static int iptcc_chain_index_alloc(TC_HANDLE_T h)
422 unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
423 unsigned int array_elems;
424 unsigned int array_mem;
426 /* Allocate memory for the chain index array */
427 array_elems = (h->num_chains / list_length) +
428 (h->num_chains % list_length ? 1 : 0);
429 array_mem = sizeof(h->chain_index) * array_elems;
431 debug("Alloc Chain index, elems:%d mem:%d bytes\n",
432 array_elems, array_mem);
434 h->chain_index = malloc(array_mem);
435 if (!h->chain_index) {
436 h->chain_index_sz = 0;
439 memset(h->chain_index, 0, array_mem);
440 h->chain_index_sz = array_elems;
445 static void iptcc_chain_index_free(TC_HANDLE_T h)
447 h->chain_index_sz = 0;
448 free(h->chain_index);
453 static void iptcc_chain_index_dump(TC_HANDLE_T h)
457 /* Dump: contents of chain index array */
458 for (i=0; i < h->chain_index_sz; i++) {
459 if (h->chain_index[i]) {
460 fprintf(stderr, "Chain index[%d].name: %s\n",
461 i, h->chain_index[i]->name);
467 /* Build the chain index */
468 static int iptcc_chain_index_build(TC_HANDLE_T h)
470 unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
471 unsigned int chains = 0;
472 unsigned int cindex = 0;
473 struct chain_head *c;
475 /* Build up the chain index array here */
476 debug("Building chain index\n");
478 debug("Number of user defined chains:%d bucket_sz:%d array_sz:%d\n",
479 h->num_chains, list_length, h->chain_index_sz);
481 if (h->chain_index_sz == 0)
484 list_for_each_entry(c, &h->chains, list) {
486 /* Issue: The index array needs to start after the
487 * builtin chains, as they are not sorted */
488 if (!iptcc_is_builtin(c)) {
489 cindex=chains / list_length;
491 /* Safe guard, break out on array limit, this
492 * is useful if chains are added and array is
493 * rebuild, without realloc of memory. */
494 if (cindex >= h->chain_index_sz)
497 if ((chains % list_length)== 0) {
498 debug("\nIndex[%d] Chains:", cindex);
499 h->chain_index[cindex] = c;
503 debug("%s, ", c->name);
510 static int iptcc_chain_index_rebuild(TC_HANDLE_T h)
512 debug("REBUILD chain index array\n");
513 iptcc_chain_index_free(h);
514 if ((iptcc_chain_index_alloc(h)) < 0)
516 iptcc_chain_index_build(h);
520 /* Delete chain (pointer) from index array. Removing an element from
521 * the chain list only affects the chain index array, if the chain
522 * index points-to/uses that list pointer.
524 * There are different strategies, the simple and safe is to rebuild
525 * the chain index every time. The more advanced is to update the
526 * array index to point to the next element, but that requires some
527 * house keeping and boundry checks. The advanced is implemented, as
528 * the simple approach behaves badly when all chains are deleted
529 * because list_for_each processing will always hit the first chain
530 * index, thus causing a rebuild for every chain.
532 static int iptcc_chain_index_delete_chain(struct chain_head *c, TC_HANDLE_T h)
534 struct list_head *index_ptr, *index_ptr2, *next;
535 struct chain_head *c2;
536 unsigned int idx, idx2;
538 index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h);
540 debug("Del chain[%s] c->list:%p index_ptr:%p\n",
541 c->name, &c->list, index_ptr);
543 /* Save the next pointer */
547 if (index_ptr == &c->list) { /* Chain used as index ptr */
549 /* See if its possible to avoid a rebuild, by shifting
550 * to next pointer. Its possible if the next pointer
551 * is located in the same index bucket.
553 c2 = list_entry(next, struct chain_head, list);
554 index_ptr2 = iptcc_bsearch_chain_index(c2->name, &idx2, h);
557 return iptcc_chain_index_rebuild(h);
559 /* Avoiding rebuild */
560 debug("Update cindex[%d] with next ptr name:[%s]\n",
562 h->chain_index[idx]=c2;
570 /**********************************************************************
571 * iptc cache utility functions (iptcc_*)
572 **********************************************************************/
574 /* Is the given chain builtin (1) or user-defined (0) */
575 static inline unsigned int iptcc_is_builtin(struct chain_head *c)
577 return (c->hooknum ? 1 : 0);
580 /* Get a specific rule within a chain */
581 static struct rule_head *iptcc_get_rule_num(struct chain_head *c,
582 unsigned int rulenum)
585 unsigned int num = 0;
587 list_for_each_entry(r, &c->rules, list) {
595 /* Get a specific rule within a chain backwards */
596 static struct rule_head *iptcc_get_rule_num_reverse(struct chain_head *c,
597 unsigned int rulenum)
600 unsigned int num = 0;
602 list_for_each_entry_reverse(r, &c->rules, list) {
610 /* Returns chain head if found, otherwise NULL. */
611 static struct chain_head *
612 iptcc_find_chain_by_offset(TC_HANDLE_T handle, unsigned int offset)
614 struct list_head *pos;
616 if (list_empty(&handle->chains))
619 list_for_each(pos, &handle->chains) {
620 struct chain_head *c = list_entry(pos, struct chain_head, list);
621 if (offset >= c->head_offset && offset <= c->foot_offset)
628 /* Returns chain head if found, otherwise NULL. */
629 static struct chain_head *
630 iptcc_find_label(const char *name, TC_HANDLE_T handle)
632 struct list_head *pos;
633 struct list_head *list_start_pos;
637 if (list_empty(&handle->chains))
640 /* First look at builtin chains */
641 list_for_each(pos, &handle->chains) {
642 struct chain_head *c = list_entry(pos, struct chain_head, list);
643 if (!iptcc_is_builtin(c))
645 if (!strcmp(c->name, name))
649 /* Find a smart place to start the search via chain index */
650 //list_start_pos = iptcc_linearly_search_chain_index(name, handle);
651 list_start_pos = iptcc_bsearch_chain_index(name, &i, handle);
653 /* Handel if bsearch bails out early */
654 if (list_start_pos == &handle->chains) {
655 list_start_pos = pos;
659 /* Verify result of bsearch against linearly index search */
660 struct list_head *test_pos;
661 struct chain_head *test_c, *tmp_c;
662 test_pos = iptcc_linearly_search_chain_index(name, handle);
663 if (list_start_pos != test_pos) {
664 debug("BUG in chain_index search\n");
665 test_c=list_entry(test_pos, struct chain_head,list);
666 tmp_c =list_entry(list_start_pos,struct chain_head,list);
667 debug("Verify search found:\n");
668 debug(" Chain:%s\n", test_c->name);
669 debug("BSearch found:\n");
670 debug(" Chain:%s\n", tmp_c->name);
676 /* Initial/special case, no user defined chains */
677 if (handle->num_chains == 0)
680 /* Start searching through the chain list */
681 list_for_each(pos, list_start_pos->prev) {
682 struct chain_head *c = list_entry(pos, struct chain_head, list);
683 res = strcmp(c->name, name);
684 debug("List search name:%s == %s res:%d\n", name, c->name, res);
688 /* We can stop earlier as we know list is sorted */
689 if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/
690 debug(" Not in list, walked too far, sorted list\n");
694 /* Stop on wrap around, if list head is reached */
695 if (pos == &handle->chains) {
696 debug("Stop, list head reached\n");
701 debug("List search NOT found name:%s\n", name);
705 /* called when rule is to be removed from cache */
706 static void iptcc_delete_rule(struct rule_head *r)
708 DEBUGP("deleting rule %p (offset %u)\n", r, r->offset);
709 /* clean up reference count of called chain */
710 if (r->type == IPTCC_R_JUMP
712 r->jump->references--;
719 /**********************************************************************
720 * RULESET PARSER (blob -> cache)
721 **********************************************************************/
723 /* Delete policy rule of previous chain, since cache doesn't contain
724 * chain policy rules.
725 * WARNING: This function has ugly design and relies on a lot of context, only
726 * to be called from specific places within the parser */
727 static int __iptcc_p_del_policy(TC_HANDLE_T h, unsigned int num)
729 if (h->chain_iterator_cur) {
730 /* policy rule is last rule */
731 struct rule_head *pr = (struct rule_head *)
732 h->chain_iterator_cur->rules.prev;
735 h->chain_iterator_cur->verdict =
736 *(int *)GET_TARGET(pr->entry)->data;
738 /* save counter and counter_map information */
739 h->chain_iterator_cur->counter_map.maptype =
740 COUNTER_MAP_NORMAL_MAP;
741 h->chain_iterator_cur->counter_map.mappos = num-1;
742 memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters,
743 sizeof(h->chain_iterator_cur->counters));
745 /* foot_offset points to verdict rule */
746 h->chain_iterator_cur->foot_index = num;
747 h->chain_iterator_cur->foot_offset = pr->offset;
749 /* delete rule from cache */
750 iptcc_delete_rule(pr);
751 h->chain_iterator_cur->num_rules--;
758 /* alphabetically insert a chain into the list */
759 static inline void iptc_insert_chain(TC_HANDLE_T h, struct chain_head *c)
761 struct chain_head *tmp;
762 struct list_head *list_start_pos;
765 /* Find a smart place to start the insert search */
766 list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h);
768 /* Handle the case, where chain.name is smaller than index[0] */
769 if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) {
770 h->chain_index[0] = c; /* Update chain index head */
771 list_start_pos = h->chains.next;
772 debug("Update chain_index[0] with %s\n", c->name);
775 /* Handel if bsearch bails out early */
776 if (list_start_pos == &h->chains) {
777 list_start_pos = h->chains.next;
780 /* sort only user defined chains */
782 list_for_each_entry(tmp, list_start_pos->prev, list) {
783 if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) {
784 list_add(&c->list, tmp->list.prev);
788 /* Stop if list head is reached */
789 if (&tmp->list == &h->chains) {
790 debug("Insert, list head reached add to tail\n");
796 /* survived till end of list: add at tail */
797 list_add_tail(&c->list, &h->chains);
800 /* Another ugly helper function split out of cache_add_entry to make it less
802 static void __iptcc_p_add_chain(TC_HANDLE_T h, struct chain_head *c,
803 unsigned int offset, unsigned int *num)
805 struct list_head *tail = h->chains.prev;
806 struct chain_head *ctail;
808 __iptcc_p_del_policy(h, *num);
810 c->head_offset = offset;
813 /* Chains from kernel are already sorted, as they are inserted
814 * sorted. But there exists an issue when shifting to 1.4.0
815 * from an older version, as old versions allow last created
816 * chain to be unsorted.
818 if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/
819 list_add_tail(&c->list, &h->chains);
821 ctail = list_entry(tail, struct chain_head, list);
822 if (strcmp(c->name, ctail->name) > 0)
823 list_add_tail(&c->list, &h->chains);/* Already sorted*/
825 iptc_insert_chain(h, c);/* Was not sorted */
828 h->chain_iterator_cur = c;
831 /* main parser function: add an entry from the blob to the cache */
832 static int cache_add_entry(STRUCT_ENTRY *e,
837 unsigned int builtin;
838 unsigned int offset = (char *)e - (char *)h->entries->entrytable;
840 DEBUGP("entering...");
842 /* Last entry ("policy rule"). End it.*/
843 if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) {
844 /* This is the ERROR node at the end of the chain */
845 DEBUGP_C("%u:%u: end of table:\n", *num, offset);
847 __iptcc_p_del_policy(h, *num);
849 h->chain_iterator_cur = NULL;
853 /* We know this is the start of a new chain if it's an ERROR
854 * target, or a hook entry point */
856 if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) {
857 struct chain_head *c =
858 iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0);
859 DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset,
865 h->num_chains++; /* New user defined chain */
867 __iptcc_p_add_chain(h, c, offset, num);
869 } else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) {
870 struct chain_head *c =
871 iptcc_alloc_chain_head((char *)hooknames[builtin-1],
873 DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n",
874 *num, offset, c, &c->rules);
880 c->hooknum = builtin;
882 __iptcc_p_add_chain(h, c, offset, num);
884 /* FIXME: this is ugly. */
887 /* has to be normal rule */
891 if (!(r = iptcc_alloc_rule(h->chain_iterator_cur,
896 DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r);
900 memcpy(r->entry, e, e->next_offset);
901 r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP;
902 r->counter_map.mappos = r->index;
904 /* handling of jumps, etc. */
905 if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) {
906 STRUCT_STANDARD_TARGET *t;
908 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
909 if (t->target.u.target_size
910 != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
915 if (t->verdict < 0) {
916 DEBUGP_C("standard, verdict=%d\n", t->verdict);
917 r->type = IPTCC_R_STANDARD;
918 } else if (t->verdict == r->offset+e->next_offset) {
919 DEBUGP_C("fallthrough\n");
920 r->type = IPTCC_R_FALLTHROUGH;
922 DEBUGP_C("jump, target=%u\n", t->verdict);
923 r->type = IPTCC_R_JUMP;
924 /* Jump target fixup has to be deferred
925 * until second pass, since we migh not
926 * yet have parsed the target */
929 DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name);
930 r->type = IPTCC_R_MODULE;
933 list_add_tail(&r->list, &h->chain_iterator_cur->rules);
934 h->chain_iterator_cur->num_rules++;
942 /* parse an iptables blob into it's pieces */
943 static int parse_table(TC_HANDLE_T h)
946 unsigned int num = 0;
947 struct chain_head *c;
949 /* First pass: over ruleset blob */
950 ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
951 cache_add_entry, h, &prev, &num);
953 /* Build the chain index, used for chain list search speedup */
954 if ((iptcc_chain_index_alloc(h)) < 0)
956 iptcc_chain_index_build(h);
958 /* Second pass: fixup parsed data from first pass */
959 list_for_each_entry(c, &h->chains, list) {
961 list_for_each_entry(r, &c->rules, list) {
962 struct chain_head *lc;
963 STRUCT_STANDARD_TARGET *t;
965 if (r->type != IPTCC_R_JUMP)
968 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
969 lc = iptcc_find_chain_by_offset(h, t->verdict);
977 /* FIXME: sort chains */
983 /**********************************************************************
984 * RULESET COMPILATION (cache -> blob)
985 **********************************************************************/
987 /* Convenience structures */
988 struct iptcb_chain_start{
990 struct ipt_error_target name;
992 #define IPTCB_CHAIN_START_SIZE (sizeof(STRUCT_ENTRY) + \
993 ALIGN(sizeof(struct ipt_error_target)))
995 struct iptcb_chain_foot {
997 STRUCT_STANDARD_TARGET target;
999 #define IPTCB_CHAIN_FOOT_SIZE (sizeof(STRUCT_ENTRY) + \
1000 ALIGN(sizeof(STRUCT_STANDARD_TARGET)))
1002 struct iptcb_chain_error {
1004 struct ipt_error_target target;
1006 #define IPTCB_CHAIN_ERROR_SIZE (sizeof(STRUCT_ENTRY) + \
1007 ALIGN(sizeof(struct ipt_error_target)))
1011 /* compile rule from cache into blob */
1012 static inline int iptcc_compile_rule (TC_HANDLE_T h, STRUCT_REPLACE *repl, struct rule_head *r)
1015 if (r->type == IPTCC_R_JUMP) {
1016 STRUCT_STANDARD_TARGET *t;
1017 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1018 /* memset for memcmp convenience on delete/replace */
1019 memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
1020 strcpy(t->target.u.user.name, STANDARD_TARGET);
1021 /* Jumps can only happen to builtin chains, so we
1022 * can safely assume that they always have a header */
1023 t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE;
1024 } else if (r->type == IPTCC_R_FALLTHROUGH) {
1025 STRUCT_STANDARD_TARGET *t;
1026 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1027 t->verdict = r->offset + r->size;
1030 /* copy entry from cache to blob */
1031 memcpy((char *)repl->entries+r->offset, r->entry, r->size);
1036 /* compile chain from cache into blob */
1037 static int iptcc_compile_chain(TC_HANDLE_T h, STRUCT_REPLACE *repl, struct chain_head *c)
1040 struct rule_head *r;
1041 struct iptcb_chain_start *head;
1042 struct iptcb_chain_foot *foot;
1044 /* only user-defined chains have heaer */
1045 if (!iptcc_is_builtin(c)) {
1046 /* put chain header in place */
1047 head = (void *)repl->entries + c->head_offset;
1048 head->e.target_offset = sizeof(STRUCT_ENTRY);
1049 head->e.next_offset = IPTCB_CHAIN_START_SIZE;
1050 strcpy(head->name.t.u.user.name, ERROR_TARGET);
1051 head->name.t.u.target_size =
1052 ALIGN(sizeof(struct ipt_error_target));
1053 strcpy(head->name.error, c->name);
1055 repl->hook_entry[c->hooknum-1] = c->head_offset;
1056 repl->underflow[c->hooknum-1] = c->foot_offset;
1059 /* iterate over rules */
1060 list_for_each_entry(r, &c->rules, list) {
1061 ret = iptcc_compile_rule(h, repl, r);
1066 /* put chain footer in place */
1067 foot = (void *)repl->entries + c->foot_offset;
1068 foot->e.target_offset = sizeof(STRUCT_ENTRY);
1069 foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE;
1070 strcpy(foot->target.target.u.user.name, STANDARD_TARGET);
1071 foot->target.target.u.target_size =
1072 ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1073 /* builtin targets have verdict, others return */
1074 if (iptcc_is_builtin(c))
1075 foot->target.verdict = c->verdict;
1077 foot->target.verdict = RETURN;
1078 /* set policy-counters */
1079 memcpy(&foot->e.counters, &c->counters, sizeof(STRUCT_COUNTERS));
1084 /* calculate offset and number for every rule in the cache */
1085 static int iptcc_compile_chain_offsets(TC_HANDLE_T h, struct chain_head *c,
1086 unsigned int *offset, unsigned int *num)
1088 struct rule_head *r;
1090 c->head_offset = *offset;
1091 DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset);
1093 if (!iptcc_is_builtin(c)) {
1094 /* Chain has header */
1095 *offset += sizeof(STRUCT_ENTRY)
1096 + ALIGN(sizeof(struct ipt_error_target));
1100 list_for_each_entry(r, &c->rules, list) {
1101 DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num);
1102 r->offset = *offset;
1108 DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num,
1110 c->foot_offset = *offset;
1111 c->foot_index = *num;
1112 *offset += sizeof(STRUCT_ENTRY)
1113 + ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1119 /* put the pieces back together again */
1120 static int iptcc_compile_table_prep(TC_HANDLE_T h, unsigned int *size)
1122 struct chain_head *c;
1123 unsigned int offset = 0, num = 0;
1126 /* First pass: calculate offset for every rule */
1127 list_for_each_entry(c, &h->chains, list) {
1128 ret = iptcc_compile_chain_offsets(h, c, &offset, &num);
1133 /* Append one error rule at end of chain */
1135 offset += sizeof(STRUCT_ENTRY)
1136 + ALIGN(sizeof(struct ipt_error_target));
1138 /* ruleset size is now in offset */
1143 static int iptcc_compile_table(TC_HANDLE_T h, STRUCT_REPLACE *repl)
1145 struct chain_head *c;
1146 struct iptcb_chain_error *error;
1148 /* Second pass: copy from cache to offsets, fill in jumps */
1149 list_for_each_entry(c, &h->chains, list) {
1150 int ret = iptcc_compile_chain(h, repl, c);
1155 /* Append error rule at end of chain */
1156 error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE;
1157 error->entry.target_offset = sizeof(STRUCT_ENTRY);
1158 error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE;
1159 error->target.t.u.user.target_size =
1160 ALIGN(sizeof(struct ipt_error_target));
1161 strcpy((char *)&error->target.t.u.user.name, ERROR_TARGET);
1162 strcpy((char *)&error->target.error, "ERROR");
1167 /**********************************************************************
1168 * EXTERNAL API (operates on cache only)
1169 **********************************************************************/
1171 /* Allocate handle of given size */
1173 alloc_handle(const char *tablename, unsigned int size, unsigned int num_rules)
1178 len = sizeof(STRUCT_TC_HANDLE) + size;
1180 h = malloc(sizeof(STRUCT_TC_HANDLE));
1185 memset(h, 0, sizeof(*h));
1186 INIT_LIST_HEAD(&h->chains);
1187 strcpy(h->info.name, tablename);
1189 h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + size);
1191 goto out_free_handle;
1193 strcpy(h->entries->name, tablename);
1194 h->entries->size = size;
1206 TC_INIT(const char *tablename)
1209 STRUCT_GETINFO info;
1215 if (strlen(tablename) >= TABLE_MAXNAMELEN) {
1220 if (sockfd_use == 0) {
1221 sockfd = socket(TC_AF, SOCK_RAW, IPPROTO_RAW);
1229 strcpy(info.name, tablename);
1230 if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) {
1231 if (--sockfd_use == 0) {
1238 DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n",
1239 info.valid_hooks, info.num_entries, info.size);
1241 if ((h = alloc_handle(info.name, info.size, info.num_entries))
1243 if (--sockfd_use == 0) {
1250 /* Initialize current state */
1253 h->entries->size = h->info.size;
1255 tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size;
1257 if (getsockopt(sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries,
1263 int fd = open("/tmp/libiptc-so_get_entries.blob",
1266 write(fd, h->entries, tmp);
1272 if (parse_table(h) < 0)
1279 /* A different process changed the ruleset size, retry */
1280 if (errno == EAGAIN)
1286 TC_FREE(TC_HANDLE_T *h)
1288 struct chain_head *c, *tmp;
1291 if (--sockfd_use == 0) {
1296 list_for_each_entry_safe(c, tmp, &(*h)->chains, list) {
1297 struct rule_head *r, *rtmp;
1299 list_for_each_entry_safe(r, rtmp, &c->rules, list) {
1306 iptcc_chain_index_free(*h);
1308 free((*h)->entries);
1315 print_match(const STRUCT_ENTRY_MATCH *m)
1317 printf("Match name: `%s'\n", m->u.user.name);
1321 static int dump_entry(STRUCT_ENTRY *e, const TC_HANDLE_T handle);
1324 TC_DUMP_ENTRIES(const TC_HANDLE_T handle)
1326 iptc_fn = TC_DUMP_ENTRIES;
1329 printf("libiptc v%s. %u bytes.\n",
1330 XTABLES_VERSION, handle->entries->size);
1331 printf("Table `%s'\n", handle->info.name);
1332 printf("Hooks: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
1333 handle->info.hook_entry[HOOK_PRE_ROUTING],
1334 handle->info.hook_entry[HOOK_LOCAL_IN],
1335 handle->info.hook_entry[HOOK_FORWARD],
1336 handle->info.hook_entry[HOOK_LOCAL_OUT],
1337 handle->info.hook_entry[HOOK_POST_ROUTING]);
1338 printf("Underflows: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
1339 handle->info.underflow[HOOK_PRE_ROUTING],
1340 handle->info.underflow[HOOK_LOCAL_IN],
1341 handle->info.underflow[HOOK_FORWARD],
1342 handle->info.underflow[HOOK_LOCAL_OUT],
1343 handle->info.underflow[HOOK_POST_ROUTING]);
1345 ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size,
1346 dump_entry, handle);
1349 /* Does this chain exist? */
1350 int TC_IS_CHAIN(const char *chain, const TC_HANDLE_T handle)
1352 iptc_fn = TC_IS_CHAIN;
1353 return iptcc_find_label(chain, handle) != NULL;
1356 static void iptcc_chain_iterator_advance(TC_HANDLE_T handle)
1358 struct chain_head *c = handle->chain_iterator_cur;
1360 if (c->list.next == &handle->chains)
1361 handle->chain_iterator_cur = NULL;
1363 handle->chain_iterator_cur =
1364 list_entry(c->list.next, struct chain_head, list);
1367 /* Iterator functions to run through the chains. */
1369 TC_FIRST_CHAIN(TC_HANDLE_T *handle)
1371 struct chain_head *c = list_entry((*handle)->chains.next,
1372 struct chain_head, list);
1374 iptc_fn = TC_FIRST_CHAIN;
1377 if (list_empty(&(*handle)->chains)) {
1378 DEBUGP(": no chains\n");
1382 (*handle)->chain_iterator_cur = c;
1383 iptcc_chain_iterator_advance(*handle);
1385 DEBUGP(": returning `%s'\n", c->name);
1389 /* Iterator functions to run through the chains. Returns NULL at end. */
1391 TC_NEXT_CHAIN(TC_HANDLE_T *handle)
1393 struct chain_head *c = (*handle)->chain_iterator_cur;
1395 iptc_fn = TC_NEXT_CHAIN;
1398 DEBUGP(": no more chains\n");
1402 iptcc_chain_iterator_advance(*handle);
1404 DEBUGP(": returning `%s'\n", c->name);
1408 /* Get first rule in the given chain: NULL for empty chain. */
1409 const STRUCT_ENTRY *
1410 TC_FIRST_RULE(const char *chain, TC_HANDLE_T *handle)
1412 struct chain_head *c;
1413 struct rule_head *r;
1415 iptc_fn = TC_FIRST_RULE;
1417 DEBUGP("first rule(%s): ", chain);
1419 c = iptcc_find_label(chain, *handle);
1425 /* Empty chain: single return/policy rule */
1426 if (list_empty(&c->rules)) {
1427 DEBUGP_C("no rules, returning NULL\n");
1431 r = list_entry(c->rules.next, struct rule_head, list);
1432 (*handle)->rule_iterator_cur = r;
1433 DEBUGP_C("%p\n", r);
1438 /* Returns NULL when rules run out. */
1439 const STRUCT_ENTRY *
1440 TC_NEXT_RULE(const STRUCT_ENTRY *prev, TC_HANDLE_T *handle)
1442 struct rule_head *r;
1444 iptc_fn = TC_NEXT_RULE;
1445 DEBUGP("rule_iterator_cur=%p...", (*handle)->rule_iterator_cur);
1447 if (!(*handle)->rule_iterator_cur) {
1448 DEBUGP_C("returning NULL\n");
1452 r = list_entry((*handle)->rule_iterator_cur->list.next,
1453 struct rule_head, list);
1455 iptc_fn = TC_NEXT_RULE;
1457 DEBUGP_C("next=%p, head=%p...", &r->list,
1458 &(*handle)->rule_iterator_cur->chain->rules);
1460 if (&r->list == &(*handle)->rule_iterator_cur->chain->rules) {
1461 (*handle)->rule_iterator_cur = NULL;
1462 DEBUGP_C("finished, returning NULL\n");
1466 (*handle)->rule_iterator_cur = r;
1468 /* NOTE: prev is without any influence ! */
1469 DEBUGP_C("returning rule %p\n", r);
1473 /* How many rules in this chain? */
1475 TC_NUM_RULES(const char *chain, TC_HANDLE_T *handle)
1477 struct chain_head *c;
1478 iptc_fn = TC_NUM_RULES;
1481 c = iptcc_find_label(chain, *handle);
1484 return (unsigned int)-1;
1487 return c->num_rules;
1490 static const STRUCT_ENTRY *
1491 TC_GET_RULE(const char *chain, unsigned int n, TC_HANDLE_T *handle)
1493 struct chain_head *c;
1494 struct rule_head *r;
1496 iptc_fn = TC_GET_RULE;
1500 c = iptcc_find_label(chain, *handle);
1506 r = iptcc_get_rule_num(c, n);
1512 /* Returns a pointer to the target name of this position. */
1513 static const char *standard_target_map(int verdict)
1517 return LABEL_RETURN;
1520 return LABEL_ACCEPT;
1529 fprintf(stderr, "ERROR: %d not a valid target)\n",
1538 /* Returns a pointer to the target name of this position. */
1539 const char *TC_GET_TARGET(const STRUCT_ENTRY *ce,
1540 TC_HANDLE_T *handle)
1542 STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce;
1543 struct rule_head *r = container_of(e, struct rule_head, entry[0]);
1545 iptc_fn = TC_GET_TARGET;
1549 case IPTCC_R_FALLTHROUGH:
1553 DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name);
1554 return r->jump->name;
1556 case IPTCC_R_STANDARD:
1557 spos = *(int *)GET_TARGET(e)->data;
1558 DEBUGP("r=%p, spos=%d'\n", r, spos);
1559 return standard_target_map(spos);
1561 case IPTCC_R_MODULE:
1562 return GET_TARGET(e)->u.user.name;
1567 /* Is this a built-in chain? Actually returns hook + 1. */
1569 TC_BUILTIN(const char *chain, const TC_HANDLE_T handle)
1571 struct chain_head *c;
1573 iptc_fn = TC_BUILTIN;
1575 c = iptcc_find_label(chain, handle);
1581 return iptcc_is_builtin(c);
1584 /* Get the policy of a given built-in chain */
1586 TC_GET_POLICY(const char *chain,
1587 STRUCT_COUNTERS *counters,
1588 TC_HANDLE_T *handle)
1590 struct chain_head *c;
1592 iptc_fn = TC_GET_POLICY;
1594 DEBUGP("called for chain %s\n", chain);
1596 c = iptcc_find_label(chain, *handle);
1602 if (!iptcc_is_builtin(c))
1605 *counters = c->counters;
1607 return standard_target_map(c->verdict);
1611 iptcc_standard_map(struct rule_head *r, int verdict)
1613 STRUCT_ENTRY *e = r->entry;
1614 STRUCT_STANDARD_TARGET *t;
1616 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
1618 if (t->target.u.target_size
1619 != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
1623 /* memset for memcmp convenience on delete/replace */
1624 memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
1625 strcpy(t->target.u.user.name, STANDARD_TARGET);
1626 t->verdict = verdict;
1628 r->type = IPTCC_R_STANDARD;
1634 iptcc_map_target(const TC_HANDLE_T handle,
1635 struct rule_head *r)
1637 STRUCT_ENTRY *e = r->entry;
1638 STRUCT_ENTRY_TARGET *t = GET_TARGET(e);
1640 /* Maybe it's empty (=> fall through) */
1641 if (strcmp(t->u.user.name, "") == 0) {
1642 r->type = IPTCC_R_FALLTHROUGH;
1645 /* Maybe it's a standard target name... */
1646 else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0)
1647 return iptcc_standard_map(r, -NF_ACCEPT - 1);
1648 else if (strcmp(t->u.user.name, LABEL_DROP) == 0)
1649 return iptcc_standard_map(r, -NF_DROP - 1);
1650 else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0)
1651 return iptcc_standard_map(r, -NF_QUEUE - 1);
1652 else if (strcmp(t->u.user.name, LABEL_RETURN) == 0)
1653 return iptcc_standard_map(r, RETURN);
1654 else if (TC_BUILTIN(t->u.user.name, handle)) {
1655 /* Can't jump to builtins. */
1659 /* Maybe it's an existing chain name. */
1660 struct chain_head *c;
1661 DEBUGP("trying to find chain `%s': ", t->u.user.name);
1663 c = iptcc_find_label(t->u.user.name, handle);
1665 DEBUGP_C("found!\n");
1666 r->type = IPTCC_R_JUMP;
1671 DEBUGP_C("not found :(\n");
1674 /* Must be a module? If not, kernel will reject... */
1675 /* memset to all 0 for your memcmp convenience: don't clear version */
1676 memset(t->u.user.name + strlen(t->u.user.name),
1678 FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name));
1679 r->type = IPTCC_R_MODULE;
1680 set_changed(handle);
1684 /* Insert the entry `fw' in chain `chain' into position `rulenum'. */
1686 TC_INSERT_ENTRY(const IPT_CHAINLABEL chain,
1687 const STRUCT_ENTRY *e,
1688 unsigned int rulenum,
1689 TC_HANDLE_T *handle)
1691 struct chain_head *c;
1692 struct rule_head *r;
1693 struct list_head *prev;
1695 iptc_fn = TC_INSERT_ENTRY;
1697 if (!(c = iptcc_find_label(chain, *handle))) {
1702 /* first rulenum index = 0
1703 first c->num_rules index = 1 */
1704 if (rulenum > c->num_rules) {
1709 /* If we are inserting at the end just take advantage of the
1710 double linked list, insert will happen before the entry
1712 if (rulenum == c->num_rules) {
1714 } else if (rulenum + 1 <= c->num_rules/2) {
1715 r = iptcc_get_rule_num(c, rulenum + 1);
1718 r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1722 if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1727 memcpy(r->entry, e, e->next_offset);
1728 r->counter_map.maptype = COUNTER_MAP_SET;
1730 if (!iptcc_map_target(*handle, r)) {
1735 list_add_tail(&r->list, prev);
1738 set_changed(*handle);
1743 /* Atomically replace rule `rulenum' in `chain' with `fw'. */
1745 TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain,
1746 const STRUCT_ENTRY *e,
1747 unsigned int rulenum,
1748 TC_HANDLE_T *handle)
1750 struct chain_head *c;
1751 struct rule_head *r, *old;
1753 iptc_fn = TC_REPLACE_ENTRY;
1755 if (!(c = iptcc_find_label(chain, *handle))) {
1760 if (rulenum >= c->num_rules) {
1765 /* Take advantage of the double linked list if possible. */
1766 if (rulenum + 1 <= c->num_rules/2) {
1767 old = iptcc_get_rule_num(c, rulenum + 1);
1769 old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1772 if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1777 memcpy(r->entry, e, e->next_offset);
1778 r->counter_map.maptype = COUNTER_MAP_SET;
1780 if (!iptcc_map_target(*handle, r)) {
1785 list_add(&r->list, &old->list);
1786 iptcc_delete_rule(old);
1788 set_changed(*handle);
1793 /* Append entry `fw' to chain `chain'. Equivalent to insert with
1794 rulenum = length of chain. */
1796 TC_APPEND_ENTRY(const IPT_CHAINLABEL chain,
1797 const STRUCT_ENTRY *e,
1798 TC_HANDLE_T *handle)
1800 struct chain_head *c;
1801 struct rule_head *r;
1803 iptc_fn = TC_APPEND_ENTRY;
1804 if (!(c = iptcc_find_label(chain, *handle))) {
1805 DEBUGP("unable to find chain `%s'\n", chain);
1810 if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1811 DEBUGP("unable to allocate rule for chain `%s'\n", chain);
1816 memcpy(r->entry, e, e->next_offset);
1817 r->counter_map.maptype = COUNTER_MAP_SET;
1819 if (!iptcc_map_target(*handle, r)) {
1820 DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1825 list_add_tail(&r->list, &c->rules);
1828 set_changed(*handle);
1834 match_different(const STRUCT_ENTRY_MATCH *a,
1835 const unsigned char *a_elems,
1836 const unsigned char *b_elems,
1837 unsigned char **maskptr)
1839 const STRUCT_ENTRY_MATCH *b;
1842 /* Offset of b is the same as a. */
1843 b = (void *)b_elems + ((unsigned char *)a - a_elems);
1845 if (a->u.match_size != b->u.match_size)
1848 if (strcmp(a->u.user.name, b->u.user.name) != 0)
1851 *maskptr += ALIGN(sizeof(*a));
1853 for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++)
1854 if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0)
1861 target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask)
1864 STRUCT_ENTRY_TARGET *ta, *tb;
1866 if (a->type != b->type)
1869 ta = GET_TARGET(a->entry);
1870 tb = GET_TARGET(b->entry);
1873 case IPTCC_R_FALLTHROUGH:
1876 return a->jump == b->jump;
1877 case IPTCC_R_STANDARD:
1878 return ((STRUCT_STANDARD_TARGET *)ta)->verdict
1879 == ((STRUCT_STANDARD_TARGET *)tb)->verdict;
1880 case IPTCC_R_MODULE:
1881 if (ta->u.target_size != tb->u.target_size)
1883 if (strcmp(ta->u.user.name, tb->u.user.name) != 0)
1886 for (i = 0; i < ta->u.target_size - sizeof(*ta); i++)
1887 if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0)
1891 fprintf(stderr, "ERROR: bad type %i\n", a->type);
1896 static unsigned char *
1897 is_same(const STRUCT_ENTRY *a,
1898 const STRUCT_ENTRY *b,
1899 unsigned char *matchmask);
1901 /* Delete the first rule in `chain' which matches `fw'. */
1903 TC_DELETE_ENTRY(const IPT_CHAINLABEL chain,
1904 const STRUCT_ENTRY *origfw,
1905 unsigned char *matchmask,
1906 TC_HANDLE_T *handle)
1908 struct chain_head *c;
1909 struct rule_head *r, *i;
1911 iptc_fn = TC_DELETE_ENTRY;
1912 if (!(c = iptcc_find_label(chain, *handle))) {
1917 /* Create a rule_head from origfw. */
1918 r = iptcc_alloc_rule(c, origfw->next_offset);
1924 memcpy(r->entry, origfw, origfw->next_offset);
1925 r->counter_map.maptype = COUNTER_MAP_NOMAP;
1926 if (!iptcc_map_target(*handle, r)) {
1927 DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1931 /* iptcc_map_target increment target chain references
1932 * since this is a fake rule only used for matching
1933 * the chain references count is decremented again.
1935 if (r->type == IPTCC_R_JUMP
1937 r->jump->references--;
1940 list_for_each_entry(i, &c->rules, list) {
1941 unsigned char *mask;
1943 mask = is_same(r->entry, i->entry, matchmask);
1947 if (!target_same(r, i, mask))
1950 /* If we are about to delete the rule that is the
1951 * current iterator, move rule iterator back. next
1952 * pointer will then point to real next node */
1953 if (i == (*handle)->rule_iterator_cur) {
1954 (*handle)->rule_iterator_cur =
1955 list_entry((*handle)->rule_iterator_cur->list.prev,
1956 struct rule_head, list);
1960 iptcc_delete_rule(i);
1962 set_changed(*handle);
1973 /* Delete the rule in position `rulenum' in `chain'. */
1975 TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain,
1976 unsigned int rulenum,
1977 TC_HANDLE_T *handle)
1979 struct chain_head *c;
1980 struct rule_head *r;
1982 iptc_fn = TC_DELETE_NUM_ENTRY;
1984 if (!(c = iptcc_find_label(chain, *handle))) {
1989 if (rulenum >= c->num_rules) {
1994 /* Take advantage of the double linked list if possible. */
1995 if (rulenum + 1 <= c->num_rules/2) {
1996 r = iptcc_get_rule_num(c, rulenum + 1);
1998 r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
2001 /* If we are about to delete the rule that is the current
2002 * iterator, move rule iterator back. next pointer will then
2003 * point to real next node */
2004 if (r == (*handle)->rule_iterator_cur) {
2005 (*handle)->rule_iterator_cur =
2006 list_entry((*handle)->rule_iterator_cur->list.prev,
2007 struct rule_head, list);
2011 iptcc_delete_rule(r);
2013 set_changed(*handle);
2018 /* Check the packet `fw' on chain `chain'. Returns the verdict, or
2019 NULL and sets errno. */
2021 TC_CHECK_PACKET(const IPT_CHAINLABEL chain,
2022 STRUCT_ENTRY *entry,
2023 TC_HANDLE_T *handle)
2025 iptc_fn = TC_CHECK_PACKET;
2030 /* Flushes the entries in the given chain (ie. empties chain). */
2032 TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2034 struct chain_head *c;
2035 struct rule_head *r, *tmp;
2037 iptc_fn = TC_FLUSH_ENTRIES;
2038 if (!(c = iptcc_find_label(chain, *handle))) {
2043 list_for_each_entry_safe(r, tmp, &c->rules, list) {
2044 iptcc_delete_rule(r);
2049 set_changed(*handle);
2054 /* Zeroes the counters in a chain. */
2056 TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2058 struct chain_head *c;
2059 struct rule_head *r;
2061 iptc_fn = TC_ZERO_ENTRIES;
2062 if (!(c = iptcc_find_label(chain, *handle))) {
2067 if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2068 c->counter_map.maptype = COUNTER_MAP_ZEROED;
2070 list_for_each_entry(r, &c->rules, list) {
2071 if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2072 r->counter_map.maptype = COUNTER_MAP_ZEROED;
2075 set_changed(*handle);
2081 TC_READ_COUNTER(const IPT_CHAINLABEL chain,
2082 unsigned int rulenum,
2083 TC_HANDLE_T *handle)
2085 struct chain_head *c;
2086 struct rule_head *r;
2088 iptc_fn = TC_READ_COUNTER;
2091 if (!(c = iptcc_find_label(chain, *handle))) {
2096 if (!(r = iptcc_get_rule_num(c, rulenum))) {
2101 return &r->entry[0].counters;
2105 TC_ZERO_COUNTER(const IPT_CHAINLABEL chain,
2106 unsigned int rulenum,
2107 TC_HANDLE_T *handle)
2109 struct chain_head *c;
2110 struct rule_head *r;
2112 iptc_fn = TC_ZERO_COUNTER;
2115 if (!(c = iptcc_find_label(chain, *handle))) {
2120 if (!(r = iptcc_get_rule_num(c, rulenum))) {
2125 if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2126 r->counter_map.maptype = COUNTER_MAP_ZEROED;
2128 set_changed(*handle);
2134 TC_SET_COUNTER(const IPT_CHAINLABEL chain,
2135 unsigned int rulenum,
2136 STRUCT_COUNTERS *counters,
2137 TC_HANDLE_T *handle)
2139 struct chain_head *c;
2140 struct rule_head *r;
2143 iptc_fn = TC_SET_COUNTER;
2146 if (!(c = iptcc_find_label(chain, *handle))) {
2151 if (!(r = iptcc_get_rule_num(c, rulenum))) {
2157 r->counter_map.maptype = COUNTER_MAP_SET;
2159 memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS));
2161 set_changed(*handle);
2166 /* Creates a new chain. */
2167 /* To create a chain, create two rules: error node and unconditional
2170 TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2172 static struct chain_head *c;
2176 iptc_fn = TC_CREATE_CHAIN;
2178 /* find_label doesn't cover built-in targets: DROP, ACCEPT,
2180 if (iptcc_find_label(chain, *handle)
2181 || strcmp(chain, LABEL_DROP) == 0
2182 || strcmp(chain, LABEL_ACCEPT) == 0
2183 || strcmp(chain, LABEL_QUEUE) == 0
2184 || strcmp(chain, LABEL_RETURN) == 0) {
2185 DEBUGP("Chain `%s' already exists\n", chain);
2190 if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) {
2191 DEBUGP("Chain name `%s' too long\n", chain);
2196 c = iptcc_alloc_chain_head(chain, 0);
2198 DEBUGP("Cannot allocate memory for chain `%s'\n", chain);
2203 (*handle)->num_chains++; /* New user defined chain */
2205 DEBUGP("Creating chain `%s'\n", chain);
2206 iptc_insert_chain(*handle, c); /* Insert sorted */
2208 /* Inserting chains don't change the correctness of the chain
2209 * index (except if its smaller than index[0], but that
2210 * handled by iptc_insert_chain). It only causes longer lists
2211 * in the buckets. Thus, only rebuild chain index when the
2212 * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains.
2214 capacity = (*handle)->chain_index_sz * CHAIN_INDEX_BUCKET_LEN;
2215 exceeded = ((((*handle)->num_chains)-capacity));
2216 if (exceeded > CHAIN_INDEX_INSERT_MAX) {
2217 debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n",
2218 capacity, exceeded, (*handle)->num_chains);
2219 iptcc_chain_index_rebuild(*handle);
2222 set_changed(*handle);
2227 /* Get the number of references to this chain. */
2229 TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain,
2230 TC_HANDLE_T *handle)
2232 struct chain_head *c;
2234 iptc_fn = TC_GET_REFERENCES;
2235 if (!(c = iptcc_find_label(chain, *handle))) {
2240 *ref = c->references;
2245 /* Deletes a chain. */
2247 TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2249 unsigned int references;
2250 struct chain_head *c;
2252 iptc_fn = TC_DELETE_CHAIN;
2254 if (!(c = iptcc_find_label(chain, *handle))) {
2255 DEBUGP("cannot find chain `%s'\n", chain);
2260 if (TC_BUILTIN(chain, *handle)) {
2261 DEBUGP("cannot remove builtin chain `%s'\n", chain);
2266 if (!TC_GET_REFERENCES(&references, chain, handle)) {
2267 DEBUGP("cannot get references on chain `%s'\n", chain);
2271 if (references > 0) {
2272 DEBUGP("chain `%s' still has references\n", chain);
2278 DEBUGP("chain `%s' is not empty\n", chain);
2283 /* If we are about to delete the chain that is the current
2284 * iterator, move chain iterator forward. */
2285 if (c == (*handle)->chain_iterator_cur)
2286 iptcc_chain_iterator_advance(*handle);
2288 (*handle)->num_chains--; /* One user defined chain deleted */
2290 //list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */
2291 iptcc_chain_index_delete_chain(c, *handle);
2294 DEBUGP("chain `%s' deleted\n", chain);
2296 set_changed(*handle);
2301 /* Renames a chain. */
2302 int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname,
2303 const IPT_CHAINLABEL newname,
2304 TC_HANDLE_T *handle)
2306 struct chain_head *c;
2307 iptc_fn = TC_RENAME_CHAIN;
2309 /* find_label doesn't cover built-in targets: DROP, ACCEPT,
2311 if (iptcc_find_label(newname, *handle)
2312 || strcmp(newname, LABEL_DROP) == 0
2313 || strcmp(newname, LABEL_ACCEPT) == 0
2314 || strcmp(newname, LABEL_QUEUE) == 0
2315 || strcmp(newname, LABEL_RETURN) == 0) {
2320 if (!(c = iptcc_find_label(oldname, *handle))
2321 || TC_BUILTIN(oldname, *handle)) {
2326 if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) {
2331 strncpy(c->name, newname, sizeof(IPT_CHAINLABEL));
2333 set_changed(*handle);
2338 /* Sets the policy on a built-in chain. */
2340 TC_SET_POLICY(const IPT_CHAINLABEL chain,
2341 const IPT_CHAINLABEL policy,
2342 STRUCT_COUNTERS *counters,
2343 TC_HANDLE_T *handle)
2345 struct chain_head *c;
2347 iptc_fn = TC_SET_POLICY;
2349 if (!(c = iptcc_find_label(chain, *handle))) {
2350 DEBUGP("cannot find chain `%s'\n", chain);
2355 if (!iptcc_is_builtin(c)) {
2356 DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain);
2361 if (strcmp(policy, LABEL_ACCEPT) == 0)
2362 c->verdict = -NF_ACCEPT - 1;
2363 else if (strcmp(policy, LABEL_DROP) == 0)
2364 c->verdict = -NF_DROP - 1;
2371 /* set byte and packet counters */
2372 memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS));
2373 c->counter_map.maptype = COUNTER_MAP_SET;
2375 c->counter_map.maptype = COUNTER_MAP_NOMAP;
2378 set_changed(*handle);
2383 /* Without this, on gcc 2.7.2.3, we get:
2384 libiptc.c: In function `TC_COMMIT':
2385 libiptc.c:833: fixed or forbidden register was spilled.
2386 This may be due to a compiler bug or to impossible asm
2387 statements or clauses.
2390 subtract_counters(STRUCT_COUNTERS *answer,
2391 const STRUCT_COUNTERS *a,
2392 const STRUCT_COUNTERS *b)
2394 answer->pcnt = a->pcnt - b->pcnt;
2395 answer->bcnt = a->bcnt - b->bcnt;
2399 static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx)
2401 newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0});
2402 DEBUGP_C("NOMAP => zero\n");
2405 static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters,
2406 STRUCT_REPLACE *repl, unsigned int idx,
2407 unsigned int mappos)
2409 /* Original read: X.
2410 * Atomic read on replacement: X + Y.
2411 * Currently in kernel: Z.
2412 * Want in kernel: X + Y + Z.
2414 * => Add in replacement read.
2416 newcounters->counters[idx] = repl->counters[mappos];
2417 DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos);
2420 static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters,
2421 STRUCT_REPLACE *repl, unsigned int idx,
2422 unsigned int mappos, STRUCT_COUNTERS *counters)
2424 /* Original read: X.
2425 * Atomic read on replacement: X + Y.
2426 * Currently in kernel: Z.
2427 * Want in kernel: Y + Z.
2429 * => Add in (replacement read - original read).
2431 subtract_counters(&newcounters->counters[idx],
2432 &repl->counters[mappos],
2434 DEBUGP_C("ZEROED => mappos %u\n", mappos);
2437 static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters,
2438 unsigned int idx, STRUCT_COUNTERS *counters)
2440 /* Want to set counter (iptables-restore) */
2442 memcpy(&newcounters->counters[idx], counters,
2443 sizeof(STRUCT_COUNTERS));
2450 TC_COMMIT(TC_HANDLE_T *handle)
2452 /* Replace, then map back the counters. */
2453 STRUCT_REPLACE *repl;
2454 STRUCT_COUNTERS_INFO *newcounters;
2455 struct chain_head *c;
2459 unsigned int new_size;
2461 iptc_fn = TC_COMMIT;
2464 /* Don't commit if nothing changed. */
2465 if (!(*handle)->changed)
2468 new_number = iptcc_compile_table_prep(*handle, &new_size);
2469 if (new_number < 0) {
2474 repl = malloc(sizeof(*repl) + new_size);
2479 memset(repl, 0, sizeof(*repl) + new_size);
2482 TC_DUMP_ENTRIES(*handle);
2485 counterlen = sizeof(STRUCT_COUNTERS_INFO)
2486 + sizeof(STRUCT_COUNTERS) * new_number;
2488 /* These are the old counters we will get from kernel */
2489 repl->counters = malloc(sizeof(STRUCT_COUNTERS)
2490 * (*handle)->info.num_entries);
2491 if (!repl->counters) {
2495 /* These are the counters we're going to put back, later. */
2496 newcounters = malloc(counterlen);
2499 goto out_free_repl_counters;
2501 memset(newcounters, 0, counterlen);
2503 strcpy(repl->name, (*handle)->info.name);
2504 repl->num_entries = new_number;
2505 repl->size = new_size;
2507 repl->num_counters = (*handle)->info.num_entries;
2508 repl->valid_hooks = (*handle)->info.valid_hooks;
2510 DEBUGP("num_entries=%u, size=%u, num_counters=%u\n",
2511 repl->num_entries, repl->size, repl->num_counters);
2513 ret = iptcc_compile_table(*handle, repl);
2516 goto out_free_newcounters;
2522 int fd = open("/tmp/libiptc-so_set_replace.blob",
2525 write(fd, repl, sizeof(*repl) + repl->size);
2531 ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_REPLACE, repl,
2532 sizeof(*repl) + repl->size);
2534 goto out_free_newcounters;
2536 /* Put counters back. */
2537 strcpy(newcounters->name, (*handle)->info.name);
2538 newcounters->num_counters = new_number;
2540 list_for_each_entry(c, &(*handle)->chains, list) {
2541 struct rule_head *r;
2543 /* Builtin chains have their own counters */
2544 if (iptcc_is_builtin(c)) {
2545 DEBUGP("counter for chain-index %u: ", c->foot_index);
2546 switch(c->counter_map.maptype) {
2547 case COUNTER_MAP_NOMAP:
2548 counters_nomap(newcounters, c->foot_index);
2550 case COUNTER_MAP_NORMAL_MAP:
2551 counters_normal_map(newcounters, repl,
2553 c->counter_map.mappos);
2555 case COUNTER_MAP_ZEROED:
2556 counters_map_zeroed(newcounters, repl,
2558 c->counter_map.mappos,
2561 case COUNTER_MAP_SET:
2562 counters_map_set(newcounters, c->foot_index,
2568 list_for_each_entry(r, &c->rules, list) {
2569 DEBUGP("counter for index %u: ", r->index);
2570 switch (r->counter_map.maptype) {
2571 case COUNTER_MAP_NOMAP:
2572 counters_nomap(newcounters, r->index);
2575 case COUNTER_MAP_NORMAL_MAP:
2576 counters_normal_map(newcounters, repl,
2578 r->counter_map.mappos);
2581 case COUNTER_MAP_ZEROED:
2582 counters_map_zeroed(newcounters, repl,
2584 r->counter_map.mappos,
2585 &r->entry->counters);
2588 case COUNTER_MAP_SET:
2589 counters_map_set(newcounters, r->index,
2590 &r->entry->counters);
2598 int fd = open("/tmp/libiptc-so_set_add_counters.blob",
2601 write(fd, newcounters, counterlen);
2607 ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS,
2608 newcounters, counterlen);
2610 goto out_free_newcounters;
2612 free(repl->counters);
2620 out_free_newcounters:
2622 out_free_repl_counters:
2623 free(repl->counters);
2630 /* Get raw socket. */
2632 TC_GET_RAW_SOCKET(void)
2637 /* Translates errno numbers into more human-readable form than strerror. */
2639 TC_STRERROR(int err)
2642 struct table_struct {
2645 const char *message;
2647 { { TC_INIT, EPERM, "Permission denied (you must be root)" },
2648 { TC_INIT, EINVAL, "Module is wrong version" },
2650 "Table does not exist (do you need to insmod?)" },
2651 { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" },
2652 { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" },
2653 { TC_DELETE_CHAIN, EMLINK,
2654 "Can't delete chain with references left" },
2655 { TC_CREATE_CHAIN, EEXIST, "Chain already exists" },
2656 { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" },
2657 { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" },
2658 { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" },
2659 { TC_READ_COUNTER, E2BIG, "Index of counter too big" },
2660 { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" },
2661 { TC_INSERT_ENTRY, ELOOP, "Loop found in table" },
2662 { TC_INSERT_ENTRY, EINVAL, "Target problem" },
2663 /* EINVAL for CHECK probably means bad interface. */
2664 { TC_CHECK_PACKET, EINVAL,
2665 "Bad arguments (does that interface exist?)" },
2666 { TC_CHECK_PACKET, ENOSYS,
2667 "Checking will most likely never get implemented" },
2668 /* ENOENT for DELETE probably means no matching rule */
2669 { TC_DELETE_ENTRY, ENOENT,
2670 "Bad rule (does a matching rule exist in that chain?)" },
2671 { TC_SET_POLICY, ENOENT,
2672 "Bad built-in chain name" },
2673 { TC_SET_POLICY, EINVAL,
2674 "Bad policy name" },
2676 { NULL, 0, "Incompatible with this kernel" },
2677 { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" },
2678 { NULL, ENOSYS, "Will be implemented real soon. I promise ;)" },
2679 { NULL, ENOMEM, "Memory allocation problem" },
2680 { NULL, ENOENT, "No chain/target/match by that name" },
2683 for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) {
2684 if ((!table[i].fn || table[i].fn == iptc_fn)
2685 && table[i].err == err)
2686 return table[i].message;
2689 return strerror(err);