src/csv.c: use a bigger buffer
[collectd.git] / src / owniptc / 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  */
18
19 /* Library which manipulates firewall rules.  Version $Revision: 7138 $ */
20
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  */
28
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"
48
49 #include "linux_list.h"
50
51 //#define IPTC_DEBUG2 1
52
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
61
62 #ifdef DEBUG
63 #define debug(x, args...)       fprintf(stderr, x, ## args)
64 #else
65 #define debug(x, args...)
66 #endif
67
68 static int sockfd = -1;
69 static int sockfd_use = 0;
70 static void *iptc_fn = NULL;
71
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 };
82
83 /* Convenience structures */
84 struct ipt_error_target
85 {
86         STRUCT_ENTRY_TARGET t;
87         char error[TABLE_MAXNAMELEN];
88 };
89
90 struct chain_head;
91 struct rule_head;
92
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 };
103
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 };
110
111 struct rule_head
112 {
113         struct list_head list;
114         struct chain_head *chain;
115         struct counter_map counter_map;
116
117         unsigned int index;             /* index (needed for counter_map) */
118         unsigned int offset;            /* offset in rule blob */
119
120         enum iptcc_rule_type type;
121         struct chain_head *jump;        /* jump target, if IPTCC_R_JUMP */
122
123         unsigned int size;              /* size of entry data */
124         STRUCT_ENTRY entry[0];
125 };
126
127 struct chain_head
128 {
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 */
134
135         STRUCT_COUNTERS counters;       /* per-chain counters */
136         struct counter_map counter_map;
137
138         unsigned int num_rules;         /* number of rules in list */
139         struct list_head rules;         /* list of rules */
140
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 };
146
147 STRUCT_TC_HANDLE
148 {
149         int changed;                     /* Have changes been made? */
150
151         struct list_head chains;
152         
153         struct chain_head *chain_iterator_cur;
154         struct rule_head *rule_iterator_cur;
155
156         unsigned int num_chains;         /* number of user defined chains */
157
158         struct chain_head **chain_index;   /* array for fast chain list access*/
159         unsigned int        chain_index_sz;/* size of chain index array */
160
161         STRUCT_GETINFO info;
162         STRUCT_GET_ENTRIES *entries;
163 };
164
165 /* allocate a new chain head for the cache */
166 static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum)
167 {
168         struct chain_head *c = malloc(sizeof(*c));
169         if (!c)
170                 return NULL;
171         memset(c, 0, sizeof(*c));
172
173         strncpy(c->name, name, TABLE_MAXNAMELEN);
174         c->hooknum = hooknum;
175         INIT_LIST_HEAD(&c->rules);
176
177         return c;
178 }
179
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)
182 {
183         struct rule_head *r = malloc(sizeof(*r)+size);
184         if (!r)
185                 return NULL;
186         memset(r, 0, sizeof(*r));
187
188         r->chain = c;
189         r->size = size;
190
191         return r;
192 }
193
194 /* notify us that the ruleset has been modified by the user */
195 static inline void
196 set_changed(TC_HANDLE_T h)
197 {
198         h->changed = 1;
199 }
200
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
207
208
209 /**********************************************************************
210  * iptc blob utility functions (iptcb_*)
211  **********************************************************************/
212
213 static inline int
214 iptcb_get_number(const STRUCT_ENTRY *i,
215            const STRUCT_ENTRY *seek,
216            unsigned int *pos)
217 {
218         if (i == seek)
219                 return 1;
220         (*pos)++;
221         return 0;
222 }
223
224 static inline int
225 iptcb_get_entry_n(STRUCT_ENTRY *i,
226             unsigned int number,
227             unsigned int *pos,
228             STRUCT_ENTRY **pe)
229 {
230         if (*pos == number) {
231                 *pe = i;
232                 return 1;
233         }
234         (*pos)++;
235         return 0;
236 }
237
238 static inline STRUCT_ENTRY *
239 iptcb_get_entry(TC_HANDLE_T h, unsigned int offset)
240 {
241         return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset);
242 }
243
244 static unsigned int
245 iptcb_entry2index(const TC_HANDLE_T h, const STRUCT_ENTRY *seek)
246 {
247         unsigned int pos = 0;
248
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;
256 }
257
258 static inline STRUCT_ENTRY *
259 iptcb_offset2entry(TC_HANDLE_T h, unsigned int offset)
260 {
261         return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset);
262 }
263
264
265 static inline unsigned long
266 iptcb_entry2offset(const TC_HANDLE_T h, const STRUCT_ENTRY *e)
267 {
268         return (void *)e - (void *)h->entries->entrytable;
269 }
270
271 static inline unsigned int
272 iptcb_offset2index(const TC_HANDLE_T h, unsigned int offset)
273 {
274         return iptcb_entry2index(h, iptcb_offset2entry(h, offset));
275 }
276
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)
280 {
281         unsigned int i;
282
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;
289 }
290
291
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
312
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
324
325 static inline unsigned int iptcc_is_builtin(struct chain_head *c);
326
327
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)
336 {
337         unsigned int pos, end;
338         int res;
339
340         struct list_head *list_pos;
341         list_pos=&handle->chains;
342
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         }
348
349         /* Init */
350         end = handle->chain_index_sz;
351         pos = end / 2;
352
353         debug("bsearch Find chain:%s (pos:%d end:%d)\n", name, pos, end);
354
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         }
361
362         res = strcmp(name, handle->chain_index[pos]->name);
363         list_pos = &handle->chain_index[pos]->list;
364         *idx = pos;
365
366         debug("bsearch Index[%d] name:%s res:%d ",
367               pos, handle->chain_index[pos]->name, res);
368
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;
375
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 */
384
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                 }
390
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                 }
397
398                 pos = (pos+end)/2;
399                 debug("jump forward to pos:%d (end:%d)\n", pos, end);
400                 goto loop;
401         }
402
403         return list_pos;
404 }
405
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)
411 {
412         unsigned int i=0;
413         int res=0;
414
415         struct list_head *list_pos;
416         list_pos = &handle->chains;
417
418         if (handle->chain_index_sz)
419                 list_pos = &handle->chain_index[0]->list;
420
421         /* Linearly walk of chain index array */
422
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         }
433
434         return list_pos;
435 }
436 #endif
437
438 static int iptcc_chain_index_alloc(TC_HANDLE_T h)
439 {
440         unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
441         unsigned int array_elems;
442         unsigned int array_mem;
443
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;
448
449         debug("Alloc Chain index, elems:%d mem:%d bytes\n",
450               array_elems, array_mem);
451
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;
459
460         return 1;
461 }
462
463 static void iptcc_chain_index_free(TC_HANDLE_T h)
464 {
465         h->chain_index_sz = 0;
466         free(h->chain_index);
467 }
468
469
470 #ifdef DEBUG
471 static void iptcc_chain_index_dump(TC_HANDLE_T h)
472 {
473         unsigned int i = 0;
474
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         }
482 }
483 #endif
484
485 /* Build the chain index */
486 static int iptcc_chain_index_build(TC_HANDLE_T h)
487 {
488         unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
489         unsigned int chains = 0;
490         unsigned int cindex = 0;
491         struct chain_head *c;
492
493         /* Build up the chain index array here */
494         debug("Building chain index\n");
495
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);
498
499         if (h->chain_index_sz == 0)
500                 return 0;
501
502         list_for_each_entry(c, &h->chains, list) {
503
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;
508
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;
514
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");
524
525         return 1;
526 }
527
528 static int iptcc_chain_index_rebuild(TC_HANDLE_T h)
529 {
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;
536 }
537
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)
551 {
552         struct list_head *index_ptr, *index_ptr2, *next;
553         struct chain_head *c2;
554         unsigned int idx, idx2;
555
556         index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h);
557
558         debug("Del chain[%s] c->list:%p index_ptr:%p\n",
559               c->name, &c->list, index_ptr);
560
561         /* Save the next pointer */
562         next = c->list.next;
563         list_del(&c->list);
564
565         if (index_ptr == &c->list) { /* Chain used as index ptr */
566
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;
585 }
586
587
588 /**********************************************************************
589  * iptc cache utility functions (iptcc_*)
590  **********************************************************************/
591
592 /* Is the given chain builtin (1) or user-defined (0) */
593 static inline unsigned int iptcc_is_builtin(struct chain_head *c)
594 {
595         return (c->hooknum ? 1 : 0);
596 }
597
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)
601 {
602         struct rule_head *r;
603         unsigned int num = 0;
604
605         list_for_each_entry(r, &c->rules, list) {
606                 num++;
607                 if (num == rulenum)
608                         return r;
609         }
610         return NULL;
611 }
612
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)
616 {
617         struct rule_head *r;
618         unsigned int num = 0;
619
620         list_for_each_entry_reverse(r, &c->rules, list) {
621                 num++;
622                 if (num == rulenum)
623                         return r;
624         }
625         return NULL;
626 }
627
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)
631 {
632         struct list_head *pos;
633
634         if (list_empty(&handle->chains))
635                 return NULL;
636
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         }
642
643         return NULL;
644 }
645
646 /* Returns chain head if found, otherwise NULL. */
647 static struct chain_head *
648 iptcc_find_label(const char *name, TC_HANDLE_T handle)
649 {
650         struct list_head *pos;
651         struct list_head *list_start_pos;
652         unsigned int i=0;
653         int res;
654
655         if (list_empty(&handle->chains))
656                 return NULL;
657
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         }
666
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);
670
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
693
694         /* Initial/special case, no user defined chains */
695         if (handle->num_chains == 0)
696                 return NULL;
697
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;
705
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                 }
711
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         }
718
719         debug("List search NOT found name:%s\n", name);
720         return NULL;
721 }
722
723 /* called when rule is to be removed from cache */
724 static void iptcc_delete_rule(struct rule_head *r)
725 {
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--;
731
732         list_del(&r->list);
733         free(r);
734 }
735
736
737 /**********************************************************************
738  * RULESET PARSER (blob -> cache)
739  **********************************************************************/
740
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)
746 {
747         const unsigned char *data;
748
749         if (h->chain_iterator_cur) {
750                 /* policy rule is last rule */
751                 struct rule_head *pr = (struct rule_head *)
752                         h->chain_iterator_cur->rules.prev;
753
754                 /* save verdict */
755                 data = GET_TARGET(pr->entry)->data;
756                 h->chain_iterator_cur->verdict = *(const int *)data;
757
758                 /* save counter and counter_map information */
759                 h->chain_iterator_cur->counter_map.maptype = 
760                                                 COUNTER_MAP_NORMAL_MAP;
761                 h->chain_iterator_cur->counter_map.mappos = num-1;
762                 memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters, 
763                         sizeof(h->chain_iterator_cur->counters));
764
765                 /* foot_offset points to verdict rule */
766                 h->chain_iterator_cur->foot_index = num;
767                 h->chain_iterator_cur->foot_offset = pr->offset;
768
769                 /* delete rule from cache */
770                 iptcc_delete_rule(pr);
771                 h->chain_iterator_cur->num_rules--;
772
773                 return 1;
774         }
775         return 0;
776 }
777
778 /* alphabetically insert a chain into the list */
779 static inline void iptc_insert_chain(TC_HANDLE_T h, struct chain_head *c)
780 {
781         struct chain_head *tmp;
782         struct list_head  *list_start_pos;
783         unsigned int i=1;
784
785         /* Find a smart place to start the insert search */
786         list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h);
787
788         /* Handle the case, where chain.name is smaller than index[0] */
789         if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) {
790                 h->chain_index[0] = c; /* Update chain index head */
791                 list_start_pos = h->chains.next;
792                 debug("Update chain_index[0] with %s\n", c->name);
793         }
794
795         /* Handel if bsearch bails out early */
796         if (list_start_pos == &h->chains) {
797                 list_start_pos = h->chains.next;
798         }
799
800         /* sort only user defined chains */
801         if (!c->hooknum) {
802                 list_for_each_entry(tmp, list_start_pos->prev, list) {
803                         if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) {
804                                 list_add(&c->list, tmp->list.prev);
805                                 return;
806                         }
807
808                         /* Stop if list head is reached */
809                         if (&tmp->list == &h->chains) {
810                                 debug("Insert, list head reached add to tail\n");
811                                 break;
812                         }
813                 }
814         }
815
816         /* survived till end of list: add at tail */
817         list_add_tail(&c->list, &h->chains);
818 }
819
820 /* Another ugly helper function split out of cache_add_entry to make it less
821  * spaghetti code */
822 static void __iptcc_p_add_chain(TC_HANDLE_T h, struct chain_head *c,
823                                 unsigned int offset, unsigned int *num)
824 {
825         struct list_head  *tail = h->chains.prev;
826         struct chain_head *ctail;
827
828         __iptcc_p_del_policy(h, *num);
829
830         c->head_offset = offset;
831         c->index = *num;
832
833         /* Chains from kernel are already sorted, as they are inserted
834          * sorted. But there exists an issue when shifting to 1.4.0
835          * from an older version, as old versions allow last created
836          * chain to be unsorted.
837          */
838         if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/
839                 list_add_tail(&c->list, &h->chains);
840         else {
841                 ctail = list_entry(tail, struct chain_head, list);
842                 if (strcmp(c->name, ctail->name) > 0)
843                         list_add_tail(&c->list, &h->chains);/* Already sorted*/
844                 else
845                         iptc_insert_chain(h, c);/* Was not sorted */
846         }
847
848         h->chain_iterator_cur = c;
849 }
850
851 /* main parser function: add an entry from the blob to the cache */
852 static int cache_add_entry(STRUCT_ENTRY *e, 
853                            TC_HANDLE_T h, 
854                            STRUCT_ENTRY **prev,
855                            unsigned int *num)
856 {
857         unsigned int builtin;
858         unsigned int offset = (char *)e - (char *)h->entries->entrytable;
859
860         DEBUGP("entering...");
861
862         /* Last entry ("policy rule"). End it.*/
863         if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) {
864                 /* This is the ERROR node at the end of the chain */
865                 DEBUGP_C("%u:%u: end of table:\n", *num, offset);
866
867                 __iptcc_p_del_policy(h, *num);
868
869                 h->chain_iterator_cur = NULL;
870                 goto out_inc;
871         }
872
873         /* We know this is the start of a new chain if it's an ERROR
874          * target, or a hook entry point */
875
876         if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) {
877                 struct chain_head *c = 
878                         iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0);
879                 DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset, 
880                         (char *)c->name, c);
881                 if (!c) {
882                         errno = -ENOMEM;
883                         return -1;
884                 }
885                 h->num_chains++; /* New user defined chain */
886
887                 __iptcc_p_add_chain(h, c, offset, num);
888
889         } else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) {
890                 struct chain_head *c =
891                         iptcc_alloc_chain_head((char *)hooknames[builtin-1], 
892                                                 builtin);
893                 DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n", 
894                         *num, offset, c, &c->rules);
895                 if (!c) {
896                         errno = -ENOMEM;
897                         return -1;
898                 }
899
900                 c->hooknum = builtin;
901
902                 __iptcc_p_add_chain(h, c, offset, num);
903
904                 /* FIXME: this is ugly. */
905                 goto new_rule;
906         } else {
907                 /* has to be normal rule */
908                 struct rule_head *r;
909 new_rule:
910
911                 if (!(r = iptcc_alloc_rule(h->chain_iterator_cur, 
912                                            e->next_offset))) {
913                         errno = ENOMEM;
914                         return -1;
915                 }
916                 DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r);
917
918                 r->index = *num;
919                 r->offset = offset;
920                 memcpy(r->entry, e, e->next_offset);
921                 r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP;
922                 r->counter_map.mappos = r->index;
923
924                 /* handling of jumps, etc. */
925                 if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) {
926                         STRUCT_STANDARD_TARGET *t;
927
928                         t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
929                         if (t->target.u.target_size
930                             != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
931                                 errno = EINVAL;
932                                 return -1;
933                         }
934
935                         if (t->verdict < 0) {
936                                 DEBUGP_C("standard, verdict=%d\n", t->verdict);
937                                 r->type = IPTCC_R_STANDARD;
938                         } else if (t->verdict == r->offset+e->next_offset) {
939                                 DEBUGP_C("fallthrough\n");
940                                 r->type = IPTCC_R_FALLTHROUGH;
941                         } else {
942                                 DEBUGP_C("jump, target=%u\n", t->verdict);
943                                 r->type = IPTCC_R_JUMP;
944                                 /* Jump target fixup has to be deferred
945                                  * until second pass, since we migh not
946                                  * yet have parsed the target */
947                         }
948                 } else {
949                         DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name);
950                         r->type = IPTCC_R_MODULE;
951                 }
952
953                 list_add_tail(&r->list, &h->chain_iterator_cur->rules);
954                 h->chain_iterator_cur->num_rules++;
955         }
956 out_inc:
957         (*num)++;
958         return 0;
959 }
960
961
962 /* parse an iptables blob into it's pieces */
963 static int parse_table(TC_HANDLE_T h)
964 {
965         STRUCT_ENTRY *prev;
966         unsigned int num = 0;
967         struct chain_head *c;
968
969         /* First pass: over ruleset blob */
970         ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
971                         cache_add_entry, h, &prev, &num);
972
973         /* Build the chain index, used for chain list search speedup */
974         if ((iptcc_chain_index_alloc(h)) < 0)
975                 return -ENOMEM;
976         iptcc_chain_index_build(h);
977
978         /* Second pass: fixup parsed data from first pass */
979         list_for_each_entry(c, &h->chains, list) {
980                 struct rule_head *r;
981                 list_for_each_entry(r, &c->rules, list) {
982                         struct chain_head *lc;
983                         STRUCT_STANDARD_TARGET *t;
984
985                         if (r->type != IPTCC_R_JUMP)
986                                 continue;
987
988                         t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
989                         lc = iptcc_find_chain_by_offset(h, t->verdict);
990                         if (!lc)
991                                 return -1;
992                         r->jump = lc;
993                         lc->references++;
994                 }
995         }
996
997         /* FIXME: sort chains */
998
999         return 1;
1000 }
1001
1002
1003 /**********************************************************************
1004  * RULESET COMPILATION (cache -> blob)
1005  **********************************************************************/
1006
1007 /* Convenience structures */
1008 struct iptcb_chain_start{
1009         STRUCT_ENTRY e;
1010         struct ipt_error_target name;
1011 };
1012 #define IPTCB_CHAIN_START_SIZE  (sizeof(STRUCT_ENTRY) +                 \
1013                                  ALIGN(sizeof(struct ipt_error_target)))
1014
1015 struct iptcb_chain_foot {
1016         STRUCT_ENTRY e;
1017         STRUCT_STANDARD_TARGET target;
1018 };
1019 #define IPTCB_CHAIN_FOOT_SIZE   (sizeof(STRUCT_ENTRY) +                 \
1020                                  ALIGN(sizeof(STRUCT_STANDARD_TARGET)))
1021
1022 struct iptcb_chain_error {
1023         STRUCT_ENTRY entry;
1024         struct ipt_error_target target;
1025 };
1026 #define IPTCB_CHAIN_ERROR_SIZE  (sizeof(STRUCT_ENTRY) +                 \
1027                                  ALIGN(sizeof(struct ipt_error_target)))
1028
1029
1030
1031 /* compile rule from cache into blob */
1032 static inline int iptcc_compile_rule (TC_HANDLE_T h, STRUCT_REPLACE *repl, struct rule_head *r)
1033 {
1034         /* handle jumps */
1035         if (r->type == IPTCC_R_JUMP) {
1036                 STRUCT_STANDARD_TARGET *t;
1037                 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1038                 /* memset for memcmp convenience on delete/replace */
1039                 memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
1040                 strcpy(t->target.u.user.name, STANDARD_TARGET);
1041                 /* Jumps can only happen to builtin chains, so we
1042                  * can safely assume that they always have a header */
1043                 t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE;
1044         } else if (r->type == IPTCC_R_FALLTHROUGH) {
1045                 STRUCT_STANDARD_TARGET *t;
1046                 t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1047                 t->verdict = r->offset + r->size;
1048         }
1049         
1050         /* copy entry from cache to blob */
1051         memcpy((char *)repl->entries+r->offset, r->entry, r->size);
1052
1053         return 1;
1054 }
1055
1056 /* compile chain from cache into blob */
1057 static int iptcc_compile_chain(TC_HANDLE_T h, STRUCT_REPLACE *repl, struct chain_head *c)
1058 {
1059         int ret;
1060         struct rule_head *r;
1061         struct iptcb_chain_start *head;
1062         struct iptcb_chain_foot *foot;
1063
1064         /* only user-defined chains have heaer */
1065         if (!iptcc_is_builtin(c)) {
1066                 /* put chain header in place */
1067                 head = (void *)repl->entries + c->head_offset;
1068                 head->e.target_offset = sizeof(STRUCT_ENTRY);
1069                 head->e.next_offset = IPTCB_CHAIN_START_SIZE;
1070                 strcpy(head->name.t.u.user.name, ERROR_TARGET);
1071                 head->name.t.u.target_size = 
1072                                 ALIGN(sizeof(struct ipt_error_target));
1073                 strcpy(head->name.error, c->name);
1074         } else {
1075                 repl->hook_entry[c->hooknum-1] = c->head_offset;        
1076                 repl->underflow[c->hooknum-1] = c->foot_offset;
1077         }
1078
1079         /* iterate over rules */
1080         list_for_each_entry(r, &c->rules, list) {
1081                 ret = iptcc_compile_rule(h, repl, r);
1082                 if (ret < 0)
1083                         return ret;
1084         }
1085
1086         /* put chain footer in place */
1087         foot = (void *)repl->entries + c->foot_offset;
1088         foot->e.target_offset = sizeof(STRUCT_ENTRY);
1089         foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE;
1090         strcpy(foot->target.target.u.user.name, STANDARD_TARGET);
1091         foot->target.target.u.target_size =
1092                                 ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1093         /* builtin targets have verdict, others return */
1094         if (iptcc_is_builtin(c))
1095                 foot->target.verdict = c->verdict;
1096         else
1097                 foot->target.verdict = RETURN;
1098         /* set policy-counters */
1099         memcpy(&foot->e.counters, &c->counters, sizeof(STRUCT_COUNTERS));
1100
1101         return 0;
1102 }
1103
1104 /* calculate offset and number for every rule in the cache */
1105 static int iptcc_compile_chain_offsets(TC_HANDLE_T h, struct chain_head *c,
1106                                        unsigned int *offset, unsigned int *num)
1107 {
1108         struct rule_head *r;
1109
1110         c->head_offset = *offset;
1111         DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset);
1112
1113         if (!iptcc_is_builtin(c))  {
1114                 /* Chain has header */
1115                 *offset += sizeof(STRUCT_ENTRY) 
1116                              + ALIGN(sizeof(struct ipt_error_target));
1117                 (*num)++;
1118         }
1119
1120         list_for_each_entry(r, &c->rules, list) {
1121                 DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num);
1122                 r->offset = *offset;
1123                 r->index = *num;
1124                 *offset += r->size;
1125                 (*num)++;
1126         }
1127
1128         DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num, 
1129                 *offset, *num);
1130         c->foot_offset = *offset;
1131         c->foot_index = *num;
1132         *offset += sizeof(STRUCT_ENTRY)
1133                    + ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1134         (*num)++;
1135
1136         return 1;
1137 }
1138
1139 /* put the pieces back together again */
1140 static int iptcc_compile_table_prep(TC_HANDLE_T h, unsigned int *size)
1141 {
1142         struct chain_head *c;
1143         unsigned int offset = 0, num = 0;
1144         int ret = 0;
1145
1146         /* First pass: calculate offset for every rule */
1147         list_for_each_entry(c, &h->chains, list) {
1148                 ret = iptcc_compile_chain_offsets(h, c, &offset, &num);
1149                 if (ret < 0)
1150                         return ret;
1151         }
1152
1153         /* Append one error rule at end of chain */
1154         num++;
1155         offset += sizeof(STRUCT_ENTRY)
1156                   + ALIGN(sizeof(struct ipt_error_target));
1157
1158         /* ruleset size is now in offset */
1159         *size = offset;
1160         return num;
1161 }
1162
1163 static int iptcc_compile_table(TC_HANDLE_T h, STRUCT_REPLACE *repl)
1164 {
1165         struct chain_head *c;
1166         struct iptcb_chain_error *error;
1167
1168         /* Second pass: copy from cache to offsets, fill in jumps */
1169         list_for_each_entry(c, &h->chains, list) {
1170                 int ret = iptcc_compile_chain(h, repl, c);
1171                 if (ret < 0)
1172                         return ret;
1173         }
1174
1175         /* Append error rule at end of chain */
1176         error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE;
1177         error->entry.target_offset = sizeof(STRUCT_ENTRY);
1178         error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE;
1179         error->target.t.u.user.target_size = 
1180                 ALIGN(sizeof(struct ipt_error_target));
1181         strcpy((char *)&error->target.t.u.user.name, ERROR_TARGET);
1182         strcpy((char *)&error->target.error, "ERROR");
1183
1184         return 1;
1185 }
1186
1187 /**********************************************************************
1188  * EXTERNAL API (operates on cache only)
1189  **********************************************************************/
1190
1191 /* Allocate handle of given size */
1192 static TC_HANDLE_T
1193 alloc_handle(const char *tablename, unsigned int size, unsigned int num_rules)
1194 {
1195         size_t len;
1196         TC_HANDLE_T h;
1197
1198         len = sizeof(STRUCT_TC_HANDLE) + size;
1199
1200         h = malloc(sizeof(STRUCT_TC_HANDLE));
1201         if (!h) {
1202                 errno = ENOMEM;
1203                 return NULL;
1204         }
1205         memset(h, 0, sizeof(*h));
1206         INIT_LIST_HEAD(&h->chains);
1207         strcpy(h->info.name, tablename);
1208
1209         h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + size);
1210         if (!h->entries)
1211                 goto out_free_handle;
1212
1213         strcpy(h->entries->name, tablename);
1214         h->entries->size = size;
1215
1216         return h;
1217
1218 out_free_handle:
1219         free(h);
1220
1221         return NULL;
1222 }
1223
1224
1225 TC_HANDLE_T
1226 TC_INIT(const char *tablename)
1227 {
1228         TC_HANDLE_T h;
1229         STRUCT_GETINFO info;
1230         unsigned int tmp;
1231         socklen_t s;
1232
1233         iptc_fn = TC_INIT;
1234
1235         if (strlen(tablename) >= TABLE_MAXNAMELEN) {
1236                 errno = EINVAL;
1237                 return NULL;
1238         }
1239         
1240         if (sockfd_use == 0) {
1241                 sockfd = socket(TC_AF, SOCK_RAW, IPPROTO_RAW);
1242                 if (sockfd < 0)
1243                         return NULL;
1244         }
1245         sockfd_use++;
1246 retry:
1247         s = sizeof(info);
1248
1249         strcpy(info.name, tablename);
1250         if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) {
1251                 if (--sockfd_use == 0) {
1252                         close(sockfd);
1253                         sockfd = -1;
1254                 }
1255                 return NULL;
1256         }
1257
1258         DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n",
1259                 info.valid_hooks, info.num_entries, info.size);
1260
1261         if ((h = alloc_handle(info.name, info.size, info.num_entries))
1262             == NULL) {
1263                 if (--sockfd_use == 0) {
1264                         close(sockfd);
1265                         sockfd = -1;
1266                 }
1267                 return NULL;
1268         }
1269
1270         /* Initialize current state */
1271         h->info = info;
1272
1273         h->entries->size = h->info.size;
1274
1275         tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size;
1276
1277         if (getsockopt(sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries,
1278                        &tmp) < 0)
1279                 goto error;
1280
1281 #ifdef IPTC_DEBUG2
1282         {
1283                 int fd = open("/tmp/libiptc-so_get_entries.blob", 
1284                                 O_CREAT|O_WRONLY);
1285                 if (fd >= 0) {
1286                         write(fd, h->entries, tmp);
1287                         close(fd);
1288                 }
1289         }
1290 #endif
1291
1292         if (parse_table(h) < 0)
1293                 goto error;
1294
1295         CHECK(h);
1296         return h;
1297 error:
1298         TC_FREE(&h);
1299         /* A different process changed the ruleset size, retry */
1300         if (errno == EAGAIN)
1301                 goto retry;
1302         return NULL;
1303 }
1304
1305 void
1306 TC_FREE(TC_HANDLE_T *h)
1307 {
1308         struct chain_head *c, *tmp;
1309
1310         iptc_fn = TC_FREE;
1311         if (--sockfd_use == 0) {
1312                 close(sockfd);
1313                 sockfd = -1;
1314         }
1315
1316         list_for_each_entry_safe(c, tmp, &(*h)->chains, list) {
1317                 struct rule_head *r, *rtmp;
1318
1319                 list_for_each_entry_safe(r, rtmp, &c->rules, list) {
1320                         free(r);
1321                 }
1322
1323                 free(c);
1324         }
1325
1326         iptcc_chain_index_free(*h);
1327
1328         free((*h)->entries);
1329         free(*h);
1330
1331         *h = NULL;
1332 }
1333
1334 static inline int
1335 print_match(const STRUCT_ENTRY_MATCH *m)
1336 {
1337         printf("Match name: `%s'\n", m->u.user.name);
1338         return 0;
1339 }
1340
1341 static int dump_entry(STRUCT_ENTRY *e, const TC_HANDLE_T handle);
1342  
1343 void
1344 TC_DUMP_ENTRIES(const TC_HANDLE_T handle)
1345 {
1346         iptc_fn = TC_DUMP_ENTRIES;
1347         CHECK(handle);
1348
1349         printf("libiptc v%s. %u bytes.\n",
1350                XTABLES_VERSION, handle->entries->size);
1351         printf("Table `%s'\n", handle->info.name);
1352         printf("Hooks: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
1353                handle->info.hook_entry[HOOK_PRE_ROUTING],
1354                handle->info.hook_entry[HOOK_LOCAL_IN],
1355                handle->info.hook_entry[HOOK_FORWARD],
1356                handle->info.hook_entry[HOOK_LOCAL_OUT],
1357                handle->info.hook_entry[HOOK_POST_ROUTING]);
1358         printf("Underflows: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
1359                handle->info.underflow[HOOK_PRE_ROUTING],
1360                handle->info.underflow[HOOK_LOCAL_IN],
1361                handle->info.underflow[HOOK_FORWARD],
1362                handle->info.underflow[HOOK_LOCAL_OUT],
1363                handle->info.underflow[HOOK_POST_ROUTING]);
1364
1365         ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size,
1366                       dump_entry, handle);
1367 }
1368
1369 /* Does this chain exist? */
1370 int TC_IS_CHAIN(const char *chain, const TC_HANDLE_T handle)
1371 {
1372         iptc_fn = TC_IS_CHAIN;
1373         return iptcc_find_label(chain, handle) != NULL;
1374 }
1375
1376 static void iptcc_chain_iterator_advance(TC_HANDLE_T handle)
1377 {
1378         struct chain_head *c = handle->chain_iterator_cur;
1379
1380         if (c->list.next == &handle->chains)
1381                 handle->chain_iterator_cur = NULL;
1382         else
1383                 handle->chain_iterator_cur = 
1384                         list_entry(c->list.next, struct chain_head, list);
1385 }
1386
1387 /* Iterator functions to run through the chains. */
1388 const char *
1389 TC_FIRST_CHAIN(TC_HANDLE_T *handle)
1390 {
1391         struct chain_head *c = list_entry((*handle)->chains.next,
1392                                           struct chain_head, list);
1393
1394         iptc_fn = TC_FIRST_CHAIN;
1395
1396
1397         if (list_empty(&(*handle)->chains)) {
1398                 DEBUGP(": no chains\n");
1399                 return NULL;
1400         }
1401
1402         (*handle)->chain_iterator_cur = c;
1403         iptcc_chain_iterator_advance(*handle);
1404
1405         DEBUGP(": returning `%s'\n", c->name);
1406         return c->name;
1407 }
1408
1409 /* Iterator functions to run through the chains.  Returns NULL at end. */
1410 const char *
1411 TC_NEXT_CHAIN(TC_HANDLE_T *handle)
1412 {
1413         struct chain_head *c = (*handle)->chain_iterator_cur;
1414
1415         iptc_fn = TC_NEXT_CHAIN;
1416
1417         if (!c) {
1418                 DEBUGP(": no more chains\n");
1419                 return NULL;
1420         }
1421
1422         iptcc_chain_iterator_advance(*handle);
1423         
1424         DEBUGP(": returning `%s'\n", c->name);
1425         return c->name;
1426 }
1427
1428 /* Get first rule in the given chain: NULL for empty chain. */
1429 const STRUCT_ENTRY *
1430 TC_FIRST_RULE(const char *chain, TC_HANDLE_T *handle)
1431 {
1432         struct chain_head *c;
1433         struct rule_head *r;
1434
1435         iptc_fn = TC_FIRST_RULE;
1436
1437         DEBUGP("first rule(%s): ", chain);
1438
1439         c = iptcc_find_label(chain, *handle);
1440         if (!c) {
1441                 errno = ENOENT;
1442                 return NULL;
1443         }
1444
1445         /* Empty chain: single return/policy rule */
1446         if (list_empty(&c->rules)) {
1447                 DEBUGP_C("no rules, returning NULL\n");
1448                 return NULL;
1449         }
1450
1451         r = list_entry(c->rules.next, struct rule_head, list);
1452         (*handle)->rule_iterator_cur = r;
1453         DEBUGP_C("%p\n", r);
1454
1455         return r->entry;
1456 }
1457
1458 /* Returns NULL when rules run out. */
1459 const STRUCT_ENTRY *
1460 TC_NEXT_RULE(const STRUCT_ENTRY *prev, TC_HANDLE_T *handle)
1461 {
1462         struct rule_head *r;
1463
1464         iptc_fn = TC_NEXT_RULE;
1465         DEBUGP("rule_iterator_cur=%p...", (*handle)->rule_iterator_cur);
1466
1467         if (!(*handle)->rule_iterator_cur) {
1468                 DEBUGP_C("returning NULL\n");
1469                 return NULL;
1470         }
1471         
1472         r = list_entry((*handle)->rule_iterator_cur->list.next, 
1473                         struct rule_head, list);
1474
1475         iptc_fn = TC_NEXT_RULE;
1476
1477         DEBUGP_C("next=%p, head=%p...", &r->list, 
1478                 &(*handle)->rule_iterator_cur->chain->rules);
1479
1480         if (&r->list == &(*handle)->rule_iterator_cur->chain->rules) {
1481                 (*handle)->rule_iterator_cur = NULL;
1482                 DEBUGP_C("finished, returning NULL\n");
1483                 return NULL;
1484         }
1485
1486         (*handle)->rule_iterator_cur = r;
1487
1488         /* NOTE: prev is without any influence ! */
1489         DEBUGP_C("returning rule %p\n", r);
1490         return r->entry;
1491 }
1492
1493 /* How many rules in this chain? */
1494 #if 0
1495 static unsigned int
1496 TC_NUM_RULES(const char *chain, TC_HANDLE_T *handle)
1497 {
1498         struct chain_head *c;
1499         iptc_fn = TC_NUM_RULES;
1500         CHECK(*handle);
1501
1502         c = iptcc_find_label(chain, *handle);
1503         if (!c) {
1504                 errno = ENOENT;
1505                 return (unsigned int)-1;
1506         }
1507         
1508         return c->num_rules;
1509 }
1510 #endif
1511
1512 #if 0
1513 static const STRUCT_ENTRY *
1514 TC_GET_RULE(const char *chain, unsigned int n, TC_HANDLE_T *handle)
1515 {
1516         struct chain_head *c;
1517         struct rule_head *r;
1518         
1519         iptc_fn = TC_GET_RULE;
1520
1521         CHECK(*handle);
1522
1523         c = iptcc_find_label(chain, *handle);
1524         if (!c) {
1525                 errno = ENOENT;
1526                 return NULL;
1527         }
1528
1529         r = iptcc_get_rule_num(c, n);
1530         if (!r)
1531                 return NULL;
1532         return r->entry;
1533 }
1534 #endif
1535
1536 /* Returns a pointer to the target name of this position. */
1537 static const char *standard_target_map(int verdict)
1538 {
1539         switch (verdict) {
1540                 case RETURN:
1541                         return LABEL_RETURN;
1542                         break;
1543                 case -NF_ACCEPT-1:
1544                         return LABEL_ACCEPT;
1545                         break;
1546                 case -NF_DROP-1:
1547                         return LABEL_DROP;
1548                         break;
1549                 case -NF_QUEUE-1:
1550                         return LABEL_QUEUE;
1551                         break;
1552                 default:
1553                         fprintf(stderr, "ERROR: %d not a valid target)\n",
1554                                 verdict);
1555                         abort();
1556                         break;
1557         }
1558         /* not reached */
1559         return NULL;
1560 }
1561
1562 /* Returns a pointer to the target name of this position. */
1563 const char *TC_GET_TARGET(const STRUCT_ENTRY *ce,
1564                           TC_HANDLE_T *handle)
1565 {
1566         STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce;
1567         struct rule_head *r = container_of(e, struct rule_head, entry[0]);
1568         const unsigned char *data;
1569
1570         iptc_fn = TC_GET_TARGET;
1571
1572         switch(r->type) {
1573                 int spos;
1574                 case IPTCC_R_FALLTHROUGH:
1575                         return "";
1576                         break;
1577                 case IPTCC_R_JUMP:
1578                         DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name);
1579                         return r->jump->name;
1580                         break;
1581                 case IPTCC_R_STANDARD:
1582                         data = GET_TARGET(e)->data;
1583                         spos = *(const int *)data;
1584                         DEBUGP("r=%p, spos=%d'\n", r, spos);
1585                         return standard_target_map(spos);
1586                         break;
1587                 case IPTCC_R_MODULE:
1588                         return GET_TARGET(e)->u.user.name;
1589                         break;
1590         }
1591         return NULL;
1592 }
1593 /* Is this a built-in chain?  Actually returns hook + 1. */
1594 int
1595 TC_BUILTIN(const char *chain, const TC_HANDLE_T handle)
1596 {
1597         struct chain_head *c;
1598         
1599         iptc_fn = TC_BUILTIN;
1600
1601         c = iptcc_find_label(chain, handle);
1602         if (!c) {
1603                 errno = ENOENT;
1604                 return 0;
1605         }
1606
1607         return iptcc_is_builtin(c);
1608 }
1609
1610 /* Get the policy of a given built-in chain */
1611 const char *
1612 TC_GET_POLICY(const char *chain,
1613               STRUCT_COUNTERS *counters,
1614               TC_HANDLE_T *handle)
1615 {
1616         struct chain_head *c;
1617
1618         iptc_fn = TC_GET_POLICY;
1619
1620         DEBUGP("called for chain %s\n", chain);
1621
1622         c = iptcc_find_label(chain, *handle);
1623         if (!c) {
1624                 errno = ENOENT;
1625                 return NULL;
1626         }
1627
1628         if (!iptcc_is_builtin(c))
1629                 return NULL;
1630
1631         *counters = c->counters;
1632
1633         return standard_target_map(c->verdict);
1634 }
1635
1636 static int
1637 iptcc_standard_map(struct rule_head *r, int verdict)
1638 {
1639         STRUCT_ENTRY *e = r->entry;
1640         STRUCT_STANDARD_TARGET *t;
1641
1642         t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
1643
1644         if (t->target.u.target_size
1645             != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
1646                 errno = EINVAL;
1647                 return 0;
1648         }
1649         /* memset for memcmp convenience on delete/replace */
1650         memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
1651         strcpy(t->target.u.user.name, STANDARD_TARGET);
1652         t->verdict = verdict;
1653
1654         r->type = IPTCC_R_STANDARD;
1655
1656         return 1;
1657 }
1658
1659 static int
1660 iptcc_map_target(const TC_HANDLE_T handle,
1661            struct rule_head *r)
1662 {
1663         STRUCT_ENTRY *e = r->entry;
1664         STRUCT_ENTRY_TARGET *t = GET_TARGET(e);
1665
1666         /* Maybe it's empty (=> fall through) */
1667         if (strcmp(t->u.user.name, "") == 0) {
1668                 r->type = IPTCC_R_FALLTHROUGH;
1669                 return 1;
1670         }
1671         /* Maybe it's a standard target name... */
1672         else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0)
1673                 return iptcc_standard_map(r, -NF_ACCEPT - 1);
1674         else if (strcmp(t->u.user.name, LABEL_DROP) == 0)
1675                 return iptcc_standard_map(r, -NF_DROP - 1);
1676         else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0)
1677                 return iptcc_standard_map(r, -NF_QUEUE - 1);
1678         else if (strcmp(t->u.user.name, LABEL_RETURN) == 0)
1679                 return iptcc_standard_map(r, RETURN);
1680         else if (TC_BUILTIN(t->u.user.name, handle)) {
1681                 /* Can't jump to builtins. */
1682                 errno = EINVAL;
1683                 return 0;
1684         } else {
1685                 /* Maybe it's an existing chain name. */
1686                 struct chain_head *c;
1687                 DEBUGP("trying to find chain `%s': ", t->u.user.name);
1688
1689                 c = iptcc_find_label(t->u.user.name, handle);
1690                 if (c) {
1691                         DEBUGP_C("found!\n");
1692                         r->type = IPTCC_R_JUMP;
1693                         r->jump = c;
1694                         c->references++;
1695                         return 1;
1696                 }
1697                 DEBUGP_C("not found :(\n");
1698         }
1699
1700         /* Must be a module?  If not, kernel will reject... */
1701         /* memset to all 0 for your memcmp convenience: don't clear version */
1702         memset(t->u.user.name + strlen(t->u.user.name),
1703                0,
1704                FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name));
1705         r->type = IPTCC_R_MODULE;
1706         set_changed(handle);
1707         return 1;
1708 }
1709
1710 /* Insert the entry `fw' in chain `chain' into position `rulenum'. */
1711 int
1712 TC_INSERT_ENTRY(const IPT_CHAINLABEL chain,
1713                 const STRUCT_ENTRY *e,
1714                 unsigned int rulenum,
1715                 TC_HANDLE_T *handle)
1716 {
1717         struct chain_head *c;
1718         struct rule_head *r;
1719         struct list_head *prev;
1720
1721         iptc_fn = TC_INSERT_ENTRY;
1722
1723         if (!(c = iptcc_find_label(chain, *handle))) {
1724                 errno = ENOENT;
1725                 return 0;
1726         }
1727
1728         /* first rulenum index = 0
1729            first c->num_rules index = 1 */
1730         if (rulenum > c->num_rules) {
1731                 errno = E2BIG;
1732                 return 0;
1733         }
1734
1735         /* If we are inserting at the end just take advantage of the
1736            double linked list, insert will happen before the entry
1737            prev points to. */
1738         if (rulenum == c->num_rules) {
1739                 prev = &c->rules;
1740         } else if (rulenum + 1 <= c->num_rules/2) {
1741                 r = iptcc_get_rule_num(c, rulenum + 1);
1742                 prev = &r->list;
1743         } else {
1744                 r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1745                 prev = &r->list;
1746         }
1747
1748         if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1749                 errno = ENOMEM;
1750                 return 0;
1751         }
1752
1753         memcpy(r->entry, e, e->next_offset);
1754         r->counter_map.maptype = COUNTER_MAP_SET;
1755
1756         if (!iptcc_map_target(*handle, r)) {
1757                 free(r);
1758                 return 0;
1759         }
1760
1761         list_add_tail(&r->list, prev);
1762         c->num_rules++;
1763
1764         set_changed(*handle);
1765
1766         return 1;
1767 }
1768
1769 /* Atomically replace rule `rulenum' in `chain' with `fw'. */
1770 int
1771 TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain,
1772                  const STRUCT_ENTRY *e,
1773                  unsigned int rulenum,
1774                  TC_HANDLE_T *handle)
1775 {
1776         struct chain_head *c;
1777         struct rule_head *r, *old;
1778
1779         iptc_fn = TC_REPLACE_ENTRY;
1780
1781         if (!(c = iptcc_find_label(chain, *handle))) {
1782                 errno = ENOENT;
1783                 return 0;
1784         }
1785
1786         if (rulenum >= c->num_rules) {
1787                 errno = E2BIG;
1788                 return 0;
1789         }
1790
1791         /* Take advantage of the double linked list if possible. */
1792         if (rulenum + 1 <= c->num_rules/2) {
1793                 old = iptcc_get_rule_num(c, rulenum + 1);
1794         } else {
1795                 old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1796         }
1797
1798         if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1799                 errno = ENOMEM;
1800                 return 0;
1801         }
1802
1803         memcpy(r->entry, e, e->next_offset);
1804         r->counter_map.maptype = COUNTER_MAP_SET;
1805
1806         if (!iptcc_map_target(*handle, r)) {
1807                 free(r);
1808                 return 0;
1809         }
1810
1811         list_add(&r->list, &old->list);
1812         iptcc_delete_rule(old);
1813
1814         set_changed(*handle);
1815
1816         return 1;
1817 }
1818
1819 /* Append entry `fw' to chain `chain'.  Equivalent to insert with
1820    rulenum = length of chain. */
1821 int
1822 TC_APPEND_ENTRY(const IPT_CHAINLABEL chain,
1823                 const STRUCT_ENTRY *e,
1824                 TC_HANDLE_T *handle)
1825 {
1826         struct chain_head *c;
1827         struct rule_head *r;
1828
1829         iptc_fn = TC_APPEND_ENTRY;
1830         if (!(c = iptcc_find_label(chain, *handle))) {
1831                 DEBUGP("unable to find chain `%s'\n", chain);
1832                 errno = ENOENT;
1833                 return 0;
1834         }
1835
1836         if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1837                 DEBUGP("unable to allocate rule for chain `%s'\n", chain);
1838                 errno = ENOMEM;
1839                 return 0;
1840         }
1841
1842         memcpy(r->entry, e, e->next_offset);
1843         r->counter_map.maptype = COUNTER_MAP_SET;
1844
1845         if (!iptcc_map_target(*handle, r)) {
1846                 DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1847                 free(r);
1848                 return 0;
1849         }
1850
1851         list_add_tail(&r->list, &c->rules);
1852         c->num_rules++;
1853
1854         set_changed(*handle);
1855
1856         return 1;
1857 }
1858
1859 static inline int
1860 match_different(const STRUCT_ENTRY_MATCH *a,
1861                 const unsigned char *a_elems,
1862                 const unsigned char *b_elems,
1863                 unsigned char **maskptr)
1864 {
1865         const STRUCT_ENTRY_MATCH *b;
1866         unsigned int i;
1867
1868         /* Offset of b is the same as a. */
1869         b = (void *)b_elems + ((unsigned char *)a - a_elems);
1870
1871         if (a->u.match_size != b->u.match_size)
1872                 return 1;
1873
1874         if (strcmp(a->u.user.name, b->u.user.name) != 0)
1875                 return 1;
1876
1877         *maskptr += ALIGN(sizeof(*a));
1878
1879         for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++)
1880                 if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0)
1881                         return 1;
1882         *maskptr += i;
1883         return 0;
1884 }
1885
1886 static inline int
1887 target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask)
1888 {
1889         unsigned int i;
1890         STRUCT_ENTRY_TARGET *ta, *tb;
1891
1892         if (a->type != b->type)
1893                 return 0;
1894
1895         ta = GET_TARGET(a->entry);
1896         tb = GET_TARGET(b->entry);
1897
1898         switch (a->type) {
1899         case IPTCC_R_FALLTHROUGH:
1900                 return 1;
1901         case IPTCC_R_JUMP:
1902                 return a->jump == b->jump;
1903         case IPTCC_R_STANDARD:
1904                 return ((STRUCT_STANDARD_TARGET *)ta)->verdict
1905                         == ((STRUCT_STANDARD_TARGET *)tb)->verdict;
1906         case IPTCC_R_MODULE:
1907                 if (ta->u.target_size != tb->u.target_size)
1908                         return 0;
1909                 if (strcmp(ta->u.user.name, tb->u.user.name) != 0)
1910                         return 0;
1911
1912                 for (i = 0; i < ta->u.target_size - sizeof(*ta); i++)
1913                         if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0)
1914                                 return 0;
1915                 return 1;
1916         default:
1917                 fprintf(stderr, "ERROR: bad type %i\n", a->type);
1918                 abort();
1919         }
1920 }
1921
1922 static unsigned char *
1923 is_same(const STRUCT_ENTRY *a,
1924         const STRUCT_ENTRY *b,
1925         unsigned char *matchmask);
1926
1927 /* Delete the first rule in `chain' which matches `fw'. */
1928 int
1929 TC_DELETE_ENTRY(const IPT_CHAINLABEL chain,
1930                 const STRUCT_ENTRY *origfw,
1931                 unsigned char *matchmask,
1932                 TC_HANDLE_T *handle)
1933 {
1934         struct chain_head *c;
1935         struct rule_head *r, *i;
1936
1937         iptc_fn = TC_DELETE_ENTRY;
1938         if (!(c = iptcc_find_label(chain, *handle))) {
1939                 errno = ENOENT;
1940                 return 0;
1941         }
1942
1943         /* Create a rule_head from origfw. */
1944         r = iptcc_alloc_rule(c, origfw->next_offset);
1945         if (!r) {
1946                 errno = ENOMEM;
1947                 return 0;
1948         }
1949
1950         memcpy(r->entry, origfw, origfw->next_offset);
1951         r->counter_map.maptype = COUNTER_MAP_NOMAP;
1952         if (!iptcc_map_target(*handle, r)) {
1953                 DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1954                 free(r);
1955                 return 0;
1956         } else {
1957                 /* iptcc_map_target increment target chain references
1958                  * since this is a fake rule only used for matching
1959                  * the chain references count is decremented again. 
1960                  */
1961                 if (r->type == IPTCC_R_JUMP
1962                     && r->jump)
1963                         r->jump->references--;
1964         }
1965
1966         list_for_each_entry(i, &c->rules, list) {
1967                 unsigned char *mask;
1968
1969                 mask = is_same(r->entry, i->entry, matchmask);
1970                 if (!mask)
1971                         continue;
1972
1973                 if (!target_same(r, i, mask))
1974                         continue;
1975
1976                 /* If we are about to delete the rule that is the
1977                  * current iterator, move rule iterator back.  next
1978                  * pointer will then point to real next node */
1979                 if (i == (*handle)->rule_iterator_cur) {
1980                         (*handle)->rule_iterator_cur = 
1981                                 list_entry((*handle)->rule_iterator_cur->list.prev,
1982                                            struct rule_head, list);
1983                 }
1984
1985                 c->num_rules--;
1986                 iptcc_delete_rule(i);
1987
1988                 set_changed(*handle);
1989                 free(r);
1990                 return 1;
1991         }
1992
1993         free(r);
1994         errno = ENOENT;
1995         return 0;
1996 }
1997
1998
1999 /* Delete the rule in position `rulenum' in `chain'. */
2000 int
2001 TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain,
2002                     unsigned int rulenum,
2003                     TC_HANDLE_T *handle)
2004 {
2005         struct chain_head *c;
2006         struct rule_head *r;
2007
2008         iptc_fn = TC_DELETE_NUM_ENTRY;
2009
2010         if (!(c = iptcc_find_label(chain, *handle))) {
2011                 errno = ENOENT;
2012                 return 0;
2013         }
2014
2015         if (rulenum >= c->num_rules) {
2016                 errno = E2BIG;
2017                 return 0;
2018         }
2019
2020         /* Take advantage of the double linked list if possible. */
2021         if (rulenum + 1 <= c->num_rules/2) {
2022                 r = iptcc_get_rule_num(c, rulenum + 1);
2023         } else {
2024                 r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
2025         }
2026
2027         /* If we are about to delete the rule that is the current
2028          * iterator, move rule iterator back.  next pointer will then
2029          * point to real next node */
2030         if (r == (*handle)->rule_iterator_cur) {
2031                 (*handle)->rule_iterator_cur = 
2032                         list_entry((*handle)->rule_iterator_cur->list.prev,
2033                                    struct rule_head, list);
2034         }
2035
2036         c->num_rules--;
2037         iptcc_delete_rule(r);
2038
2039         set_changed(*handle);
2040
2041         return 1;
2042 }
2043
2044 /* Check the packet `fw' on chain `chain'.  Returns the verdict, or
2045    NULL and sets errno. */
2046 const char *
2047 TC_CHECK_PACKET(const IPT_CHAINLABEL chain,
2048                 STRUCT_ENTRY *entry,
2049                 TC_HANDLE_T *handle)
2050 {
2051         iptc_fn = TC_CHECK_PACKET;
2052         errno = ENOSYS;
2053         return NULL;
2054 }
2055
2056 /* Flushes the entries in the given chain (ie. empties chain). */
2057 int
2058 TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2059 {
2060         struct chain_head *c;
2061         struct rule_head *r, *tmp;
2062
2063         iptc_fn = TC_FLUSH_ENTRIES;
2064         if (!(c = iptcc_find_label(chain, *handle))) {
2065                 errno = ENOENT;
2066                 return 0;
2067         }
2068
2069         list_for_each_entry_safe(r, tmp, &c->rules, list) {
2070                 iptcc_delete_rule(r);
2071         }
2072
2073         c->num_rules = 0;
2074
2075         set_changed(*handle);
2076
2077         return 1;
2078 }
2079
2080 /* Zeroes the counters in a chain. */
2081 int
2082 TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2083 {
2084         struct chain_head *c;
2085         struct rule_head *r;
2086
2087         iptc_fn = TC_ZERO_ENTRIES;
2088         if (!(c = iptcc_find_label(chain, *handle))) {
2089                 errno = ENOENT;
2090                 return 0;
2091         }
2092
2093         if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2094                 c->counter_map.maptype = COUNTER_MAP_ZEROED;
2095
2096         list_for_each_entry(r, &c->rules, list) {
2097                 if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2098                         r->counter_map.maptype = COUNTER_MAP_ZEROED;
2099         }
2100
2101         set_changed(*handle);
2102
2103         return 1;
2104 }
2105
2106 STRUCT_COUNTERS *
2107 TC_READ_COUNTER(const IPT_CHAINLABEL chain,
2108                 unsigned int rulenum,
2109                 TC_HANDLE_T *handle)
2110 {
2111         struct chain_head *c;
2112         struct rule_head *r;
2113
2114         iptc_fn = TC_READ_COUNTER;
2115         CHECK(*handle);
2116
2117         if (!(c = iptcc_find_label(chain, *handle))) {
2118                 errno = ENOENT;
2119                 return NULL;
2120         }
2121
2122         if (!(r = iptcc_get_rule_num(c, rulenum))) {
2123                 errno = E2BIG;
2124                 return NULL;
2125         }
2126
2127         return &r->entry[0].counters;
2128 }
2129
2130 int
2131 TC_ZERO_COUNTER(const IPT_CHAINLABEL chain,
2132                 unsigned int rulenum,
2133                 TC_HANDLE_T *handle)
2134 {
2135         struct chain_head *c;
2136         struct rule_head *r;
2137         
2138         iptc_fn = TC_ZERO_COUNTER;
2139         CHECK(*handle);
2140
2141         if (!(c = iptcc_find_label(chain, *handle))) {
2142                 errno = ENOENT;
2143                 return 0;
2144         }
2145
2146         if (!(r = iptcc_get_rule_num(c, rulenum))) {
2147                 errno = E2BIG;
2148                 return 0;
2149         }
2150
2151         if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2152                 r->counter_map.maptype = COUNTER_MAP_ZEROED;
2153
2154         set_changed(*handle);
2155
2156         return 1;
2157 }
2158
2159 int 
2160 TC_SET_COUNTER(const IPT_CHAINLABEL chain,
2161                unsigned int rulenum,
2162                STRUCT_COUNTERS *counters,
2163                TC_HANDLE_T *handle)
2164 {
2165         struct chain_head *c;
2166         struct rule_head *r;
2167         STRUCT_ENTRY *e;
2168
2169         iptc_fn = TC_SET_COUNTER;
2170         CHECK(*handle);
2171
2172         if (!(c = iptcc_find_label(chain, *handle))) {
2173                 errno = ENOENT;
2174                 return 0;
2175         }
2176
2177         if (!(r = iptcc_get_rule_num(c, rulenum))) {
2178                 errno = E2BIG;
2179                 return 0;
2180         }
2181
2182         e = r->entry;
2183         r->counter_map.maptype = COUNTER_MAP_SET;
2184
2185         memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS));
2186
2187         set_changed(*handle);
2188
2189         return 1;
2190 }
2191
2192 /* Creates a new chain. */
2193 /* To create a chain, create two rules: error node and unconditional
2194  * return. */
2195 int
2196 TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2197 {
2198         static struct chain_head *c;
2199         int capacity;
2200         int exceeded;
2201
2202         iptc_fn = TC_CREATE_CHAIN;
2203
2204         /* find_label doesn't cover built-in targets: DROP, ACCEPT,
2205            QUEUE, RETURN. */
2206         if (iptcc_find_label(chain, *handle)
2207             || strcmp(chain, LABEL_DROP) == 0
2208             || strcmp(chain, LABEL_ACCEPT) == 0
2209             || strcmp(chain, LABEL_QUEUE) == 0
2210             || strcmp(chain, LABEL_RETURN) == 0) {
2211                 DEBUGP("Chain `%s' already exists\n", chain);
2212                 errno = EEXIST;
2213                 return 0;
2214         }
2215
2216         if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) {
2217                 DEBUGP("Chain name `%s' too long\n", chain);
2218                 errno = EINVAL;
2219                 return 0;
2220         }
2221
2222         c = iptcc_alloc_chain_head(chain, 0);
2223         if (!c) {
2224                 DEBUGP("Cannot allocate memory for chain `%s'\n", chain);
2225                 errno = ENOMEM;
2226                 return 0;
2227
2228         }
2229         (*handle)->num_chains++; /* New user defined chain */
2230
2231         DEBUGP("Creating chain `%s'\n", chain);
2232         iptc_insert_chain(*handle, c); /* Insert sorted */
2233
2234         /* Inserting chains don't change the correctness of the chain
2235          * index (except if its smaller than index[0], but that
2236          * handled by iptc_insert_chain).  It only causes longer lists
2237          * in the buckets. Thus, only rebuild chain index when the
2238          * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains.
2239          */
2240         capacity = (*handle)->chain_index_sz * CHAIN_INDEX_BUCKET_LEN;
2241         exceeded = ((((*handle)->num_chains)-capacity));
2242         if (exceeded > CHAIN_INDEX_INSERT_MAX) {
2243                 debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n",
2244                       capacity, exceeded, (*handle)->num_chains);
2245                 iptcc_chain_index_rebuild(*handle);
2246         }
2247
2248         set_changed(*handle);
2249
2250         return 1;
2251 }
2252
2253 /* Get the number of references to this chain. */
2254 int
2255 TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain,
2256                   TC_HANDLE_T *handle)
2257 {
2258         struct chain_head *c;
2259
2260         iptc_fn = TC_GET_REFERENCES;
2261         if (!(c = iptcc_find_label(chain, *handle))) {
2262                 errno = ENOENT;
2263                 return 0;
2264         }
2265
2266         *ref = c->references;
2267
2268         return 1;
2269 }
2270
2271 /* Deletes a chain. */
2272 int
2273 TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
2274 {
2275         unsigned int references;
2276         struct chain_head *c;
2277
2278         iptc_fn = TC_DELETE_CHAIN;
2279
2280         if (!(c = iptcc_find_label(chain, *handle))) {
2281                 DEBUGP("cannot find chain `%s'\n", chain);
2282                 errno = ENOENT;
2283                 return 0;
2284         }
2285
2286         if (TC_BUILTIN(chain, *handle)) {
2287                 DEBUGP("cannot remove builtin chain `%s'\n", chain);
2288                 errno = EINVAL;
2289                 return 0;
2290         }
2291
2292         if (!TC_GET_REFERENCES(&references, chain, handle)) {
2293                 DEBUGP("cannot get references on chain `%s'\n", chain);
2294                 return 0;
2295         }
2296
2297         if (references > 0) {
2298                 DEBUGP("chain `%s' still has references\n", chain);
2299                 errno = EMLINK;
2300                 return 0;
2301         }
2302
2303         if (c->num_rules) {
2304                 DEBUGP("chain `%s' is not empty\n", chain);
2305                 errno = ENOTEMPTY;
2306                 return 0;
2307         }
2308
2309         /* If we are about to delete the chain that is the current
2310          * iterator, move chain iterator forward. */
2311         if (c == (*handle)->chain_iterator_cur)
2312                 iptcc_chain_iterator_advance(*handle);
2313
2314         (*handle)->num_chains--; /* One user defined chain deleted */
2315
2316         //list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */
2317         iptcc_chain_index_delete_chain(c, *handle);
2318         free(c);
2319
2320         DEBUGP("chain `%s' deleted\n", chain);
2321
2322         set_changed(*handle);
2323
2324         return 1;
2325 }
2326
2327 /* Renames a chain. */
2328 int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname,
2329                     const IPT_CHAINLABEL newname,
2330                     TC_HANDLE_T *handle)
2331 {
2332         struct chain_head *c;
2333         iptc_fn = TC_RENAME_CHAIN;
2334
2335         /* find_label doesn't cover built-in targets: DROP, ACCEPT,
2336            QUEUE, RETURN. */
2337         if (iptcc_find_label(newname, *handle)
2338             || strcmp(newname, LABEL_DROP) == 0
2339             || strcmp(newname, LABEL_ACCEPT) == 0
2340             || strcmp(newname, LABEL_QUEUE) == 0
2341             || strcmp(newname, LABEL_RETURN) == 0) {
2342                 errno = EEXIST;
2343                 return 0;
2344         }
2345
2346         if (!(c = iptcc_find_label(oldname, *handle))
2347             || TC_BUILTIN(oldname, *handle)) {
2348                 errno = ENOENT;
2349                 return 0;
2350         }
2351
2352         if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) {
2353                 errno = EINVAL;
2354                 return 0;
2355         }
2356
2357         strncpy(c->name, newname, sizeof(IPT_CHAINLABEL));
2358         
2359         set_changed(*handle);
2360
2361         return 1;
2362 }
2363
2364 /* Sets the policy on a built-in chain. */
2365 int
2366 TC_SET_POLICY(const IPT_CHAINLABEL chain,
2367               const IPT_CHAINLABEL policy,
2368               STRUCT_COUNTERS *counters,
2369               TC_HANDLE_T *handle)
2370 {
2371         struct chain_head *c;
2372
2373         iptc_fn = TC_SET_POLICY;
2374
2375         if (!(c = iptcc_find_label(chain, *handle))) {
2376                 DEBUGP("cannot find chain `%s'\n", chain);
2377                 errno = ENOENT;
2378                 return 0;
2379         }
2380
2381         if (!iptcc_is_builtin(c)) {
2382                 DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain);
2383                 errno = ENOENT;
2384                 return 0;
2385         }
2386
2387         if (strcmp(policy, LABEL_ACCEPT) == 0)
2388                 c->verdict = -NF_ACCEPT - 1;
2389         else if (strcmp(policy, LABEL_DROP) == 0)
2390                 c->verdict = -NF_DROP - 1;
2391         else {
2392                 errno = EINVAL;
2393                 return 0;
2394         }
2395
2396         if (counters) {
2397                 /* set byte and packet counters */
2398                 memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS));
2399                 c->counter_map.maptype = COUNTER_MAP_SET;
2400         } else {
2401                 c->counter_map.maptype = COUNTER_MAP_NOMAP;
2402         }
2403
2404         set_changed(*handle);
2405
2406         return 1;
2407 }
2408
2409 /* Without this, on gcc 2.7.2.3, we get:
2410    libiptc.c: In function `TC_COMMIT':
2411    libiptc.c:833: fixed or forbidden register was spilled.
2412    This may be due to a compiler bug or to impossible asm
2413    statements or clauses.
2414 */
2415 static void
2416 subtract_counters(STRUCT_COUNTERS *answer,
2417                   const STRUCT_COUNTERS *a,
2418                   const STRUCT_COUNTERS *b)
2419 {
2420         answer->pcnt = a->pcnt - b->pcnt;
2421         answer->bcnt = a->bcnt - b->bcnt;
2422 }
2423
2424
2425 static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx)
2426 {
2427         newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0});
2428         DEBUGP_C("NOMAP => zero\n");
2429 }
2430
2431 static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters,
2432                                 STRUCT_REPLACE *repl, unsigned int idx,
2433                                 unsigned int mappos)
2434 {
2435         /* Original read: X.
2436          * Atomic read on replacement: X + Y.
2437          * Currently in kernel: Z.
2438          * Want in kernel: X + Y + Z.
2439          * => Add in X + Y
2440          * => Add in replacement read.
2441          */
2442         newcounters->counters[idx] = repl->counters[mappos];
2443         DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos);
2444 }
2445
2446 static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters,
2447                                 STRUCT_REPLACE *repl, unsigned int idx,
2448                                 unsigned int mappos, STRUCT_COUNTERS *counters)
2449 {
2450         /* Original read: X.
2451          * Atomic read on replacement: X + Y.
2452          * Currently in kernel: Z.
2453          * Want in kernel: Y + Z.
2454          * => Add in Y.
2455          * => Add in (replacement read - original read).
2456          */
2457         subtract_counters(&newcounters->counters[idx],
2458                           &repl->counters[mappos],
2459                           counters);
2460         DEBUGP_C("ZEROED => mappos %u\n", mappos);
2461 }
2462
2463 static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters,
2464                              unsigned int idx, STRUCT_COUNTERS *counters)
2465 {
2466         /* Want to set counter (iptables-restore) */
2467
2468         memcpy(&newcounters->counters[idx], counters,
2469                 sizeof(STRUCT_COUNTERS));
2470
2471         DEBUGP_C("SET\n");
2472 }
2473
2474
2475 int
2476 TC_COMMIT(TC_HANDLE_T *handle)
2477 {
2478         /* Replace, then map back the counters. */
2479         STRUCT_REPLACE *repl;
2480         STRUCT_COUNTERS_INFO *newcounters;
2481         struct chain_head *c;
2482         int ret;
2483         size_t counterlen;
2484         int new_number;
2485         unsigned int new_size;
2486
2487         iptc_fn = TC_COMMIT;
2488         CHECK(*handle);
2489
2490         /* Don't commit if nothing changed. */
2491         if (!(*handle)->changed)
2492                 goto finished;
2493
2494         new_number = iptcc_compile_table_prep(*handle, &new_size);
2495         if (new_number < 0) {
2496                 errno = ENOMEM;
2497                 goto out_zero;
2498         }
2499
2500         repl = malloc(sizeof(*repl) + new_size);
2501         if (!repl) {
2502                 errno = ENOMEM;
2503                 goto out_zero;
2504         }
2505         memset(repl, 0, sizeof(*repl) + new_size);
2506
2507 #if 0
2508         TC_DUMP_ENTRIES(*handle);
2509 #endif
2510
2511         counterlen = sizeof(STRUCT_COUNTERS_INFO)
2512                         + sizeof(STRUCT_COUNTERS) * new_number;
2513
2514         /* These are the old counters we will get from kernel */
2515         repl->counters = malloc(sizeof(STRUCT_COUNTERS)
2516                                 * (*handle)->info.num_entries);
2517         if (!repl->counters) {
2518                 errno = ENOMEM;
2519                 goto out_free_repl;
2520         }
2521         /* These are the counters we're going to put back, later. */
2522         newcounters = malloc(counterlen);
2523         if (!newcounters) {
2524                 errno = ENOMEM;
2525                 goto out_free_repl_counters;
2526         }
2527         memset(newcounters, 0, counterlen);
2528
2529         strcpy(repl->name, (*handle)->info.name);
2530         repl->num_entries = new_number;
2531         repl->size = new_size;
2532
2533         repl->num_counters = (*handle)->info.num_entries;
2534         repl->valid_hooks = (*handle)->info.valid_hooks;
2535
2536         DEBUGP("num_entries=%u, size=%u, num_counters=%u\n",
2537                 repl->num_entries, repl->size, repl->num_counters);
2538
2539         ret = iptcc_compile_table(*handle, repl);
2540         if (ret < 0) {
2541                 errno = ret;
2542                 goto out_free_newcounters;
2543         }
2544
2545
2546 #ifdef IPTC_DEBUG2
2547         {
2548                 int fd = open("/tmp/libiptc-so_set_replace.blob", 
2549                                 O_CREAT|O_WRONLY);
2550                 if (fd >= 0) {
2551                         write(fd, repl, sizeof(*repl) + repl->size);
2552                         close(fd);
2553                 }
2554         }
2555 #endif
2556
2557         ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_REPLACE, repl,
2558                          sizeof(*repl) + repl->size);
2559         if (ret < 0)
2560                 goto out_free_newcounters;
2561
2562         /* Put counters back. */
2563         strcpy(newcounters->name, (*handle)->info.name);
2564         newcounters->num_counters = new_number;
2565
2566         list_for_each_entry(c, &(*handle)->chains, list) {
2567                 struct rule_head *r;
2568
2569                 /* Builtin chains have their own counters */
2570                 if (iptcc_is_builtin(c)) {
2571                         DEBUGP("counter for chain-index %u: ", c->foot_index);
2572                         switch(c->counter_map.maptype) {
2573                         case COUNTER_MAP_NOMAP:
2574                                 counters_nomap(newcounters, c->foot_index);
2575                                 break;
2576                         case COUNTER_MAP_NORMAL_MAP:
2577                                 counters_normal_map(newcounters, repl,
2578                                                     c->foot_index, 
2579                                                     c->counter_map.mappos);
2580                                 break;
2581                         case COUNTER_MAP_ZEROED:
2582                                 counters_map_zeroed(newcounters, repl,
2583                                                     c->foot_index, 
2584                                                     c->counter_map.mappos,
2585                                                     &c->counters);
2586                                 break;
2587                         case COUNTER_MAP_SET:
2588                                 counters_map_set(newcounters, c->foot_index,
2589                                                  &c->counters);
2590                                 break;
2591                         }
2592                 }
2593
2594                 list_for_each_entry(r, &c->rules, list) {
2595                         DEBUGP("counter for index %u: ", r->index);
2596                         switch (r->counter_map.maptype) {
2597                         case COUNTER_MAP_NOMAP:
2598                                 counters_nomap(newcounters, r->index);
2599                                 break;
2600
2601                         case COUNTER_MAP_NORMAL_MAP:
2602                                 counters_normal_map(newcounters, repl,
2603                                                     r->index, 
2604                                                     r->counter_map.mappos);
2605                                 break;
2606
2607                         case COUNTER_MAP_ZEROED:
2608                                 counters_map_zeroed(newcounters, repl,
2609                                                     r->index,
2610                                                     r->counter_map.mappos,
2611                                                     &r->entry->counters);
2612                                 break;
2613
2614                         case COUNTER_MAP_SET:
2615                                 counters_map_set(newcounters, r->index,
2616                                                  &r->entry->counters);
2617                                 break;
2618                         }
2619                 }
2620         }
2621
2622 #ifdef IPTC_DEBUG2
2623         {
2624                 int fd = open("/tmp/libiptc-so_set_add_counters.blob", 
2625                                 O_CREAT|O_WRONLY);
2626                 if (fd >= 0) {
2627                         write(fd, newcounters, counterlen);
2628                         close(fd);
2629                 }
2630         }
2631 #endif
2632
2633         ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS,
2634                          newcounters, counterlen);
2635         if (ret < 0)
2636                 goto out_free_newcounters;
2637
2638         free(repl->counters);
2639         free(repl);
2640         free(newcounters);
2641
2642 finished:
2643         TC_FREE(handle);
2644         return 1;
2645
2646 out_free_newcounters:
2647         free(newcounters);
2648 out_free_repl_counters:
2649         free(repl->counters);
2650 out_free_repl:
2651         free(repl);
2652 out_zero:
2653         return 0;
2654 }
2655
2656 /* Get raw socket. */
2657 int
2658 TC_GET_RAW_SOCKET(void)
2659 {
2660         return sockfd;
2661 }
2662
2663 /* Translates errno numbers into more human-readable form than strerror. */
2664 const char *
2665 TC_STRERROR(int err)
2666 {
2667         unsigned int i;
2668         struct table_struct {
2669                 void *fn;
2670                 int err;
2671                 const char *message;
2672         } table [] =
2673           { { TC_INIT, EPERM, "Permission denied (you must be root)" },
2674             { TC_INIT, EINVAL, "Module is wrong version" },
2675             { TC_INIT, ENOENT, 
2676                     "Table does not exist (do you need to insmod?)" },
2677             { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" },
2678             { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" },
2679             { TC_DELETE_CHAIN, EMLINK,
2680               "Can't delete chain with references left" },
2681             { TC_CREATE_CHAIN, EEXIST, "Chain already exists" },
2682             { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" },
2683             { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" },
2684             { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" },
2685             { TC_READ_COUNTER, E2BIG, "Index of counter too big" },
2686             { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" },
2687             { TC_INSERT_ENTRY, ELOOP, "Loop found in table" },
2688             { TC_INSERT_ENTRY, EINVAL, "Target problem" },
2689             /* EINVAL for CHECK probably means bad interface. */
2690             { TC_CHECK_PACKET, EINVAL,
2691               "Bad arguments (does that interface exist?)" },
2692             { TC_CHECK_PACKET, ENOSYS,
2693               "Checking will most likely never get implemented" },
2694             /* ENOENT for DELETE probably means no matching rule */
2695             { TC_DELETE_ENTRY, ENOENT,
2696               "Bad rule (does a matching rule exist in that chain?)" },
2697             { TC_SET_POLICY, ENOENT,
2698               "Bad built-in chain name" },
2699             { TC_SET_POLICY, EINVAL,
2700               "Bad policy name" },
2701
2702             { NULL, 0, "Incompatible with this kernel" },
2703             { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" },
2704             { NULL, ENOSYS, "Will be implemented real soon.  I promise ;)" },
2705             { NULL, ENOMEM, "Memory allocation problem" },
2706             { NULL, ENOENT, "No chain/target/match by that name" },
2707           };
2708
2709         for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) {
2710                 if ((!table[i].fn || table[i].fn == iptc_fn)
2711                     && table[i].err == err)
2712                         return table[i].message;
2713         }
2714
2715         return strerror(err);
2716 }