Code

Merge branch 'collectd-4.5' into collectd-4.6
[collectd.git] / src / libiptc / libiptc.c
1 /**
2  * This file was imported from the iptables sources.
3  * Copyright (C) 1999-2008 Netfilter Core Team
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  */
19 /* Library which manipulates firewall rules.  Version $Revision: 7138 $ */
21 /* Architecture of firewall rules is as follows:
22  *
23  * Chains go INPUT, FORWARD, OUTPUT then user chains.
24  * Each user chain starts with an ERROR node.
25  * Every chain ends with an unconditional jump: a RETURN for user chains,
26  * and a POLICY for built-ins.
27  */
29 /* (C) 1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See
30  * COPYING for details). 
31  * (C) 2000-2004 by the Netfilter Core Team <coreteam@netfilter.org>
32  *
33  * 2003-Jun-20: Harald Welte <laforge@netfilter.org>:
34  *      - Reimplementation of chain cache to use offsets instead of entries
35  * 2003-Jun-23: Harald Welte <laforge@netfilter.org>:
36  *      - performance optimization, sponsored by Astaro AG (http://www.astaro.com/)
37  *        don't rebuild the chain cache after every operation, instead fix it
38  *        up after a ruleset change.  
39  * 2004-Aug-18: Harald Welte <laforge@netfilter.org>:
40  *      - futher performance work: total reimplementation of libiptc.
41  *      - libiptc now has a real internal (linked-list) represntation of the
42  *        ruleset and a parser/compiler from/to this internal representation
43  *      - again sponsored by Astaro AG (http://www.astaro.com/)
44  */
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include "xtables.h"
49 #include "linux_list.h"
51 //#define IPTC_DEBUG2 1
53 #ifdef IPTC_DEBUG2
54 #include <fcntl.h>
55 #define DEBUGP(x, args...)      fprintf(stderr, "%s: " x, __FUNCTION__, ## args)
56 #define DEBUGP_C(x, args...)    fprintf(stderr, x, ## args)
57 #else
58 #define DEBUGP(x, args...)
59 #define DEBUGP_C(x, args...)
60 #endif
62 #ifdef DEBUG
63 #define debug(x, args...)       fprintf(stderr, x, ## args)
64 #else
65 #define debug(x, args...)
66 #endif
68 static int sockfd = -1;
69 static int sockfd_use = 0;
70 static void *iptc_fn = NULL;
72 static const char *hooknames[] = {
73         [HOOK_PRE_ROUTING]      = "PREROUTING",
74         [HOOK_LOCAL_IN]         = "INPUT",
75         [HOOK_FORWARD]          = "FORWARD",
76         [HOOK_LOCAL_OUT]        = "OUTPUT",
77         [HOOK_POST_ROUTING]     = "POSTROUTING",
78 #ifdef HOOK_DROPPING
79         [HOOK_DROPPING]         = "DROPPING"
80 #endif
81 };
83 /* Convenience structures */
84 struct ipt_error_target
85 {
86         STRUCT_ENTRY_TARGET t;
87         char error[TABLE_MAXNAMELEN];
88 };
90 struct chain_head;
91 struct rule_head;
93 struct counter_map
94 {
95         enum {
96                 COUNTER_MAP_NOMAP,
97                 COUNTER_MAP_NORMAL_MAP,
98                 COUNTER_MAP_ZEROED,
99                 COUNTER_MAP_SET
100         } maptype;
101         unsigned int mappos;
102 };
104 enum iptcc_rule_type {
105         IPTCC_R_STANDARD,               /* standard target (ACCEPT, ...) */
106         IPTCC_R_MODULE,                 /* extension module (SNAT, ...) */
107         IPTCC_R_FALLTHROUGH,            /* fallthrough rule */
108         IPTCC_R_JUMP,                   /* jump to other chain */
109 };
111 struct rule_head
113         struct list_head list;
114         struct chain_head *chain;
115         struct counter_map counter_map;
117         unsigned int index;             /* index (needed for counter_map) */
118         unsigned int offset;            /* offset in rule blob */
120         enum iptcc_rule_type type;
121         struct chain_head *jump;        /* jump target, if IPTCC_R_JUMP */
123         unsigned int size;              /* size of entry data */
124         STRUCT_ENTRY entry[0];
125 };
127 struct chain_head
129         struct list_head list;
130         char name[TABLE_MAXNAMELEN];
131         unsigned int hooknum;           /* hook number+1 if builtin */
132         unsigned int references;        /* how many jumps reference us */
133         int verdict;                    /* verdict if builtin */
135         STRUCT_COUNTERS counters;       /* per-chain counters */
136         struct counter_map counter_map;
138         unsigned int num_rules;         /* number of rules in list */
139         struct list_head rules;         /* list of rules */
141         unsigned int index;             /* index (needed for jump resolval) */
142         unsigned int head_offset;       /* offset in rule blob */
143         unsigned int foot_index;        /* index (needed for counter_map) */
144         unsigned int foot_offset;       /* offset in rule blob */
145 };
147 STRUCT_TC_HANDLE
149         int changed;                     /* Have changes been made? */
151         struct list_head chains;
152         
153         struct chain_head *chain_iterator_cur;
154         struct rule_head *rule_iterator_cur;
156         unsigned int num_chains;         /* number of user defined chains */
158         struct chain_head **chain_index;   /* array for fast chain list access*/
159         unsigned int        chain_index_sz;/* size of chain index array */
161         STRUCT_GETINFO info;
162         STRUCT_GET_ENTRIES *entries;
163 };
165 /* allocate a new chain head for the cache */
166 static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum)
168         struct chain_head *c = malloc(sizeof(*c));
169         if (!c)
170                 return NULL;
171         memset(c, 0, sizeof(*c));
173         strncpy(c->name, name, TABLE_MAXNAMELEN);
174         c->hooknum = hooknum;
175         INIT_LIST_HEAD(&c->rules);
177         return c;
180 /* allocate and initialize a new rule for the cache */
181 static struct rule_head *iptcc_alloc_rule(struct chain_head *c, unsigned int size)
183         struct rule_head *r = malloc(sizeof(*r)+size);
184         if (!r)
185                 return NULL;
186         memset(r, 0, sizeof(*r));
188         r->chain = c;
189         r->size = size;
191         return r;
194 /* notify us that the ruleset has been modified by the user */
195 static inline void
196 set_changed(TC_HANDLE_T h)
198         h->changed = 1;
201 #ifdef IPTC_DEBUG
202 static void do_check(TC_HANDLE_T h, unsigned int line);
203 #define CHECK(h) do { if (!getenv("IPTC_NO_CHECK")) do_check((h), __LINE__); } while(0)
204 #else
205 #define CHECK(h)
206 #endif
209 /**********************************************************************
210  * iptc blob utility functions (iptcb_*)
211  **********************************************************************/
213 static inline int
214 iptcb_get_number(const STRUCT_ENTRY *i,
215            const STRUCT_ENTRY *seek,
216            unsigned int *pos)
218         if (i == seek)
219                 return 1;
220         (*pos)++;
221         return 0;
224 static inline int
225 iptcb_get_entry_n(STRUCT_ENTRY *i,
226             unsigned int number,
227             unsigned int *pos,
228             STRUCT_ENTRY **pe)
230         if (*pos == number) {
231                 *pe = i;
232                 return 1;
233         }
234         (*pos)++;
235         return 0;
238 static inline STRUCT_ENTRY *
239 iptcb_get_entry(TC_HANDLE_T h, unsigned int offset)
241         return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset);
244 static unsigned int
245 iptcb_entry2index(const TC_HANDLE_T h, const STRUCT_ENTRY *seek)
247         unsigned int pos = 0;
249         if (ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
250                           iptcb_get_number, seek, &pos) == 0) {
251                 fprintf(stderr, "ERROR: offset %u not an entry!\n",
252                         (unsigned int)((char *)seek - (char *)h->entries->entrytable));
253                 abort();
254         }
255         return pos;
258 static inline STRUCT_ENTRY *
259 iptcb_offset2entry(TC_HANDLE_T h, unsigned int offset)
261         return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset);
265 static inline unsigned long
266 iptcb_entry2offset(const TC_HANDLE_T h, const STRUCT_ENTRY *e)
268         return (void *)e - (void *)h->entries->entrytable;
271 static inline unsigned int
272 iptcb_offset2index(const TC_HANDLE_T h, unsigned int offset)
274         return iptcb_entry2index(h, iptcb_offset2entry(h, offset));
277 /* Returns 0 if not hook entry, else hooknumber + 1 */
278 static inline unsigned int
279 iptcb_ent_is_hook_entry(STRUCT_ENTRY *e, TC_HANDLE_T h)
281         unsigned int i;
283         for (i = 0; i < NUMHOOKS; i++) {
284                 if ((h->info.valid_hooks & (1 << i))
285                     && iptcb_get_entry(h, h->info.hook_entry[i]) == e)
286                         return i+1;
287         }
288         return 0;
292 /**********************************************************************
293  * Chain index (cache utility) functions
294  **********************************************************************
295  * The chain index is an array with pointers into the chain list, with
296  * CHAIN_INDEX_BUCKET_LEN spacing.  This facilitates the ability to
297  * speedup chain list searching, by find a more optimal starting
298  * points when searching the linked list.
299  *
300  * The starting point can be found fast by using a binary search of
301  * the chain index. Thus, reducing the previous search complexity of
302  * O(n) to O(log(n/k) + k) where k is CHAIN_INDEX_BUCKET_LEN.
303  *
304  * A nice property of the chain index, is that the "bucket" list
305  * length is max CHAIN_INDEX_BUCKET_LEN (when just build, inserts will
306  * change this). Oppose to hashing, where the "bucket" list length can
307  * vary a lot.
308  */
309 #ifndef CHAIN_INDEX_BUCKET_LEN
310 #define CHAIN_INDEX_BUCKET_LEN 40
311 #endif
313 /* Another nice property of the chain index is that inserting/creating
314  * chains in chain list don't change the correctness of the chain
315  * index, it only causes longer lists in the buckets.
316  *
317  * To mitigate the performance penalty of longer bucket lists and the
318  * penalty of rebuilding, the chain index is rebuild only when
319  * CHAIN_INDEX_INSERT_MAX chains has been added.
320  */
321 #ifndef CHAIN_INDEX_INSERT_MAX
322 #define CHAIN_INDEX_INSERT_MAX 355
323 #endif
325 static inline unsigned int iptcc_is_builtin(struct chain_head *c);
328 /* Use binary search in the chain index array, to find a chain_head
329  * pointer closest to the place of the searched name element.
330  *
331  * Notes that, binary search (obviously) requires that the chain list
332  * is sorted by name.
333  */
334 static struct list_head *
335 iptcc_bsearch_chain_index(const char *name, unsigned int *idx, TC_HANDLE_T handle)
337         unsigned int pos, end;
338         int res;
340         struct list_head *list_pos;
341         list_pos=&handle->chains;
343         /* Check for empty array, e.g. no user defined chains */
344         if (handle->chain_index_sz == 0) {
345                 debug("WARNING: handle->chain_index_sz == 0\n");
346                 return list_pos;
347         }
349         /* Init */
350         end = handle->chain_index_sz;
351         pos = end / 2;
353         debug("bsearch Find chain:%s (pos:%d end:%d)\n", name, pos, end);
355         /* Loop */
356  loop:
357         if (!handle->chain_index[pos]) {
358                 fprintf(stderr, "ERROR: NULL pointer chain_index[%d]\n", pos);
359                 return &handle->chains; /* Be safe, return orig start pos */
360         }
362         res = strcmp(name, handle->chain_index[pos]->name);
363         list_pos = &handle->chain_index[pos]->list;
364         *idx = pos;
366         debug("bsearch Index[%d] name:%s res:%d ",
367               pos, handle->chain_index[pos]->name, res);
369         if (res == 0) { /* Found element, by direct hit */
370                 debug("[found] Direct hit pos:%d end:%d\n", pos, end);
371                 return list_pos;
372         } else if (res < 0) { /* Too far, jump back */
373                 end = pos;
374                 pos = pos / 2;
376                 /* Exit case: First element of array */
377                 if (end == 0) {
378                         debug("[found] Reached first array elem (end%d)\n",end);
379                         return list_pos;
380                 }
381                 debug("jump back to pos:%d (end:%d)\n", pos, end);
382                 goto loop;
383         } else if (res > 0 ){ /* Not far enough, jump forward */
385                 /* Exit case: Last element of array */
386                 if (pos == handle->chain_index_sz-1) {
387                         debug("[found] Last array elem (end:%d)\n", end);
388                         return list_pos;
389                 }
391                 /* Exit case: Next index less, thus elem in this list section */
392                 res = strcmp(name, handle->chain_index[pos+1]->name);
393                 if (res < 0) {
394                         debug("[found] closest list (end:%d)\n", end);
395                         return list_pos;
396                 }
398                 pos = (pos+end)/2;
399                 debug("jump forward to pos:%d (end:%d)\n", pos, end);
400                 goto loop;
401         }
403         return list_pos;
406 #ifdef DEBUG
407 /* Trivial linear search of chain index. Function used for verifying
408    the output of bsearch function */
409 static struct list_head *
410 iptcc_linearly_search_chain_index(const char *name, TC_HANDLE_T handle)
412         unsigned int i=0;
413         int res=0;
415         struct list_head *list_pos;
416         list_pos = &handle->chains;
418         if (handle->chain_index_sz)
419                 list_pos = &handle->chain_index[0]->list;
421         /* Linearly walk of chain index array */
423         for (i=0; i < handle->chain_index_sz; i++) {
424                 if (handle->chain_index[i]) {
425                         res = strcmp(handle->chain_index[i]->name, name);
426                         if (res > 0)
427                                 break; // One step too far
428                         list_pos = &handle->chain_index[i]->list;
429                         if (res == 0)
430                                 break; // Direct hit
431                 }
432         }
434         return list_pos;
436 #endif
438 static int iptcc_chain_index_alloc(TC_HANDLE_T h)
440         unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
441         unsigned int array_elems;
442         unsigned int array_mem;
444         /* Allocate memory for the chain index array */
445         array_elems = (h->num_chains / list_length) +
446                       (h->num_chains % list_length ? 1 : 0);
447         array_mem   = sizeof(h->chain_index) * array_elems;
449         debug("Alloc Chain index, elems:%d mem:%d bytes\n",
450               array_elems, array_mem);
452         h->chain_index = malloc(array_mem);
453         if (!h->chain_index) {
454                 h->chain_index_sz = 0;
455                 return -ENOMEM;
456         }
457         memset(h->chain_index, 0, array_mem);
458         h->chain_index_sz = array_elems;
460         return 1;
463 static void iptcc_chain_index_free(TC_HANDLE_T h)
465         h->chain_index_sz = 0;
466         free(h->chain_index);
470 #ifdef DEBUG
471 static void iptcc_chain_index_dump(TC_HANDLE_T h)
473         unsigned int i = 0;
475         /* Dump: contents of chain index array */
476         for (i=0; i < h->chain_index_sz; i++) {
477                 if (h->chain_index[i]) {
478                         fprintf(stderr, "Chain index[%d].name: %s\n",
479                                 i, h->chain_index[i]->name);
480                 }
481         }
483 #endif
485 /* Build the chain index */
486 static int iptcc_chain_index_build(TC_HANDLE_T h)
488         unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
489         unsigned int chains = 0;
490         unsigned int cindex = 0;
491         struct chain_head *c;
493         /* Build up the chain index array here */
494         debug("Building chain index\n");
496         debug("Number of user defined chains:%d bucket_sz:%d array_sz:%d\n",
497                 h->num_chains, list_length, h->chain_index_sz);
499         if (h->chain_index_sz == 0)
500                 return 0;
502         list_for_each_entry(c, &h->chains, list) {
504                 /* Issue: The index array needs to start after the
505                  * builtin chains, as they are not sorted */
506                 if (!iptcc_is_builtin(c)) {
507                         cindex=chains / list_length;
509                         /* Safe guard, break out on array limit, this
510                          * is useful if chains are added and array is
511                          * rebuild, without realloc of memory. */
512                         if (cindex >= h->chain_index_sz)
513                                 break;
515                         if ((chains % list_length)== 0) {
516                                 debug("\nIndex[%d] Chains:", cindex);
517                                 h->chain_index[cindex] = c;
518                         }
519                         chains++;
520                 }
521                 debug("%s, ", c->name);
522         }
523         debug("\n");
525         return 1;
528 static int iptcc_chain_index_rebuild(TC_HANDLE_T h)
530         debug("REBUILD chain index array\n");
531         iptcc_chain_index_free(h);
532         if ((iptcc_chain_index_alloc(h)) < 0)
533                 return -ENOMEM;
534         iptcc_chain_index_build(h);
535         return 1;
538 /* Delete chain (pointer) from index array.  Removing an element from
539  * the chain list only affects the chain index array, if the chain
540  * index points-to/uses that list pointer.
541  *
542  * There are different strategies, the simple and safe is to rebuild
543  * the chain index every time.  The more advanced is to update the
544  * array index to point to the next element, but that requires some
545  * house keeping and boundry checks.  The advanced is implemented, as
546  * the simple approach behaves badly when all chains are deleted
547  * because list_for_each processing will always hit the first chain
548  * index, thus causing a rebuild for every chain.
549  */
550 static int iptcc_chain_index_delete_chain(struct chain_head *c, TC_HANDLE_T h)
552         struct list_head *index_ptr, *index_ptr2, *next;
553         struct chain_head *c2;
554         unsigned int idx, idx2;
556         index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h);
558         debug("Del chain[%s] c->list:%p index_ptr:%p\n",
559               c->name, &c->list, index_ptr);
561         /* Save the next pointer */
562         next = c->list.next;
563         list_del(&c->list);
565         if (index_ptr == &c->list) { /* Chain used as index ptr */
567                 /* See if its possible to avoid a rebuild, by shifting
568                  * to next pointer.  Its possible if the next pointer
569                  * is located in the same index bucket.
570                  */
571                 c2         = list_entry(next, struct chain_head, list);
572                 index_ptr2 = iptcc_bsearch_chain_index(c2->name, &idx2, h);
573                 if (idx != idx2) {
574                         /* Rebuild needed */
575                         return iptcc_chain_index_rebuild(h);
576                 } else {
577                         /* Avoiding rebuild */
578                         debug("Update cindex[%d] with next ptr name:[%s]\n",
579                               idx, c2->name);
580                         h->chain_index[idx]=c2;
581                         return 0;
582                 }
583         }
584         return 0;
588 /**********************************************************************
589  * iptc cache utility functions (iptcc_*)
590  **********************************************************************/
592 /* Is the given chain builtin (1) or user-defined (0) */
593 static inline unsigned int iptcc_is_builtin(struct chain_head *c)
595         return (c->hooknum ? 1 : 0);
598 /* Get a specific rule within a chain */
599 static struct rule_head *iptcc_get_rule_num(struct chain_head *c,
600                                             unsigned int rulenum)
602         struct rule_head *r;
603         unsigned int num = 0;
605         list_for_each_entry(r, &c->rules, list) {
606                 num++;
607                 if (num == rulenum)
608                         return r;
609         }
610         return NULL;
613 /* Get a specific rule within a chain backwards */
614 static struct rule_head *iptcc_get_rule_num_reverse(struct chain_head *c,
615                                             unsigned int rulenum)
617         struct rule_head *r;
618         unsigned int num = 0;
620         list_for_each_entry_reverse(r, &c->rules, list) {
621                 num++;
622                 if (num == rulenum)
623                         return r;
624         }
625         return NULL;
628 /* Returns chain head if found, otherwise NULL. */
629 static struct chain_head *
630 iptcc_find_chain_by_offset(TC_HANDLE_T handle, unsigned int offset)
632         struct list_head *pos;
634         if (list_empty(&handle->chains))
635                 return NULL;
637         list_for_each(pos, &handle->chains) {
638                 struct chain_head *c = list_entry(pos, struct chain_head, list);
639                 if (offset >= c->head_offset && offset <= c->foot_offset)
640                         return c;
641         }
643         return NULL;
646 /* Returns chain head if found, otherwise NULL. */
647 static struct chain_head *
648 iptcc_find_label(const char *name, TC_HANDLE_T handle)
650         struct list_head *pos;
651         struct list_head *list_start_pos;
652         unsigned int i=0;
653         int res;
655         if (list_empty(&handle->chains))
656                 return NULL;
658         /* First look at builtin chains */
659         list_for_each(pos, &handle->chains) {
660                 struct chain_head *c = list_entry(pos, struct chain_head, list);
661                 if (!iptcc_is_builtin(c))
662                         break;
663                 if (!strcmp(c->name, name))
664                         return c;
665         }
667         /* Find a smart place to start the search via chain index */
668         //list_start_pos = iptcc_linearly_search_chain_index(name, handle);
669         list_start_pos = iptcc_bsearch_chain_index(name, &i, handle);
671         /* Handel if bsearch bails out early */
672         if (list_start_pos == &handle->chains) {
673                 list_start_pos = pos;
674         }
675 #ifdef DEBUG
676         else {
677                 /* Verify result of bsearch against linearly index search */
678                 struct list_head *test_pos;
679                 struct chain_head *test_c, *tmp_c;
680                 test_pos = iptcc_linearly_search_chain_index(name, handle);
681                 if (list_start_pos != test_pos) {
682                         debug("BUG in chain_index search\n");
683                         test_c=list_entry(test_pos,      struct chain_head,list);
684                         tmp_c =list_entry(list_start_pos,struct chain_head,list);
685                         debug("Verify search found:\n");
686                         debug(" Chain:%s\n", test_c->name);
687                         debug("BSearch found:\n");
688                         debug(" Chain:%s\n", tmp_c->name);
689                         exit(42);
690                 }
691         }
692 #endif
694         /* Initial/special case, no user defined chains */
695         if (handle->num_chains == 0)
696                 return NULL;
698         /* Start searching through the chain list */
699         list_for_each(pos, list_start_pos->prev) {
700                 struct chain_head *c = list_entry(pos, struct chain_head, list);
701                 res = strcmp(c->name, name);
702                 debug("List search name:%s == %s res:%d\n", name, c->name, res);
703                 if (res==0)
704                         return c;
706                 /* We can stop earlier as we know list is sorted */
707                 if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/
708                         debug(" Not in list, walked too far, sorted list\n");
709                         return NULL;
710                 }
712                 /* Stop on wrap around, if list head is reached */
713                 if (pos == &handle->chains) {
714                         debug("Stop, list head reached\n");
715                         return NULL;
716                 }
717         }
719         debug("List search NOT found name:%s\n", name);
720         return NULL;
723 /* called when rule is to be removed from cache */
724 static void iptcc_delete_rule(struct rule_head *r)
726         DEBUGP("deleting rule %p (offset %u)\n", r, r->offset);
727         /* clean up reference count of called chain */
728         if (r->type == IPTCC_R_JUMP
729             && r->jump)
730                 r->jump->references--;
732         list_del(&r->list);
733         free(r);
737 /**********************************************************************
738  * RULESET PARSER (blob -> cache)
739  **********************************************************************/
741 /* Delete policy rule of previous chain, since cache doesn't contain
742  * chain policy rules.
743  * WARNING: This function has ugly design and relies on a lot of context, only
744  * to be called from specific places within the parser */
745 static int __iptcc_p_del_policy(TC_HANDLE_T h, unsigned int num)
747         if (h->chain_iterator_cur) {
748                 /* policy rule is last rule */
749                 struct rule_head *pr = (struct rule_head *)
750                         h->chain_iterator_cur->rules.prev;
752                 /* save verdict */
753                 h->chain_iterator_cur->verdict = 
754                         *(int *)GET_TARGET(pr->entry)->data;
756                 /* save counter and counter_map information */
757                 h->chain_iterator_cur->counter_map.maptype = 
758                                                 COUNTER_MAP_NORMAL_MAP;
759                 h->chain_iterator_cur->counter_map.mappos = num-1;
760                 memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters, 
761                         sizeof(h->chain_iterator_cur->counters));
763                 /* foot_offset points to verdict rule */
764                 h->chain_iterator_cur->foot_index = num;
765                 h->chain_iterator_cur->foot_offset = pr->offset;
767                 /* delete rule from cache */
768                 iptcc_delete_rule(pr);
769                 h->chain_iterator_cur->num_rules--;
771                 return 1;
772         }
773         return 0;
776 /* alphabetically insert a chain into the list */
777 static inline void iptc_insert_chain(TC_HANDLE_T h, struct chain_head *c)
779         struct chain_head *tmp;
780         struct list_head  *list_start_pos;
781         unsigned int i=1;
783         /* Find a smart place to start the insert search */
784         list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h);
786         /* Handle the case, where chain.name is smaller than index[0] */
787         if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) {
788                 h->chain_index[0] = c; /* Update chain index head */
789                 list_start_pos = h->chains.next;
790                 debug("Update chain_index[0] with %s\n", c->name);
791         }
793         /* Handel if bsearch bails out early */
794         if (list_start_pos == &h->chains) {
795                 list_start_pos = h->chains.next;
796         }
798         /* sort only user defined chains */
799         if (!c->hooknum) {
800                 list_for_each_entry(tmp, list_start_pos->prev, list) {
801                         if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) {
802                                 list_add(&c->list, tmp->list.prev);
803                                 return;
804                         }
806                         /* Stop if list head is reached */
807                         if (&tmp->list == &h->chains) {
808                                 debug("Insert, list head reached add to tail\n");
809                                 break;
810                         }
811                 }
812         }
814         /* survived till end of list: add at tail */
815         list_add_tail(&c->list, &h->chains);
818 /* Another ugly helper function split out of cache_add_entry to make it less
819  * spaghetti code */
820 static void __iptcc_p_add_chain(TC_HANDLE_T h, struct chain_head *c,
821                                 unsigned int offset, unsigned int *num)
823         struct list_head  *tail = h->chains.prev;
824         struct chain_head *ctail;
826         __iptcc_p_del_policy(h, *num);
828         c->head_offset = offset;
829         c->index = *num;
831         /* Chains from kernel are already sorted, as they are inserted
832          * sorted. But there exists an issue when shifting to 1.4.0
833          * from an older version, as old versions allow last created
834          * chain to be unsorted.
835          */
836         if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/
837                 list_add_tail(&c->list, &h->chains);
838         else {
839                 ctail = list_entry(tail, struct chain_head, list);
840                 if (strcmp(c->name, ctail->name) > 0)
841                         list_add_tail(&c->list, &h->chains);/* Already sorted*/
842                 else
843                         iptc_insert_chain(h, c);/* Was not sorted */
844         }
846         h->chain_iterator_cur = c;
849 /* main parser function: add an entry from the blob to the cache */
850 static int cache_add_entry(STRUCT_ENTRY *e, 
851                            TC_HANDLE_T h, 
852                            STRUCT_ENTRY **prev,
853                            unsigned int *num)
855         unsigned int builtin;
856         unsigned int offset = (char *)e - (char *)h->entries->entrytable;
858         DEBUGP("entering...");
860         /* Last entry ("policy rule"). End it.*/
861         if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) {
862                 /* This is the ERROR node at the end of the chain */
863                 DEBUGP_C("%u:%u: end of table:\n", *num, offset);
865                 __iptcc_p_del_policy(h, *num);
867                 h->chain_iterator_cur = NULL;
868                 goto out_inc;
869         }
871         /* We know this is the start of a new chain if it's an ERROR
872          * target, or a hook entry point */
874         if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) {
875                 struct chain_head *c = 
876                         iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0);
877                 DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset, 
878                         (char *)c->name, c);
879                 if (!c) {
880                         errno = -ENOMEM;
881                         return -1;
882                 }
883                 h->num_chains++; /* New user defined chain */
885                 __iptcc_p_add_chain(h, c, offset, num);
887         } else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) {
888                 struct chain_head *c =
889                         iptcc_alloc_chain_head((char *)hooknames[builtin-1], 
890                                                 builtin);
891                 DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n", 
892                         *num, offset, c, &c->rules);
893                 if (!c) {
894                         errno = -ENOMEM;
895                         return -1;
896                 }
898                 c->hooknum = builtin;
900                 __iptcc_p_add_chain(h, c, offset, num);
902                 /* FIXME: this is ugly. */
903                 goto new_rule;
904         } else {
905                 /* has to be normal rule */
906                 struct rule_head *r;
907 new_rule:
909                 if (!(r = iptcc_alloc_rule(h->chain_iterator_cur, 
910                                            e->next_offset))) {
911                         errno = ENOMEM;
912                         return -1;
913                 }
914                 DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r);
916                 r->index = *num;
917                 r->offset = offset;
918                 memcpy(r->entry, e, e->next_offset);
919                 r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP;
920                 r->counter_map.mappos = r->index;
922                 /* handling of jumps, etc. */
923                 if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) {
924                         STRUCT_STANDARD_TARGET *t;
926                         t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
927                         if (t->target.u.target_size
928                             != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
929                                 errno = EINVAL;
930                                 return -1;
931                         }
933                         if (t->verdict < 0) {
934                                 DEBUGP_C("standard, verdict=%d\n", t->verdict);
935                                 r->type = IPTCC_R_STANDARD;
936                         } else if (t->verdict == r->offset+e->next_offset) {
937                                 DEBUGP_C("fallthrough\n");
938                                 r->type = IPTCC_R_FALLTHROUGH;
939                         } else {
940                                 DEBUGP_C("jump, target=%u\n", t->verdict);
941                                 r->type = IPTCC_R_JUMP;
942                                 /* Jump target fixup has to be deferred
943                                  * until second pass, since we migh not
944                                  * yet have parsed the target */
945                         }
946                 } else {
947                         DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name);
948                         r->type = IPTCC_R_MODULE;
949                 }
951                 list_add_tail(&r->list, &h->chain_iterator_cur->rules);
952                 h->chain_iterator_cur->num_rules++;
953         }
954 out_inc:
955         (*num)++;
956         return 0;
960 /* parse an iptables blob into it's pieces */
961 static int parse_table(TC_HANDLE_T h)
963         STRUCT_ENTRY *prev;
964         unsigned int num = 0;
965         struct chain_head *c;
967         /* First pass: over ruleset blob */
968         ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
969                         cache_add_entry, h, &prev, &num);
971         /* Build the chain index, used for chain list search speedup */
972         if ((iptcc_chain_index_alloc(h)) < 0)
973                 return -ENOMEM;
974         iptcc_chain_index_build(h);
976         /* Second pass: fixup parsed data from first pass */
977         list_for_each_entry(c, &h->chains, list) {
978                 struct rule_head *r;
979                 list_for_each_entry(r, &c->rules, list) {
980                         struct chain_head *lc;
981                         STRUCT_STANDARD_TARGET *t;
983                         if (r->type != IPTCC_R_JUMP)
984                                 continue;
986                         t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
987                         lc = iptcc_find_chain_by_offset(h, t->verdict);
988                         if (!lc)
989                                 return -1;
990                         r->jump = lc;
991                         lc->references++;
992                 }
993         }
995         /* FIXME: sort chains */
997         return 1;
1001 /**********************************************************************
1002  * RULESET COMPILATION (cache -> blob)
1003  **********************************************************************/
1005 /* Convenience structures */
1006 struct iptcb_chain_start{
1007         STRUCT_ENTRY e;
1008         struct ipt_error_target name;
1009 };
1010 #define IPTCB_CHAIN_START_SIZE  (sizeof(STRUCT_ENTRY) +                 \
1011                                  ALIGN(sizeof(struct ipt_error_target)))
1013 struct iptcb_chain_foot {
1014         STRUCT_ENTRY e;
1015         STRUCT_STANDARD_TARGET target;
1016 };
1017 #define IPTCB_CHAIN_FOOT_SIZE   (sizeof(STRUCT_ENTRY) +                 \
1018                                  ALIGN(sizeof(STRUCT_STANDARD_TARGET)))
1020 struct iptcb_chain_error {
1021         STRUCT_ENTRY entry;
1022         struct ipt_error_target target;
1023 };
1024 #define IPTCB_CHAIN_ERROR_SIZE  (sizeof(STRUCT_ENTRY) +                 \
1025                                  ALIGN(sizeof(struct ipt_error_target)))
1029 /* compile rule from cache into blob */
1030 static inline int iptcc_compile_rule (TC_HANDLE_T h, STRUCT_REPLACE *repl, struct rule_head *r)
1032         /* handle jumps */
1033         if (r->type == IPTCC_R_JUMP) {
1034                 STRUCT_STANDARD_TARGET *t;
1035                 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1036                 /* memset for memcmp convenience on delete/replace */
1037                 memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
1038                 strcpy(t->target.u.user.name, STANDARD_TARGET);
1039                 /* Jumps can only happen to builtin chains, so we
1040                  * can safely assume that they always have a header */
1041                 t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE;
1042         } else if (r->type == IPTCC_R_FALLTHROUGH) {
1043                 STRUCT_STANDARD_TARGET *t;
1044                 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1045                 t->verdict = r->offset + r->size;
1046         }
1047         
1048         /* copy entry from cache to blob */
1049         memcpy((char *)repl->entries+r->offset, r->entry, r->size);
1051         return 1;
1054 /* compile chain from cache into blob */
1055 static int iptcc_compile_chain(TC_HANDLE_T h, STRUCT_REPLACE *repl, struct chain_head *c)
1057         int ret;
1058         struct rule_head *r;
1059         struct iptcb_chain_start *head;
1060         struct iptcb_chain_foot *foot;
1062         /* only user-defined chains have heaer */
1063         if (!iptcc_is_builtin(c)) {
1064                 /* put chain header in place */
1065                 head = (void *)repl->entries + c->head_offset;
1066                 head->e.target_offset = sizeof(STRUCT_ENTRY);
1067                 head->e.next_offset = IPTCB_CHAIN_START_SIZE;
1068                 strcpy(head->name.t.u.user.name, ERROR_TARGET);
1069                 head->name.t.u.target_size = 
1070                                 ALIGN(sizeof(struct ipt_error_target));
1071                 strcpy(head->name.error, c->name);
1072         } else {
1073                 repl->hook_entry[c->hooknum-1] = c->head_offset;        
1074                 repl->underflow[c->hooknum-1] = c->foot_offset;
1075         }
1077         /* iterate over rules */
1078         list_for_each_entry(r, &c->rules, list) {
1079                 ret = iptcc_compile_rule(h, repl, r);
1080                 if (ret < 0)
1081                         return ret;
1082         }
1084         /* put chain footer in place */
1085         foot = (void *)repl->entries + c->foot_offset;
1086         foot->e.target_offset = sizeof(STRUCT_ENTRY);
1087         foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE;
1088         strcpy(foot->target.target.u.user.name, STANDARD_TARGET);
1089         foot->target.target.u.target_size =
1090                                 ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1091         /* builtin targets have verdict, others return */
1092         if (iptcc_is_builtin(c))
1093                 foot->target.verdict = c->verdict;
1094         else
1095                 foot->target.verdict = RETURN;
1096         /* set policy-counters */
1097         memcpy(&foot->e.counters, &c->counters, sizeof(STRUCT_COUNTERS));
1099         return 0;
1102 /* calculate offset and number for every rule in the cache */
1103 static int iptcc_compile_chain_offsets(TC_HANDLE_T h, struct chain_head *c,
1104                                        unsigned int *offset, unsigned int *num)
1106         struct rule_head *r;
1108         c->head_offset = *offset;
1109         DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset);
1111         if (!iptcc_is_builtin(c))  {
1112                 /* Chain has header */
1113                 *offset += sizeof(STRUCT_ENTRY) 
1114                              + ALIGN(sizeof(struct ipt_error_target));
1115                 (*num)++;
1116         }
1118         list_for_each_entry(r, &c->rules, list) {
1119                 DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num);
1120                 r->offset = *offset;
1121                 r->index = *num;
1122                 *offset += r->size;
1123                 (*num)++;
1124         }
1126         DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num, 
1127                 *offset, *num);
1128         c->foot_offset = *offset;
1129         c->foot_index = *num;
1130         *offset += sizeof(STRUCT_ENTRY)
1131                    + ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1132         (*num)++;
1134         return 1;
1137 /* put the pieces back together again */
1138 static int iptcc_compile_table_prep(TC_HANDLE_T h, unsigned int *size)
1140         struct chain_head *c;
1141         unsigned int offset = 0, num = 0;
1142         int ret = 0;
1144         /* First pass: calculate offset for every rule */
1145         list_for_each_entry(c, &h->chains, list) {
1146                 ret = iptcc_compile_chain_offsets(h, c, &offset, &num);
1147                 if (ret < 0)
1148                         return ret;
1149         }
1151         /* Append one error rule at end of chain */
1152         num++;
1153         offset += sizeof(STRUCT_ENTRY)
1154                   + ALIGN(sizeof(struct ipt_error_target));
1156         /* ruleset size is now in offset */
1157         *size = offset;
1158         return num;
1161 static int iptcc_compile_table(TC_HANDLE_T h, STRUCT_REPLACE *repl)
1163         struct chain_head *c;
1164         struct iptcb_chain_error *error;
1166         /* Second pass: copy from cache to offsets, fill in jumps */
1167         list_for_each_entry(c, &h->chains, list) {
1168                 int ret = iptcc_compile_chain(h, repl, c);
1169                 if (ret < 0)
1170                         return ret;
1171         }
1173         /* Append error rule at end of chain */
1174         error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE;
1175         error->entry.target_offset = sizeof(STRUCT_ENTRY);
1176         error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE;
1177         error->target.t.u.user.target_size = 
1178                 ALIGN(sizeof(struct ipt_error_target));
1179         strcpy((char *)&error->target.t.u.user.name, ERROR_TARGET);
1180         strcpy((char *)&error->target.error, "ERROR");
1182         return 1;
1185 /**********************************************************************
1186  * EXTERNAL API (operates on cache only)
1187  **********************************************************************/
1189 /* Allocate handle of given size */
1190 static TC_HANDLE_T
1191 alloc_handle(const char *tablename, unsigned int size, unsigned int num_rules)
1193         size_t len;
1194         TC_HANDLE_T h;
1196         len = sizeof(STRUCT_TC_HANDLE) + size;
1198         h = malloc(sizeof(STRUCT_TC_HANDLE));
1199         if (!h) {
1200                 errno = ENOMEM;
1201                 return NULL;
1202         }
1203         memset(h, 0, sizeof(*h));
1204         INIT_LIST_HEAD(&h->chains);
1205         strcpy(h->info.name, tablename);
1207         h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + size);
1208         if (!h->entries)
1209                 goto out_free_handle;
1211         strcpy(h->entries->name, tablename);
1212         h->entries->size = size;
1214         return h;
1216 out_free_handle:
1217         free(h);
1219         return NULL;
1223 TC_HANDLE_T
1224 TC_INIT(const char *tablename)
1226         TC_HANDLE_T h;
1227         STRUCT_GETINFO info;
1228         unsigned int tmp;
1229         socklen_t s;
1231         iptc_fn = TC_INIT;
1233         if (strlen(tablename) >= TABLE_MAXNAMELEN) {
1234                 errno = EINVAL;
1235                 return NULL;
1236         }
1237         
1238         if (sockfd_use == 0) {
1239                 sockfd = socket(TC_AF, SOCK_RAW, IPPROTO_RAW);
1240                 if (sockfd < 0)
1241                         return NULL;
1242         }
1243         sockfd_use++;
1244 retry:
1245         s = sizeof(info);
1247         strcpy(info.name, tablename);
1248         if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) {
1249                 if (--sockfd_use == 0) {
1250                         close(sockfd);
1251                         sockfd = -1;
1252                 }
1253                 return NULL;
1254         }
1256         DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n",
1257                 info.valid_hooks, info.num_entries, info.size);
1259         if ((h = alloc_handle(info.name, info.size, info.num_entries))
1260             == NULL) {
1261                 if (--sockfd_use == 0) {
1262                         close(sockfd);
1263                         sockfd = -1;
1264                 }
1265                 return NULL;
1266         }
1268         /* Initialize current state */
1269         h->info = info;
1271         h->entries->size = h->info.size;
1273         tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size;
1275         if (getsockopt(sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries,
1276                        &tmp) < 0)
1277                 goto error;
1279 #ifdef IPTC_DEBUG2
1280         {
1281                 int fd = open("/tmp/libiptc-so_get_entries.blob", 
1282                                 O_CREAT|O_WRONLY);
1283                 if (fd >= 0) {
1284                         write(fd, h->entries, tmp);
1285                         close(fd);
1286                 }
1287         }
1288 #endif
1290         if (parse_table(h) < 0)
1291                 goto error;
1293         CHECK(h);
1294         return h;
1295 error:
1296         TC_FREE(&h);
1297         /* A different process changed the ruleset size, retry */
1298         if (errno == EAGAIN)
1299                 goto retry;
1300         return NULL;
1303 void
1304 TC_FREE(TC_HANDLE_T *h)
1306         struct chain_head *c, *tmp;
1308         iptc_fn = TC_FREE;
1309         if (--sockfd_use == 0) {
1310                 close(sockfd);
1311                 sockfd = -1;
1312         }
1314         list_for_each_entry_safe(c, tmp, &(*h)->chains, list) {
1315                 struct rule_head *r, *rtmp;
1317                 list_for_each_entry_safe(r, rtmp, &c->rules, list) {
1318                         free(r);
1319                 }
1321                 free(c);
1322         }
1324         iptcc_chain_index_free(*h);
1326         free((*h)->entries);
1327         free(*h);
1329         *h = NULL;
1332 static inline int
1333 print_match(const STRUCT_ENTRY_MATCH *m)
1335         printf("Match name: `%s'\n", m->u.user.name);
1336         return 0;
1339 static int dump_entry(STRUCT_ENTRY *e, const TC_HANDLE_T handle);
1340  
1341 void
1342 TC_DUMP_ENTRIES(const TC_HANDLE_T handle)
1344         iptc_fn = TC_DUMP_ENTRIES;
1345         CHECK(handle);
1347         printf("libiptc v%s. %u bytes.\n",
1348                XTABLES_VERSION, handle->entries->size);
1349         printf("Table `%s'\n", handle->info.name);
1350         printf("Hooks: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
1351                handle->info.hook_entry[HOOK_PRE_ROUTING],
1352                handle->info.hook_entry[HOOK_LOCAL_IN],
1353                handle->info.hook_entry[HOOK_FORWARD],
1354                handle->info.hook_entry[HOOK_LOCAL_OUT],
1355                handle->info.hook_entry[HOOK_POST_ROUTING]);
1356         printf("Underflows: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
1357                handle->info.underflow[HOOK_PRE_ROUTING],
1358                handle->info.underflow[HOOK_LOCAL_IN],
1359                handle->info.underflow[HOOK_FORWARD],
1360                handle->info.underflow[HOOK_LOCAL_OUT],
1361                handle->info.underflow[HOOK_POST_ROUTING]);
1363         ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size,
1364                       dump_entry, handle);
1367 /* Does this chain exist? */
1368 int TC_IS_CHAIN(const char *chain, const TC_HANDLE_T handle)
1370         iptc_fn = TC_IS_CHAIN;
1371         return iptcc_find_label(chain, handle) != NULL;
1374 static void iptcc_chain_iterator_advance(TC_HANDLE_T handle)
1376         struct chain_head *c = handle->chain_iterator_cur;
1378         if (c->list.next == &handle->chains)
1379                 handle->chain_iterator_cur = NULL;
1380         else
1381                 handle->chain_iterator_cur = 
1382                         list_entry(c->list.next, struct chain_head, list);
1385 /* Iterator functions to run through the chains. */
1386 const char *
1387 TC_FIRST_CHAIN(TC_HANDLE_T *handle)
1389         struct chain_head *c = list_entry((*handle)->chains.next,
1390                                           struct chain_head, list);
1392         iptc_fn = TC_FIRST_CHAIN;
1395         if (list_empty(&(*handle)->chains)) {
1396                 DEBUGP(": no chains\n");
1397                 return NULL;
1398         }
1400         (*handle)->chain_iterator_cur = c;
1401         iptcc_chain_iterator_advance(*handle);
1403         DEBUGP(": returning `%s'\n", c->name);
1404         return c->name;
1407 /* Iterator functions to run through the chains.  Returns NULL at end. */
1408 const char *
1409 TC_NEXT_CHAIN(TC_HANDLE_T *handle)
1411         struct chain_head *c = (*handle)->chain_iterator_cur;
1413         iptc_fn = TC_NEXT_CHAIN;
1415         if (!c) {
1416                 DEBUGP(": no more chains\n");
1417                 return NULL;
1418         }
1420         iptcc_chain_iterator_advance(*handle);
1421         
1422         DEBUGP(": returning `%s'\n", c->name);
1423         return c->name;
1426 /* Get first rule in the given chain: NULL for empty chain. */
1427 const STRUCT_ENTRY *
1428 TC_FIRST_RULE(const char *chain, TC_HANDLE_T *handle)
1430         struct chain_head *c;
1431         struct rule_head *r;
1433         iptc_fn = TC_FIRST_RULE;
1435         DEBUGP("first rule(%s): ", chain);
1437         c = iptcc_find_label(chain, *handle);
1438         if (!c) {
1439                 errno = ENOENT;
1440                 return NULL;
1441         }
1443         /* Empty chain: single return/policy rule */
1444         if (list_empty(&c->rules)) {
1445                 DEBUGP_C("no rules, returning NULL\n");
1446                 return NULL;
1447         }
1449         r = list_entry(c->rules.next, struct rule_head, list);
1450         (*handle)->rule_iterator_cur = r;
1451         DEBUGP_C("%p\n", r);
1453         return r->entry;
1456 /* Returns NULL when rules run out. */
1457 const STRUCT_ENTRY *
1458 TC_NEXT_RULE(const STRUCT_ENTRY *prev, TC_HANDLE_T *handle)
1460         struct rule_head *r;
1462         iptc_fn = TC_NEXT_RULE;
1463         DEBUGP("rule_iterator_cur=%p...", (*handle)->rule_iterator_cur);
1465         if (!(*handle)->rule_iterator_cur) {
1466                 DEBUGP_C("returning NULL\n");
1467                 return NULL;
1468         }
1469         
1470         r = list_entry((*handle)->rule_iterator_cur->list.next, 
1471                         struct rule_head, list);
1473         iptc_fn = TC_NEXT_RULE;
1475         DEBUGP_C("next=%p, head=%p...", &r->list, 
1476                 &(*handle)->rule_iterator_cur->chain->rules);
1478         if (&r->list == &(*handle)->rule_iterator_cur->chain->rules) {
1479                 (*handle)->rule_iterator_cur = NULL;
1480                 DEBUGP_C("finished, returning NULL\n");
1481                 return NULL;
1482         }
1484         (*handle)->rule_iterator_cur = r;
1486         /* NOTE: prev is without any influence ! */
1487         DEBUGP_C("returning rule %p\n", r);
1488         return r->entry;
1491 /* How many rules in this chain? */
1492 static unsigned int
1493 TC_NUM_RULES(const char *chain, TC_HANDLE_T *handle)
1495         struct chain_head *c;
1496         iptc_fn = TC_NUM_RULES;
1497         CHECK(*handle);
1499         c = iptcc_find_label(chain, *handle);
1500         if (!c) {
1501                 errno = ENOENT;
1502                 return (unsigned int)-1;
1503         }
1504         
1505         return c->num_rules;
1508 static const STRUCT_ENTRY *
1509 TC_GET_RULE(const char *chain, unsigned int n, TC_HANDLE_T *handle)
1511         struct chain_head *c;
1512         struct rule_head *r;
1513         
1514         iptc_fn = TC_GET_RULE;
1516         CHECK(*handle);
1518         c = iptcc_find_label(chain, *handle);
1519         if (!c) {
1520                 errno = ENOENT;
1521                 return NULL;
1522         }
1524         r = iptcc_get_rule_num(c, n);
1525         if (!r)
1526                 return NULL;
1527         return r->entry;
1530 /* Returns a pointer to the target name of this position. */
1531 static const char *standard_target_map(int verdict)
1533         switch (verdict) {
1534                 case RETURN:
1535                         return LABEL_RETURN;
1536                         break;
1537                 case -NF_ACCEPT-1:
1538                         return LABEL_ACCEPT;
1539                         break;
1540                 case -NF_DROP-1:
1541                         return LABEL_DROP;
1542                         break;
1543                 case -NF_QUEUE-1:
1544                         return LABEL_QUEUE;
1545                         break;
1546                 default:
1547                         fprintf(stderr, "ERROR: %d not a valid target)\n",
1548                                 verdict);
1549                         abort();
1550                         break;
1551         }
1552         /* not reached */
1553         return NULL;
1556 /* Returns a pointer to the target name of this position. */
1557 const char *TC_GET_TARGET(const STRUCT_ENTRY *ce,
1558                           TC_HANDLE_T *handle)
1560         STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce;
1561         struct rule_head *r = container_of(e, struct rule_head, entry[0]);
1563         iptc_fn = TC_GET_TARGET;
1565         switch(r->type) {
1566                 int spos;
1567                 case IPTCC_R_FALLTHROUGH:
1568                         return "";
1569                         break;
1570                 case IPTCC_R_JUMP:
1571                         DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name);
1572                         return r->jump->name;
1573                         break;
1574                 case IPTCC_R_STANDARD:
1575                         spos = *(int *)GET_TARGET(e)->data;
1576                         DEBUGP("r=%p, spos=%d'\n", r, spos);
1577                         return standard_target_map(spos);
1578                         break;
1579                 case IPTCC_R_MODULE:
1580                         return GET_TARGET(e)->u.user.name;
1581                         break;
1582         }
1583         return NULL;
1585 /* Is this a built-in chain?  Actually returns hook + 1. */
1586 int
1587 TC_BUILTIN(const char *chain, const TC_HANDLE_T handle)
1589         struct chain_head *c;
1590         
1591         iptc_fn = TC_BUILTIN;
1593         c = iptcc_find_label(chain, handle);
1594         if (!c) {
1595                 errno = ENOENT;
1596                 return 0;
1597         }
1599         return iptcc_is_builtin(c);
1602 /* Get the policy of a given built-in chain */
1603 const char *
1604 TC_GET_POLICY(const char *chain,
1605               STRUCT_COUNTERS *counters,
1606               TC_HANDLE_T *handle)
1608         struct chain_head *c;
1610         iptc_fn = TC_GET_POLICY;
1612         DEBUGP("called for chain %s\n", chain);
1614         c = iptcc_find_label(chain, *handle);
1615         if (!c) {
1616                 errno = ENOENT;
1617                 return NULL;
1618         }
1620         if (!iptcc_is_builtin(c))
1621                 return NULL;
1623         *counters = c->counters;
1625         return standard_target_map(c->verdict);
1628 static int
1629 iptcc_standard_map(struct rule_head *r, int verdict)
1631         STRUCT_ENTRY *e = r->entry;
1632         STRUCT_STANDARD_TARGET *t;
1634         t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
1636         if (t->target.u.target_size
1637             != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
1638                 errno = EINVAL;
1639                 return 0;
1640         }
1641         /* memset for memcmp convenience on delete/replace */
1642         memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
1643         strcpy(t->target.u.user.name, STANDARD_TARGET);
1644         t->verdict = verdict;
1646         r->type = IPTCC_R_STANDARD;
1648         return 1;
1651 static int
1652 iptcc_map_target(const TC_HANDLE_T handle,
1653            struct rule_head *r)
1655         STRUCT_ENTRY *e = r->entry;
1656         STRUCT_ENTRY_TARGET *t = GET_TARGET(e);
1658         /* Maybe it's empty (=> fall through) */
1659         if (strcmp(t->u.user.name, "") == 0) {
1660                 r->type = IPTCC_R_FALLTHROUGH;
1661                 return 1;
1662         }
1663         /* Maybe it's a standard target name... */
1664         else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0)
1665                 return iptcc_standard_map(r, -NF_ACCEPT - 1);
1666         else if (strcmp(t->u.user.name, LABEL_DROP) == 0)
1667                 return iptcc_standard_map(r, -NF_DROP - 1);
1668         else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0)
1669                 return iptcc_standard_map(r, -NF_QUEUE - 1);
1670         else if (strcmp(t->u.user.name, LABEL_RETURN) == 0)
1671                 return iptcc_standard_map(r, RETURN);
1672         else if (TC_BUILTIN(t->u.user.name, handle)) {
1673                 /* Can't jump to builtins. */
1674                 errno = EINVAL;
1675                 return 0;
1676         } else {
1677                 /* Maybe it's an existing chain name. */
1678                 struct chain_head *c;
1679                 DEBUGP("trying to find chain `%s': ", t->u.user.name);
1681                 c = iptcc_find_label(t->u.user.name, handle);
1682                 if (c) {
1683                         DEBUGP_C("found!\n");
1684                         r->type = IPTCC_R_JUMP;
1685                         r->jump = c;
1686                         c->references++;
1687                         return 1;
1688                 }
1689                 DEBUGP_C("not found :(\n");
1690         }
1692         /* Must be a module?  If not, kernel will reject... */
1693         /* memset to all 0 for your memcmp convenience: don't clear version */
1694         memset(t->u.user.name + strlen(t->u.user.name),
1695                0,
1696                FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name));
1697         r->type = IPTCC_R_MODULE;
1698         set_changed(handle);
1699         return 1;
1702 /* Insert the entry `fw' in chain `chain' into position `rulenum'. */
1703 int
1704 TC_INSERT_ENTRY(const IPT_CHAINLABEL chain,
1705                 const STRUCT_ENTRY *e,
1706                 unsigned int rulenum,
1707                 TC_HANDLE_T *handle)
1709         struct chain_head *c;
1710         struct rule_head *r;
1711         struct list_head *prev;
1713         iptc_fn = TC_INSERT_ENTRY;
1715         if (!(c = iptcc_find_label(chain, *handle))) {
1716                 errno = ENOENT;
1717                 return 0;
1718         }
1720         /* first rulenum index = 0
1721            first c->num_rules index = 1 */
1722         if (rulenum > c->num_rules) {
1723                 errno = E2BIG;
1724                 return 0;
1725         }
1727         /* If we are inserting at the end just take advantage of the
1728            double linked list, insert will happen before the entry
1729            prev points to. */
1730         if (rulenum == c->num_rules) {
1731                 prev = &c->rules;
1732         } else if (rulenum + 1 <= c->num_rules/2) {
1733                 r = iptcc_get_rule_num(c, rulenum + 1);
1734                 prev = &r->list;
1735         } else {
1736                 r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1737                 prev = &r->list;
1738         }
1740         if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1741                 errno = ENOMEM;
1742                 return 0;
1743         }
1745         memcpy(r->entry, e, e->next_offset);
1746         r->counter_map.maptype = COUNTER_MAP_SET;
1748         if (!iptcc_map_target(*handle, r)) {
1749                 free(r);
1750                 return 0;
1751         }
1753         list_add_tail(&r->list, prev);
1754         c->num_rules++;
1756         set_changed(*handle);
1758         return 1;
1761 /* Atomically replace rule `rulenum' in `chain' with `fw'. */
1762 int
1763 TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain,
1764                  const STRUCT_ENTRY *e,
1765                  unsigned int rulenum,
1766                  TC_HANDLE_T *handle)
1768         struct chain_head *c;
1769         struct rule_head *r, *old;
1771         iptc_fn = TC_REPLACE_ENTRY;
1773         if (!(c = iptcc_find_label(chain, *handle))) {
1774                 errno = ENOENT;
1775                 return 0;
1776         }
1778         if (rulenum >= c->num_rules) {
1779                 errno = E2BIG;
1780                 return 0;
1781         }
1783         /* Take advantage of the double linked list if possible. */
1784         if (rulenum + 1 <= c->num_rules/2) {
1785                 old = iptcc_get_rule_num(c, rulenum + 1);
1786         } else {
1787                 old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1788         }
1790         if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1791                 errno = ENOMEM;
1792                 return 0;
1793         }
1795         memcpy(r->entry, e, e->next_offset);
1796         r->counter_map.maptype = COUNTER_MAP_SET;
1798         if (!iptcc_map_target(*handle, r)) {
1799                 free(r);
1800                 return 0;
1801         }
1803         list_add(&r->list, &old->list);
1804         iptcc_delete_rule(old);
1806         set_changed(*handle);
1808         return 1;
1811 /* Append entry `fw' to chain `chain'.  Equivalent to insert with
1812    rulenum = length of chain. */
1813 int
1814 TC_APPEND_ENTRY(const IPT_CHAINLABEL chain,
1815                 const STRUCT_ENTRY *e,
1816                 TC_HANDLE_T *handle)
1818         struct chain_head *c;
1819         struct rule_head *r;
1821         iptc_fn = TC_APPEND_ENTRY;
1822         if (!(c = iptcc_find_label(chain, *handle))) {
1823                 DEBUGP("unable to find chain `%s'\n", chain);
1824                 errno = ENOENT;
1825                 return 0;
1826         }
1828         if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1829                 DEBUGP("unable to allocate rule for chain `%s'\n", chain);
1830                 errno = ENOMEM;
1831                 return 0;
1832         }
1834         memcpy(r->entry, e, e->next_offset);
1835         r->counter_map.maptype = COUNTER_MAP_SET;
1837         if (!iptcc_map_target(*handle, r)) {
1838                 DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1839                 free(r);
1840                 return 0;
1841         }
1843         list_add_tail(&r->list, &c->rules);
1844         c->num_rules++;
1846         set_changed(*handle);
1848         return 1;
1851 static inline int
1852 match_different(const STRUCT_ENTRY_MATCH *a,
1853                 const unsigned char *a_elems,
1854                 const unsigned char *b_elems,
1855                 unsigned char **maskptr)
1857         const STRUCT_ENTRY_MATCH *b;
1858         unsigned int i;
1860         /* Offset of b is the same as a. */
1861         b = (void *)b_elems + ((unsigned char *)a - a_elems);
1863         if (a->u.match_size != b->u.match_size)
1864                 return 1;
1866         if (strcmp(a->u.user.name, b->u.user.name) != 0)
1867                 return 1;
1869         *maskptr += ALIGN(sizeof(*a));
1871         for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++)
1872                 if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0)
1873                         return 1;
1874         *maskptr += i;
1875         return 0;
1878 static inline int
1879 target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask)
1881         unsigned int i;
1882         STRUCT_ENTRY_TARGET *ta, *tb;
1884         if (a->type != b->type)
1885                 return 0;
1887         ta = GET_TARGET(a->entry);
1888         tb = GET_TARGET(b->entry);
1890         switch (a->type) {
1891         case IPTCC_R_FALLTHROUGH:
1892                 return 1;
1893         case IPTCC_R_JUMP:
1894                 return a->jump == b->jump;
1895         case IPTCC_R_STANDARD:
1896                 return ((STRUCT_STANDARD_TARGET *)ta)->verdict
1897                         == ((STRUCT_STANDARD_TARGET *)tb)->verdict;
1898         case IPTCC_R_MODULE:
1899                 if (ta->u.target_size != tb->u.target_size)
1900                         return 0;
1901                 if (strcmp(ta->u.user.name, tb->u.user.name) != 0)
1902                         return 0;
1904                 for (i = 0; i < ta->u.target_size - sizeof(*ta); i++)
1905                         if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0)
1906                                 return 0;
1907                 return 1;
1908         default:
1909                 fprintf(stderr, "ERROR: bad type %i\n", a->type);
1910                 abort();
1911         }
1914 static unsigned char *
1915 is_same(const STRUCT_ENTRY *a,
1916         const STRUCT_ENTRY *b,
1917         unsigned char *matchmask);
1919 /* Delete the first rule in `chain' which matches `fw'. */
1920 int
1921 TC_DELETE_ENTRY(const IPT_CHAINLABEL chain,
1922                 const STRUCT_ENTRY *origfw,
1923                 unsigned char *matchmask,
1924                 TC_HANDLE_T *handle)
1926         struct chain_head *c;
1927         struct rule_head *r, *i;
1929         iptc_fn = TC_DELETE_ENTRY;
1930         if (!(c = iptcc_find_label(chain, *handle))) {
1931                 errno = ENOENT;
1932                 return 0;
1933         }
1935         /* Create a rule_head from origfw. */
1936         r = iptcc_alloc_rule(c, origfw->next_offset);
1937         if (!r) {
1938                 errno = ENOMEM;
1939                 return 0;
1940         }
1942         memcpy(r->entry, origfw, origfw->next_offset);
1943         r->counter_map.maptype = COUNTER_MAP_NOMAP;
1944         if (!iptcc_map_target(*handle, r)) {
1945                 DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1946                 free(r);
1947                 return 0;
1948         } else {
1949                 /* iptcc_map_target increment target chain references
1950                  * since this is a fake rule only used for matching
1951                  * the chain references count is decremented again. 
1952                  */
1953                 if (r->type == IPTCC_R_JUMP
1954                     && r->jump)
1955                         r->jump->references--;
1956         }
1958         list_for_each_entry(i, &c->rules, list) {
1959                 unsigned char *mask;
1961                 mask = is_same(r->entry, i->entry, matchmask);
1962                 if (!mask)
1963                         continue;
1965                 if (!target_same(r, i, mask))
1966                         continue;
1968                 /* If we are about to delete the rule that is the
1969                  * current iterator, move rule iterator back.  next
1970                  * pointer will then point to real next node */
1971                 if (i == (*handle)->rule_iterator_cur) {
1972                         (*handle)->rule_iterator_cur = 
1973                                 list_entry((*handle)->rule_iterator_cur->list.prev,
1974                                            struct rule_head, list);
1975                 }
1977                 c->num_rules--;
1978                 iptcc_delete_rule(i);
1980                 set_changed(*handle);
1981                 free(r);
1982                 return 1;
1983         }
1985         free(r);
1986         errno = ENOENT;
1987         return 0;
1991 /* Delete the rule in position `rulenum' in `chain'. */
1992 int
1993 TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain,
1994                     unsigned int rulenum,
1995                     TC_HANDLE_T *handle)
1997         struct chain_head *c;
1998         struct rule_head *r;
2000         iptc_fn = TC_DELETE_NUM_ENTRY;
2002         if (!(c = iptcc_find_label(chain, *handle))) {
2003                 errno = ENOENT;
2004                 return 0;
2005         }
2007         if (rulenum >= c->num_rules) {
2008                 errno = E2BIG;
2009                 return 0;
2010         }
2012         /* Take advantage of the double linked list if possible. */
2013         if (rulenum + 1 <= c->num_rules/2) {
2014                 r = iptcc_get_rule_num(c, rulenum + 1);
2015         } else {
2016                 r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
2017         }
2019         /* If we are about to delete the rule that is the current
2020          * iterator, move rule iterator back.  next pointer will then
2021          * point to real next node */
2022         if (r == (*handle)->rule_iterator_cur) {
2023                 (*handle)->rule_iterator_cur = 
2024                         list_entry((*handle)->rule_iterator_cur->list.prev,
2025                                    struct rule_head, list);
2026         }
2028         c->num_rules--;
2029         iptcc_delete_rule(r);
2031         set_changed(*handle);
2033         return 1;
2036 /* Check the packet `fw' on chain `chain'.  Returns the verdict, or
2037    NULL and sets errno. */
2038 const char *
2039 TC_CHECK_PACKET(const IPT_CHAINLABEL chain,
2040                 STRUCT_ENTRY *entry,
2041                 TC_HANDLE_T *handle)
2043         iptc_fn = TC_CHECK_PACKET;
2044         errno = ENOSYS;
2045         return NULL;
2048 /* Flushes the entries in the given chain (ie. empties chain). */
2049 int
2050 TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2052         struct chain_head *c;
2053         struct rule_head *r, *tmp;
2055         iptc_fn = TC_FLUSH_ENTRIES;
2056         if (!(c = iptcc_find_label(chain, *handle))) {
2057                 errno = ENOENT;
2058                 return 0;
2059         }
2061         list_for_each_entry_safe(r, tmp, &c->rules, list) {
2062                 iptcc_delete_rule(r);
2063         }
2065         c->num_rules = 0;
2067         set_changed(*handle);
2069         return 1;
2072 /* Zeroes the counters in a chain. */
2073 int
2074 TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2076         struct chain_head *c;
2077         struct rule_head *r;
2079         iptc_fn = TC_ZERO_ENTRIES;
2080         if (!(c = iptcc_find_label(chain, *handle))) {
2081                 errno = ENOENT;
2082                 return 0;
2083         }
2085         if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2086                 c->counter_map.maptype = COUNTER_MAP_ZEROED;
2088         list_for_each_entry(r, &c->rules, list) {
2089                 if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2090                         r->counter_map.maptype = COUNTER_MAP_ZEROED;
2091         }
2093         set_changed(*handle);
2095         return 1;
2098 STRUCT_COUNTERS *
2099 TC_READ_COUNTER(const IPT_CHAINLABEL chain,
2100                 unsigned int rulenum,
2101                 TC_HANDLE_T *handle)
2103         struct chain_head *c;
2104         struct rule_head *r;
2106         iptc_fn = TC_READ_COUNTER;
2107         CHECK(*handle);
2109         if (!(c = iptcc_find_label(chain, *handle))) {
2110                 errno = ENOENT;
2111                 return NULL;
2112         }
2114         if (!(r = iptcc_get_rule_num(c, rulenum))) {
2115                 errno = E2BIG;
2116                 return NULL;
2117         }
2119         return &r->entry[0].counters;
2122 int
2123 TC_ZERO_COUNTER(const IPT_CHAINLABEL chain,
2124                 unsigned int rulenum,
2125                 TC_HANDLE_T *handle)
2127         struct chain_head *c;
2128         struct rule_head *r;
2129         
2130         iptc_fn = TC_ZERO_COUNTER;
2131         CHECK(*handle);
2133         if (!(c = iptcc_find_label(chain, *handle))) {
2134                 errno = ENOENT;
2135                 return 0;
2136         }
2138         if (!(r = iptcc_get_rule_num(c, rulenum))) {
2139                 errno = E2BIG;
2140                 return 0;
2141         }
2143         if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2144                 r->counter_map.maptype = COUNTER_MAP_ZEROED;
2146         set_changed(*handle);
2148         return 1;
2151 int 
2152 TC_SET_COUNTER(const IPT_CHAINLABEL chain,
2153                unsigned int rulenum,
2154                STRUCT_COUNTERS *counters,
2155                TC_HANDLE_T *handle)
2157         struct chain_head *c;
2158         struct rule_head *r;
2159         STRUCT_ENTRY *e;
2161         iptc_fn = TC_SET_COUNTER;
2162         CHECK(*handle);
2164         if (!(c = iptcc_find_label(chain, *handle))) {
2165                 errno = ENOENT;
2166                 return 0;
2167         }
2169         if (!(r = iptcc_get_rule_num(c, rulenum))) {
2170                 errno = E2BIG;
2171                 return 0;
2172         }
2174         e = r->entry;
2175         r->counter_map.maptype = COUNTER_MAP_SET;
2177         memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS));
2179         set_changed(*handle);
2181         return 1;
2184 /* Creates a new chain. */
2185 /* To create a chain, create two rules: error node and unconditional
2186  * return. */
2187 int
2188 TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2190         static struct chain_head *c;
2191         int capacity;
2192         int exceeded;
2194         iptc_fn = TC_CREATE_CHAIN;
2196         /* find_label doesn't cover built-in targets: DROP, ACCEPT,
2197            QUEUE, RETURN. */
2198         if (iptcc_find_label(chain, *handle)
2199             || strcmp(chain, LABEL_DROP) == 0
2200             || strcmp(chain, LABEL_ACCEPT) == 0
2201             || strcmp(chain, LABEL_QUEUE) == 0
2202             || strcmp(chain, LABEL_RETURN) == 0) {
2203                 DEBUGP("Chain `%s' already exists\n", chain);
2204                 errno = EEXIST;
2205                 return 0;
2206         }
2208         if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) {
2209                 DEBUGP("Chain name `%s' too long\n", chain);
2210                 errno = EINVAL;
2211                 return 0;
2212         }
2214         c = iptcc_alloc_chain_head(chain, 0);
2215         if (!c) {
2216                 DEBUGP("Cannot allocate memory for chain `%s'\n", chain);
2217                 errno = ENOMEM;
2218                 return 0;
2220         }
2221         (*handle)->num_chains++; /* New user defined chain */
2223         DEBUGP("Creating chain `%s'\n", chain);
2224         iptc_insert_chain(*handle, c); /* Insert sorted */
2226         /* Inserting chains don't change the correctness of the chain
2227          * index (except if its smaller than index[0], but that
2228          * handled by iptc_insert_chain).  It only causes longer lists
2229          * in the buckets. Thus, only rebuild chain index when the
2230          * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains.
2231          */
2232         capacity = (*handle)->chain_index_sz * CHAIN_INDEX_BUCKET_LEN;
2233         exceeded = ((((*handle)->num_chains)-capacity));
2234         if (exceeded > CHAIN_INDEX_INSERT_MAX) {
2235                 debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n",
2236                       capacity, exceeded, (*handle)->num_chains);
2237                 iptcc_chain_index_rebuild(*handle);
2238         }
2240         set_changed(*handle);
2242         return 1;
2245 /* Get the number of references to this chain. */
2246 int
2247 TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain,
2248                   TC_HANDLE_T *handle)
2250         struct chain_head *c;
2252         iptc_fn = TC_GET_REFERENCES;
2253         if (!(c = iptcc_find_label(chain, *handle))) {
2254                 errno = ENOENT;
2255                 return 0;
2256         }
2258         *ref = c->references;
2260         return 1;
2263 /* Deletes a chain. */
2264 int
2265 TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2267         unsigned int references;
2268         struct chain_head *c;
2270         iptc_fn = TC_DELETE_CHAIN;
2272         if (!(c = iptcc_find_label(chain, *handle))) {
2273                 DEBUGP("cannot find chain `%s'\n", chain);
2274                 errno = ENOENT;
2275                 return 0;
2276         }
2278         if (TC_BUILTIN(chain, *handle)) {
2279                 DEBUGP("cannot remove builtin chain `%s'\n", chain);
2280                 errno = EINVAL;
2281                 return 0;
2282         }
2284         if (!TC_GET_REFERENCES(&references, chain, handle)) {
2285                 DEBUGP("cannot get references on chain `%s'\n", chain);
2286                 return 0;
2287         }
2289         if (references > 0) {
2290                 DEBUGP("chain `%s' still has references\n", chain);
2291                 errno = EMLINK;
2292                 return 0;
2293         }
2295         if (c->num_rules) {
2296                 DEBUGP("chain `%s' is not empty\n", chain);
2297                 errno = ENOTEMPTY;
2298                 return 0;
2299         }
2301         /* If we are about to delete the chain that is the current
2302          * iterator, move chain iterator forward. */
2303         if (c == (*handle)->chain_iterator_cur)
2304                 iptcc_chain_iterator_advance(*handle);
2306         (*handle)->num_chains--; /* One user defined chain deleted */
2308         //list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */
2309         iptcc_chain_index_delete_chain(c, *handle);
2310         free(c);
2312         DEBUGP("chain `%s' deleted\n", chain);
2314         set_changed(*handle);
2316         return 1;
2319 /* Renames a chain. */
2320 int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname,
2321                     const IPT_CHAINLABEL newname,
2322                     TC_HANDLE_T *handle)
2324         struct chain_head *c;
2325         iptc_fn = TC_RENAME_CHAIN;
2327         /* find_label doesn't cover built-in targets: DROP, ACCEPT,
2328            QUEUE, RETURN. */
2329         if (iptcc_find_label(newname, *handle)
2330             || strcmp(newname, LABEL_DROP) == 0
2331             || strcmp(newname, LABEL_ACCEPT) == 0
2332             || strcmp(newname, LABEL_QUEUE) == 0
2333             || strcmp(newname, LABEL_RETURN) == 0) {
2334                 errno = EEXIST;
2335                 return 0;
2336         }
2338         if (!(c = iptcc_find_label(oldname, *handle))
2339             || TC_BUILTIN(oldname, *handle)) {
2340                 errno = ENOENT;
2341                 return 0;
2342         }
2344         if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) {
2345                 errno = EINVAL;
2346                 return 0;
2347         }
2349         strncpy(c->name, newname, sizeof(IPT_CHAINLABEL));
2350         
2351         set_changed(*handle);
2353         return 1;
2356 /* Sets the policy on a built-in chain. */
2357 int
2358 TC_SET_POLICY(const IPT_CHAINLABEL chain,
2359               const IPT_CHAINLABEL policy,
2360               STRUCT_COUNTERS *counters,
2361               TC_HANDLE_T *handle)
2363         struct chain_head *c;
2365         iptc_fn = TC_SET_POLICY;
2367         if (!(c = iptcc_find_label(chain, *handle))) {
2368                 DEBUGP("cannot find chain `%s'\n", chain);
2369                 errno = ENOENT;
2370                 return 0;
2371         }
2373         if (!iptcc_is_builtin(c)) {
2374                 DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain);
2375                 errno = ENOENT;
2376                 return 0;
2377         }
2379         if (strcmp(policy, LABEL_ACCEPT) == 0)
2380                 c->verdict = -NF_ACCEPT - 1;
2381         else if (strcmp(policy, LABEL_DROP) == 0)
2382                 c->verdict = -NF_DROP - 1;
2383         else {
2384                 errno = EINVAL;
2385                 return 0;
2386         }
2388         if (counters) {
2389                 /* set byte and packet counters */
2390                 memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS));
2391                 c->counter_map.maptype = COUNTER_MAP_SET;
2392         } else {
2393                 c->counter_map.maptype = COUNTER_MAP_NOMAP;
2394         }
2396         set_changed(*handle);
2398         return 1;
2401 /* Without this, on gcc 2.7.2.3, we get:
2402    libiptc.c: In function `TC_COMMIT':
2403    libiptc.c:833: fixed or forbidden register was spilled.
2404    This may be due to a compiler bug or to impossible asm
2405    statements or clauses.
2406 */
2407 static void
2408 subtract_counters(STRUCT_COUNTERS *answer,
2409                   const STRUCT_COUNTERS *a,
2410                   const STRUCT_COUNTERS *b)
2412         answer->pcnt = a->pcnt - b->pcnt;
2413         answer->bcnt = a->bcnt - b->bcnt;
2417 static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx)
2419         newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0});
2420         DEBUGP_C("NOMAP => zero\n");
2423 static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters,
2424                                 STRUCT_REPLACE *repl, unsigned int idx,
2425                                 unsigned int mappos)
2427         /* Original read: X.
2428          * Atomic read on replacement: X + Y.
2429          * Currently in kernel: Z.
2430          * Want in kernel: X + Y + Z.
2431          * => Add in X + Y
2432          * => Add in replacement read.
2433          */
2434         newcounters->counters[idx] = repl->counters[mappos];
2435         DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos);
2438 static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters,
2439                                 STRUCT_REPLACE *repl, unsigned int idx,
2440                                 unsigned int mappos, STRUCT_COUNTERS *counters)
2442         /* Original read: X.
2443          * Atomic read on replacement: X + Y.
2444          * Currently in kernel: Z.
2445          * Want in kernel: Y + Z.
2446          * => Add in Y.
2447          * => Add in (replacement read - original read).
2448          */
2449         subtract_counters(&newcounters->counters[idx],
2450                           &repl->counters[mappos],
2451                           counters);
2452         DEBUGP_C("ZEROED => mappos %u\n", mappos);
2455 static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters,
2456                              unsigned int idx, STRUCT_COUNTERS *counters)
2458         /* Want to set counter (iptables-restore) */
2460         memcpy(&newcounters->counters[idx], counters,
2461                 sizeof(STRUCT_COUNTERS));
2463         DEBUGP_C("SET\n");
2467 int
2468 TC_COMMIT(TC_HANDLE_T *handle)
2470         /* Replace, then map back the counters. */
2471         STRUCT_REPLACE *repl;
2472         STRUCT_COUNTERS_INFO *newcounters;
2473         struct chain_head *c;
2474         int ret;
2475         size_t counterlen;
2476         int new_number;
2477         unsigned int new_size;
2479         iptc_fn = TC_COMMIT;
2480         CHECK(*handle);
2482         /* Don't commit if nothing changed. */
2483         if (!(*handle)->changed)
2484                 goto finished;
2486         new_number = iptcc_compile_table_prep(*handle, &new_size);
2487         if (new_number < 0) {
2488                 errno = ENOMEM;
2489                 goto out_zero;
2490         }
2492         repl = malloc(sizeof(*repl) + new_size);
2493         if (!repl) {
2494                 errno = ENOMEM;
2495                 goto out_zero;
2496         }
2497         memset(repl, 0, sizeof(*repl) + new_size);
2499 #if 0
2500         TC_DUMP_ENTRIES(*handle);
2501 #endif
2503         counterlen = sizeof(STRUCT_COUNTERS_INFO)
2504                         + sizeof(STRUCT_COUNTERS) * new_number;
2506         /* These are the old counters we will get from kernel */
2507         repl->counters = malloc(sizeof(STRUCT_COUNTERS)
2508                                 * (*handle)->info.num_entries);
2509         if (!repl->counters) {
2510                 errno = ENOMEM;
2511                 goto out_free_repl;
2512         }
2513         /* These are the counters we're going to put back, later. */
2514         newcounters = malloc(counterlen);
2515         if (!newcounters) {
2516                 errno = ENOMEM;
2517                 goto out_free_repl_counters;
2518         }
2519         memset(newcounters, 0, counterlen);
2521         strcpy(repl->name, (*handle)->info.name);
2522         repl->num_entries = new_number;
2523         repl->size = new_size;
2525         repl->num_counters = (*handle)->info.num_entries;
2526         repl->valid_hooks = (*handle)->info.valid_hooks;
2528         DEBUGP("num_entries=%u, size=%u, num_counters=%u\n",
2529                 repl->num_entries, repl->size, repl->num_counters);
2531         ret = iptcc_compile_table(*handle, repl);
2532         if (ret < 0) {
2533                 errno = ret;
2534                 goto out_free_newcounters;
2535         }
2538 #ifdef IPTC_DEBUG2
2539         {
2540                 int fd = open("/tmp/libiptc-so_set_replace.blob", 
2541                                 O_CREAT|O_WRONLY);
2542                 if (fd >= 0) {
2543                         write(fd, repl, sizeof(*repl) + repl->size);
2544                         close(fd);
2545                 }
2546         }
2547 #endif
2549         ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_REPLACE, repl,
2550                          sizeof(*repl) + repl->size);
2551         if (ret < 0)
2552                 goto out_free_newcounters;
2554         /* Put counters back. */
2555         strcpy(newcounters->name, (*handle)->info.name);
2556         newcounters->num_counters = new_number;
2558         list_for_each_entry(c, &(*handle)->chains, list) {
2559                 struct rule_head *r;
2561                 /* Builtin chains have their own counters */
2562                 if (iptcc_is_builtin(c)) {
2563                         DEBUGP("counter for chain-index %u: ", c->foot_index);
2564                         switch(c->counter_map.maptype) {
2565                         case COUNTER_MAP_NOMAP:
2566                                 counters_nomap(newcounters, c->foot_index);
2567                                 break;
2568                         case COUNTER_MAP_NORMAL_MAP:
2569                                 counters_normal_map(newcounters, repl,
2570                                                     c->foot_index, 
2571                                                     c->counter_map.mappos);
2572                                 break;
2573                         case COUNTER_MAP_ZEROED:
2574                                 counters_map_zeroed(newcounters, repl,
2575                                                     c->foot_index, 
2576                                                     c->counter_map.mappos,
2577                                                     &c->counters);
2578                                 break;
2579                         case COUNTER_MAP_SET:
2580                                 counters_map_set(newcounters, c->foot_index,
2581                                                  &c->counters);
2582                                 break;
2583                         }
2584                 }
2586                 list_for_each_entry(r, &c->rules, list) {
2587                         DEBUGP("counter for index %u: ", r->index);
2588                         switch (r->counter_map.maptype) {
2589                         case COUNTER_MAP_NOMAP:
2590                                 counters_nomap(newcounters, r->index);
2591                                 break;
2593                         case COUNTER_MAP_NORMAL_MAP:
2594                                 counters_normal_map(newcounters, repl,
2595                                                     r->index, 
2596                                                     r->counter_map.mappos);
2597                                 break;
2599                         case COUNTER_MAP_ZEROED:
2600                                 counters_map_zeroed(newcounters, repl,
2601                                                     r->index,
2602                                                     r->counter_map.mappos,
2603                                                     &r->entry->counters);
2604                                 break;
2606                         case COUNTER_MAP_SET:
2607                                 counters_map_set(newcounters, r->index,
2608                                                  &r->entry->counters);
2609                                 break;
2610                         }
2611                 }
2612         }
2614 #ifdef IPTC_DEBUG2
2615         {
2616                 int fd = open("/tmp/libiptc-so_set_add_counters.blob", 
2617                                 O_CREAT|O_WRONLY);
2618                 if (fd >= 0) {
2619                         write(fd, newcounters, counterlen);
2620                         close(fd);
2621                 }
2622         }
2623 #endif
2625         ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS,
2626                          newcounters, counterlen);
2627         if (ret < 0)
2628                 goto out_free_newcounters;
2630         free(repl->counters);
2631         free(repl);
2632         free(newcounters);
2634 finished:
2635         TC_FREE(handle);
2636         return 1;
2638 out_free_newcounters:
2639         free(newcounters);
2640 out_free_repl_counters:
2641         free(repl->counters);
2642 out_free_repl:
2643         free(repl);
2644 out_zero:
2645         return 0;
2648 /* Get raw socket. */
2649 int
2650 TC_GET_RAW_SOCKET(void)
2652         return sockfd;
2655 /* Translates errno numbers into more human-readable form than strerror. */
2656 const char *
2657 TC_STRERROR(int err)
2659         unsigned int i;
2660         struct table_struct {
2661                 void *fn;
2662                 int err;
2663                 const char *message;
2664         } table [] =
2665           { { TC_INIT, EPERM, "Permission denied (you must be root)" },
2666             { TC_INIT, EINVAL, "Module is wrong version" },
2667             { TC_INIT, ENOENT, 
2668                     "Table does not exist (do you need to insmod?)" },
2669             { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" },
2670             { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" },
2671             { TC_DELETE_CHAIN, EMLINK,
2672               "Can't delete chain with references left" },
2673             { TC_CREATE_CHAIN, EEXIST, "Chain already exists" },
2674             { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" },
2675             { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" },
2676             { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" },
2677             { TC_READ_COUNTER, E2BIG, "Index of counter too big" },
2678             { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" },
2679             { TC_INSERT_ENTRY, ELOOP, "Loop found in table" },
2680             { TC_INSERT_ENTRY, EINVAL, "Target problem" },
2681             /* EINVAL for CHECK probably means bad interface. */
2682             { TC_CHECK_PACKET, EINVAL,
2683               "Bad arguments (does that interface exist?)" },
2684             { TC_CHECK_PACKET, ENOSYS,
2685               "Checking will most likely never get implemented" },
2686             /* ENOENT for DELETE probably means no matching rule */
2687             { TC_DELETE_ENTRY, ENOENT,
2688               "Bad rule (does a matching rule exist in that chain?)" },
2689             { TC_SET_POLICY, ENOENT,
2690               "Bad built-in chain name" },
2691             { TC_SET_POLICY, EINVAL,
2692               "Bad policy name" },
2694             { NULL, 0, "Incompatible with this kernel" },
2695             { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" },
2696             { NULL, ENOSYS, "Will be implemented real soon.  I promise ;)" },
2697             { NULL, ENOMEM, "Memory allocation problem" },
2698             { NULL, ENOENT, "No chain/target/match by that name" },
2699           };
2701         for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) {
2702                 if ((!table[i].fn || table[i].fn == iptc_fn)
2703                     && table[i].err == err)
2704                         return table[i].message;
2705         }
2707         return strerror(err);