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