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