Don't use 'release' macro.
[platform/upstream/ebtables.git] / libebtc.c
1 /*
2  * libebtc.c, January 2004
3  *
4  * Contains the functions with which to make a table in userspace.
5  *
6  * Author: Bart De Schuymer
7  *
8  *  This code is stongly inspired on the iptables code which is
9  *  Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License as
13  * published by the Free Software Foundation; either version 2 of the
14  * License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  */
25
26 #include <string.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include "include/ebtables_u.h"
31 #include "include/ethernetdb.h"
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <sys/wait.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <errno.h>
38
39 static void decrease_chain_jumps(struct ebt_u_replace *replace);
40 static int iterate_entries(struct ebt_u_replace *replace, int type);
41
42 /* The standard names */
43 const char *ebt_hooknames[NF_BR_NUMHOOKS] =
44 {
45         [NF_BR_PRE_ROUTING]"PREROUTING",
46         [NF_BR_LOCAL_IN]"INPUT",
47         [NF_BR_FORWARD]"FORWARD",
48         [NF_BR_LOCAL_OUT]"OUTPUT",
49         [NF_BR_POST_ROUTING]"POSTROUTING",
50         [NF_BR_BROUTING]"BROUTING"
51 };
52
53 /* The four target names */
54 const char* ebt_standard_targets[NUM_STANDARD_TARGETS] =
55 {
56         "ACCEPT",
57         "DROP",
58         "CONTINUE",
59         "RETURN",
60 };
61
62 /* The lists of supported tables, matches, watchers and targets */
63 struct ebt_u_table *ebt_tables;
64 struct ebt_u_match *ebt_matches;
65 struct ebt_u_watcher *ebt_watchers;
66 struct ebt_u_target *ebt_targets;
67
68 /* Find the right structure belonging to a name */
69 struct ebt_u_target *ebt_find_target(const char *name)
70 {
71         struct ebt_u_target *t = ebt_targets;
72
73         while (t && strcmp(t->name, name))
74                 t = t->next;
75         return t;
76 }
77
78 struct ebt_u_match *ebt_find_match(const char *name)
79 {
80         struct ebt_u_match *m = ebt_matches;
81
82         while (m && strcmp(m->name, name))
83                 m = m->next;
84         return m;
85 }
86
87 struct ebt_u_watcher *ebt_find_watcher(const char *name)
88 {
89         struct ebt_u_watcher *w = ebt_watchers;
90
91         while (w && strcmp(w->name, name))
92                 w = w->next;
93         return w;
94 }
95
96 struct ebt_u_table *ebt_find_table(const char *name)
97 {
98         struct ebt_u_table *t = ebt_tables;
99
100         while (t && strcmp(t->name, name))
101                 t = t->next;
102         return t;
103 }
104
105 /* Prints all registered extensions */
106 void ebt_list_extensions()
107 {
108         struct ebt_u_table *tbl = ebt_tables;
109         struct ebt_u_target *t = ebt_targets;
110         struct ebt_u_match *m = ebt_matches;
111         struct ebt_u_watcher *w = ebt_watchers;
112
113         PRINT_VERSION;
114         printf("Loaded userspace extensions:\n\nLoaded tables:\n");
115         while (tbl) {
116                 printf("%s\n", tbl->name);
117                 tbl = tbl->next;
118         }
119         printf("\nLoaded targets:\n");
120         while (t) {
121                 printf("%s\n", t->name);
122                 t = t->next;
123         }
124         printf("\nLoaded matches:\n");
125         while (m) {
126                 printf("%s\n", m->name);
127                 m = m->next;
128         }
129         printf("\nLoaded watchers:\n");
130         while (w) {
131                 printf("%s\n", w->name);
132                 w = w->next;
133         }
134 }
135
136 #ifndef LOCKFILE
137 #define LOCKDIR "/var/lib/ebtables"
138 #define LOCKFILE LOCKDIR"/lock"
139 #endif
140 static int lockfd = -1, locked;
141 int use_lockfd;
142 /* Returns 0 on success, -1 when the file is locked by another process
143  * or -2 on any other error. */
144 static int lock_file()
145 {
146         int try = 0;
147         int ret = 0;
148         sigset_t sigset;
149
150 tryagain:
151         /* the SIGINT handler will call unlock_file. To make sure the state
152          * of the variable locked is correct, we need to temporarily mask the
153          * SIGINT interrupt. */
154         sigemptyset(&sigset);
155         sigaddset(&sigset, SIGINT);
156         sigprocmask(SIG_BLOCK, &sigset, NULL);
157         lockfd = open(LOCKFILE, O_CREAT | O_EXCL | O_WRONLY, 00600);
158         if (lockfd < 0) {
159                 if (errno == EEXIST)
160                         ret = -1;
161                 else if (try == 1)
162                         ret = -2;
163                 else {
164                         if (mkdir(LOCKDIR, 00700))
165                                 ret = -2;
166                         else {
167                                 try = 1;
168                                 goto tryagain;
169                         }
170                 }
171         } else {
172                 close(lockfd);
173                 locked = 1;
174         }
175         sigprocmask(SIG_UNBLOCK, &sigset, NULL);
176         return ret;
177 }
178
179 void unlock_file()
180 {
181         if (locked) {
182                 remove(LOCKFILE);
183                 locked = 0;
184         }
185 }
186
187 void __attribute__ ((destructor)) onexit()
188 {
189         if (use_lockfd)
190                 unlock_file();
191 }
192 /* Get the table from the kernel or from a binary file
193  * init: 1 = ask the kernel for the initial contents of a table, i.e. the
194  *           way it looks when the table is insmod'ed
195  *       0 = get the current data in the table */
196 int ebt_get_kernel_table(struct ebt_u_replace *replace, int init)
197 {
198         int ret;
199
200         if (!ebt_find_table(replace->name)) {
201                 ebt_print_error("Bad table name '%s'", replace->name);
202                 return -1;
203         }
204         while (use_lockfd && (ret = lock_file())) {
205                 if (ret == -2) {
206                         /* if we get an error we can't handle, we exit. This
207                          * doesn't break backwards compatibility since using
208                          * this file locking is disabled by default. */
209                         ebt_print_error2("Unable to create lock file "LOCKFILE);
210                 }
211                 fprintf(stderr, "Trying to obtain lock %s\n", LOCKFILE);
212                 sleep(1);
213         }
214         /* Get the kernel's information */
215         if (ebt_get_table(replace, init)) {
216                 if (ebt_errormsg[0] != '\0')
217                         return -1;
218                 ebtables_insmod("ebtables");
219                 if (ebt_get_table(replace, init)) {
220                         ebt_print_error("The kernel doesn't support the ebtables '%s' table", replace->name);
221                         return -1;
222                 }
223         }
224         return 0;
225 }
226
227 /* Put sane values into a new entry */
228 void ebt_initialize_entry(struct ebt_u_entry *e)
229 {
230         e->bitmask = EBT_NOPROTO;
231         e->invflags = 0;
232         e->ethproto = 0;
233         strcpy(e->in, "");
234         strcpy(e->out, "");
235         strcpy(e->logical_in, "");
236         strcpy(e->logical_out, "");
237         e->m_list = NULL;
238         e->w_list = NULL;
239         e->t = (struct ebt_entry_target *)ebt_find_target(EBT_STANDARD_TARGET);
240         ebt_find_target(EBT_STANDARD_TARGET)->used = 1;
241         e->cnt.pcnt = e->cnt.bcnt = e->cnt_surplus.pcnt = e->cnt_surplus.bcnt = 0;
242
243         if (!e->t)
244                 ebt_print_bug("Couldn't load standard target");
245         ((struct ebt_standard_target *)((struct ebt_u_target *)e->t)->t)->verdict = EBT_CONTINUE;
246 }
247
248 /* Free up the memory of the table held in userspace, *replace can be reused */
249 void ebt_cleanup_replace(struct ebt_u_replace *replace)
250 {
251         int i;
252         struct ebt_u_entries *entries;
253         struct ebt_cntchanges *cc1, *cc2;
254         struct ebt_u_entry *u_e1, *u_e2;
255
256         replace->name[0] = '\0';
257         replace->valid_hooks = 0;
258         replace->nentries = 0;
259         replace->num_counters = 0;
260         replace->flags = 0;
261         replace->command = 0;
262         replace->selected_chain = -1;
263         free(replace->filename);
264         replace->filename = NULL;
265         free(replace->counters);
266         replace->counters = NULL;
267
268         for (i = 0; i < replace->num_chains; i++) {
269                 if (!(entries = replace->chains[i]))
270                         continue;
271                 u_e1 = entries->entries->next;
272                 while (u_e1 != entries->entries) {
273                         ebt_free_u_entry(u_e1);
274                         u_e2 = u_e1->next;
275                         free(u_e1);
276                         u_e1 = u_e2;
277                 }
278                 free(entries->entries);
279                 free(entries);
280                 replace->chains[i] = NULL;
281         }
282         cc1 = replace->cc->next;
283         while (cc1 != replace->cc) {
284                 cc2 = cc1->next;
285                 free(cc1);
286                 cc1 = cc2;
287         }
288         replace->cc->next = replace->cc->prev = replace->cc;
289 }
290
291 /* Should be called, e.g., between 2 rule adds */
292 void ebt_reinit_extensions()
293 {
294         struct ebt_u_match *m;
295         struct ebt_u_watcher *w;
296         struct ebt_u_target *t;
297         int size;
298
299         /* The init functions should determine by themselves whether they are
300          * called for the first time or not (when necessary). */
301         for (m = ebt_matches; m; m = m->next) {
302                 if (m->used) {
303                         size = EBT_ALIGN(m->size) + sizeof(struct ebt_entry_match);
304                         m->m = (struct ebt_entry_match *)malloc(size);
305                         if (!m->m)
306                                 ebt_print_memory();
307                         strcpy(m->m->u.name, m->name);
308                         m->m->match_size = EBT_ALIGN(m->size);
309                         m->used = 0;
310                 }
311                 m->flags = 0; /* An error can occur before used is set, while flags is changed. */
312                 m->init(m->m);
313         }
314         for (w = ebt_watchers; w; w = w->next) {
315                 if (w->used) {
316                         size = EBT_ALIGN(w->size) + sizeof(struct ebt_entry_watcher);
317                         w->w = (struct ebt_entry_watcher *)malloc(size);
318                         if (!w->w)
319                                 ebt_print_memory();
320                         strcpy(w->w->u.name, w->name);
321                         w->w->watcher_size = EBT_ALIGN(w->size);
322                         w->used = 0;
323                 }
324                 w->flags = 0;
325                 w->init(w->w);
326         }
327         for (t = ebt_targets; t; t = t->next) {
328                 if (t->used) {
329                         size = EBT_ALIGN(t->size) + sizeof(struct ebt_entry_target);
330                         t->t = (struct ebt_entry_target *)malloc(size);
331                         if (!t->t)
332                                 ebt_print_memory();
333                         strcpy(t->t->u.name, t->name);
334                         t->t->target_size = EBT_ALIGN(t->size);
335                         t->used = 0;
336                 }
337                 t->flags = 0;
338                 t->init(t->t);
339         }
340 }
341
342 /* This doesn't free e, because the calling function might need e->next */
343 void ebt_free_u_entry(struct ebt_u_entry *e)
344 {
345         struct ebt_u_match_list *m_l, *m_l2;
346         struct ebt_u_watcher_list *w_l, *w_l2;
347
348         m_l = e->m_list;
349         while (m_l) {
350                 m_l2 = m_l->next;
351                 free(m_l->m);
352                 free(m_l);
353                 m_l = m_l2;
354         }
355         w_l = e->w_list;
356         while (w_l) {
357                 w_l2 = w_l->next;
358                 free(w_l->w);
359                 free(w_l);
360                 w_l = w_l2;
361         }
362         free(e->t);
363 }
364
365 static char *get_modprobe(void)
366 {
367         int procfile;
368         char *ret;
369
370         procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
371         if (procfile < 0)
372                 return NULL;
373
374         ret = malloc(1024);
375         if (ret) {
376                 if (read(procfile, ret, 1024) == -1)
377                         goto fail;
378                 /* The kernel adds a '\n' */
379                 ret[1023] = '\n';
380                 *strchr(ret, '\n') = '\0';
381                 close(procfile);
382                 return ret;
383         }
384  fail:
385         free(ret);
386         close(procfile);
387         return NULL;
388 }
389
390 char *ebt_modprobe;
391 /* Try to load the kernel module, analogous to ip_tables.c */
392 int ebtables_insmod(const char *modname)
393 {
394         char *buf = NULL;
395         char *argv[3];
396
397         /* If they don't explicitly set it, read out of /proc */
398         if (!ebt_modprobe) {
399                 buf = get_modprobe();
400                 if (!buf)
401                         return -1;
402                 ebt_modprobe = buf; /* Keep the value for possible later use */
403         }
404
405         switch (fork()) {
406         case 0:
407                 argv[0] = (char *)ebt_modprobe;
408                 argv[1] = (char *)modname;
409                 argv[2] = NULL;
410                 execv(argv[0], argv);
411
412                 /* Not usually reached */
413                 exit(0);
414         case -1:
415                 return -1;
416
417         default: /* Parent */
418                 wait(NULL);
419         }
420
421         return 0;
422 }
423
424 /* Parse the chain name and return a pointer to the chain base.
425  * Returns NULL on failure. */
426 struct ebt_u_entries *ebt_name_to_chain(const struct ebt_u_replace *replace, const char* arg)
427 {
428         int i;
429         struct ebt_u_entries *chain;
430
431         for (i = 0; i < replace->num_chains; i++) {
432                 if (!(chain = replace->chains[i]))
433                         continue;
434                 if (!strcmp(arg, chain->name))
435                         return chain;
436         }
437         return NULL;
438 }
439
440 /* Parse the chain name and return the corresponding chain nr
441  * returns -1 on failure */
442 int ebt_get_chainnr(const struct ebt_u_replace *replace, const char* arg)
443 {
444         int i;
445
446         for (i = 0; i < replace->num_chains; i++) {
447                 if (!replace->chains[i])
448                         continue;
449                 if (!strcmp(arg, replace->chains[i]->name))
450                         return i;
451         }
452         return -1;
453 }
454
455      /*
456 ************
457 ************
458 **COMMANDS**
459 ************
460 ************
461      */
462
463 /* Change the policy of selected_chain.
464  * Handing a bad policy to this function is a bug. */
465 void ebt_change_policy(struct ebt_u_replace *replace, int policy)
466 {
467         struct ebt_u_entries *entries = ebt_to_chain(replace);
468
469         if (policy < -NUM_STANDARD_TARGETS || policy == EBT_CONTINUE)
470                 ebt_print_bug("Wrong policy: %d", policy);
471         entries->policy = policy;
472 }
473
474 void ebt_delete_cc(struct ebt_cntchanges *cc)
475 {
476         if (cc->type == CNT_ADD) {
477                 cc->prev->next = cc->next;
478                 cc->next->prev = cc->prev;
479                 free(cc);
480         } else
481                 cc->type = CNT_DEL;
482 }
483
484 void ebt_empty_chain(struct ebt_u_entries *entries)
485 {
486         struct ebt_u_entry *u_e = entries->entries->next, *tmp;
487         while (u_e != entries->entries) {
488                 ebt_delete_cc(u_e->cc);
489                 ebt_free_u_entry(u_e);
490                 tmp = u_e->next;
491                 free(u_e);
492                 u_e = tmp;
493         }
494         entries->entries->next = entries->entries->prev = entries->entries;
495         entries->nentries = 0;
496 }
497
498 /* Flush one chain or the complete table
499  * If selected_chain == -1 then flush the complete table */
500 void ebt_flush_chains(struct ebt_u_replace *replace)
501 {
502         int i, numdel;
503         struct ebt_u_entries *entries = ebt_to_chain(replace);
504
505         /* Flush whole table */
506         if (!entries) {
507                 if (replace->nentries == 0)
508                         return;
509                 replace->nentries = 0;
510
511                 /* Free everything and zero (n)entries */
512                 for (i = 0; i < replace->num_chains; i++) {
513                         if (!(entries = replace->chains[i]))
514                                 continue;
515                         entries->counter_offset = 0;
516                         ebt_empty_chain(entries);
517                 }
518                 return;
519         }
520
521         if (entries->nentries == 0)
522                 return;
523         replace->nentries -= entries->nentries;
524         numdel = entries->nentries;
525
526         /* Update counter_offset */
527         for (i = replace->selected_chain+1; i < replace->num_chains; i++) {
528                 if (!(entries = replace->chains[i]))
529                         continue;
530                 entries->counter_offset -= numdel;
531         }
532
533         entries = ebt_to_chain(replace);
534         ebt_empty_chain(entries);
535 }
536
537 #define OPT_COUNT       0x1000 /* This value is also defined in ebtables.c */
538 /* Returns the rule number on success (starting from 0), -1 on failure
539  *
540  * This function expects the ebt_{match,watcher,target} members of new_entry
541  * to contain pointers to ebt_u_{match,watcher,target} */
542 int ebt_check_rule_exists(struct ebt_u_replace *replace,
543                           struct ebt_u_entry *new_entry)
544 {
545         struct ebt_u_entry *u_e;
546         struct ebt_u_match_list *m_l, *m_l2;
547         struct ebt_u_match *m;
548         struct ebt_u_watcher_list *w_l, *w_l2;
549         struct ebt_u_watcher *w;
550         struct ebt_u_target *t = (struct ebt_u_target *)new_entry->t;
551         struct ebt_u_entries *entries = ebt_to_chain(replace);
552         int i, j, k;
553
554         u_e = entries->entries->next;
555         /* Check for an existing rule (if there are duplicate rules,
556          * take the first occurance) */
557         for (i = 0; i < entries->nentries; i++, u_e = u_e->next) {
558                 if (u_e->ethproto != new_entry->ethproto)
559                         continue;
560                 if (strcmp(u_e->in, new_entry->in))
561                         continue;
562                 if (strcmp(u_e->out, new_entry->out))
563                         continue;
564                 if (strcmp(u_e->logical_in, new_entry->logical_in))
565                         continue;
566                 if (strcmp(u_e->logical_out, new_entry->logical_out))
567                         continue;
568                 if (new_entry->bitmask & EBT_SOURCEMAC &&
569                     memcmp(u_e->sourcemac, new_entry->sourcemac, ETH_ALEN))
570                         continue;
571                 if (new_entry->bitmask & EBT_DESTMAC &&
572                     memcmp(u_e->destmac, new_entry->destmac, ETH_ALEN))
573                         continue;
574                 if (new_entry->bitmask != u_e->bitmask ||
575                     new_entry->invflags != u_e->invflags)
576                         continue;
577                 if (replace->flags & OPT_COUNT && (new_entry->cnt.pcnt !=
578                     u_e->cnt.pcnt || new_entry->cnt.bcnt != u_e->cnt.bcnt))
579                         continue;
580                 /* Compare all matches */
581                 m_l = new_entry->m_list;
582                 j = 0;
583                 while (m_l) {
584                         m = (struct ebt_u_match *)(m_l->m);
585                         m_l2 = u_e->m_list;
586                         while (m_l2 && strcmp(m_l2->m->u.name, m->m->u.name))
587                                 m_l2 = m_l2->next;
588                         if (!m_l2 || !m->compare(m->m, m_l2->m))
589                                 goto letscontinue;
590                         j++;
591                         m_l = m_l->next;
592                 }
593                 /* Now be sure they have the same nr of matches */
594                 k = 0;
595                 m_l = u_e->m_list;
596                 while (m_l) {
597                         k++;
598                         m_l = m_l->next;
599                 }
600                 if (j != k)
601                         continue;
602
603                 /* Compare all watchers */
604                 w_l = new_entry->w_list;
605                 j = 0;
606                 while (w_l) {
607                         w = (struct ebt_u_watcher *)(w_l->w);
608                         w_l2 = u_e->w_list;
609                         while (w_l2 && strcmp(w_l2->w->u.name, w->w->u.name))
610                                 w_l2 = w_l2->next;
611                         if (!w_l2 || !w->compare(w->w, w_l2->w))
612                                 goto letscontinue;
613                         j++;
614                         w_l = w_l->next;
615                 }
616                 k = 0;
617                 w_l = u_e->w_list;
618                 while (w_l) {
619                         k++;
620                         w_l = w_l->next;
621                 }
622                 if (j != k)
623                         continue;
624                 if (strcmp(t->t->u.name, u_e->t->u.name))
625                         continue;
626                 if (!t->compare(t->t, u_e->t))
627                         continue;
628                 return i;
629 letscontinue:;
630         }
631         return -1;
632 }
633
634 /* Add a rule, rule_nr is the rule to update
635  * rule_nr specifies where the rule should be inserted
636  * rule_nr > 0 : insert the rule right before the rule_nr'th rule
637  *               (the first rule is rule 1)
638  * rule_nr < 0 : insert the rule right before the (n+rule_nr+1)'th rule,
639  *               where n denotes the number of rules in the chain
640  * rule_nr == 0: add a new rule at the end of the chain
641  *
642  * This function expects the ebt_{match,watcher,target} members of new_entry
643  * to contain pointers to ebt_u_{match,watcher,target} and updates these
644  * pointers so that they point to ebt_{match,watcher,target}, before adding
645  * the rule to the chain. Don't free() the ebt_{match,watcher,target} and
646  * don't reuse the new_entry after a successful call to ebt_add_rule() */
647 void ebt_add_rule(struct ebt_u_replace *replace, struct ebt_u_entry *new_entry, int rule_nr)
648 {
649         int i;
650         struct ebt_u_entry *u_e;
651         struct ebt_u_match_list *m_l;
652         struct ebt_u_watcher_list *w_l;
653         struct ebt_u_entries *entries = ebt_to_chain(replace);
654         struct ebt_cntchanges *cc, *new_cc;
655
656         if (rule_nr <= 0)
657                 rule_nr += entries->nentries;
658         else
659                 rule_nr--;
660         if (rule_nr > entries->nentries || rule_nr < 0) {
661                 ebt_print_error("The specified rule number is incorrect");
662                 return;
663         }
664         /* Go to the right position in the chain */
665         if (rule_nr == entries->nentries)
666                 u_e = entries->entries;
667         else {
668                 u_e = entries->entries->next;
669                 for (i = 0; i < rule_nr; i++)
670                         u_e = u_e->next;
671         }
672         /* We're adding one rule */
673         replace->nentries++;
674         entries->nentries++;
675         /* Insert the rule */
676         new_entry->next = u_e;
677         new_entry->prev = u_e->prev;
678         u_e->prev->next = new_entry;
679         u_e->prev = new_entry;
680         new_cc = (struct ebt_cntchanges *)malloc(sizeof(struct ebt_cntchanges));
681         if (!new_cc)
682                 ebt_print_memory();
683         new_cc->type = CNT_ADD;
684         new_cc->change = 0;
685         if (new_entry->next == entries->entries) {
686                 for (i = replace->selected_chain+1; i < replace->num_chains; i++)
687                         if (!replace->chains[i] || replace->chains[i]->nentries == 0)
688                                 continue;
689                         else
690                                 break;
691                 if (i == replace->num_chains)
692                         cc = replace->cc;
693                 else
694                         cc = replace->chains[i]->entries->next->cc;
695         } else
696                 cc = new_entry->next->cc;
697         new_cc->next = cc;
698         new_cc->prev = cc->prev;
699         cc->prev->next = new_cc;
700         cc->prev = new_cc;
701         new_entry->cc = new_cc;
702
703         /* Put the ebt_{match, watcher, target} pointers in place */
704         m_l = new_entry->m_list;
705         while (m_l) {
706                 m_l->m = ((struct ebt_u_match *)m_l->m)->m;
707                 m_l = m_l->next;
708         }
709         w_l = new_entry->w_list;
710         while (w_l) {
711                 w_l->w = ((struct ebt_u_watcher *)w_l->w)->w;
712                 w_l = w_l->next;
713         }
714         new_entry->t = ((struct ebt_u_target *)new_entry->t)->t;
715         /* Update the counter_offset of chains behind this one */
716         for (i = replace->selected_chain+1; i < replace->num_chains; i++) {
717                 entries = replace->chains[i];
718                 if (!(entries = replace->chains[i]))
719                         continue;
720                 entries->counter_offset++;
721         }
722 }
723
724 /* If *begin==*end==0 then find the rule corresponding to new_entry,
725  * else make the rule numbers positive (starting from 0) and check
726  * for bad rule numbers. */
727 static int check_and_change_rule_number(struct ebt_u_replace *replace,
728    struct ebt_u_entry *new_entry, int *begin, int *end)
729 {
730         struct ebt_u_entries *entries = ebt_to_chain(replace);
731
732         if (*begin < 0)
733                 *begin += entries->nentries + 1;
734         if (*end < 0)
735                 *end += entries->nentries + 1;
736
737         if (*begin < 0 || *begin > *end || *end > entries->nentries) {
738                 ebt_print_error("Sorry, wrong rule numbers");
739                 return -1;
740         }
741
742         if ((*begin * *end == 0) && (*begin + *end != 0))
743                 ebt_print_bug("begin and end should be either both zero, "
744                               "either both non-zero");
745         if (*begin != 0) {
746                 (*begin)--;
747                 (*end)--;
748         } else {
749                 *begin = ebt_check_rule_exists(replace, new_entry);
750                 *end = *begin;
751                 if (*begin == -1) {
752                         ebt_print_error("Sorry, rule does not exist");
753                         return -1;
754                 }
755         }
756         return 0;
757 }
758
759 /* Delete a rule or rules
760  * begin == end == 0: delete the rule corresponding to new_entry
761  *
762  * The first rule has rule nr 1, the last rule has rule nr -1, etc.
763  * This function expects the ebt_{match,watcher,target} members of new_entry
764  * to contain pointers to ebt_u_{match,watcher,target}. */
765 void ebt_delete_rule(struct ebt_u_replace *replace,
766                      struct ebt_u_entry *new_entry, int begin, int end)
767 {
768         int i,  nr_deletes;
769         struct ebt_u_entry *u_e, *u_e2, *u_e3;
770         struct ebt_u_entries *entries = ebt_to_chain(replace);
771
772         if (check_and_change_rule_number(replace, new_entry, &begin, &end))
773                 return;
774         /* We're deleting rules */
775         nr_deletes = end - begin + 1;
776         replace->nentries -= nr_deletes;
777         entries->nentries -= nr_deletes;
778         /* Go to the right position in the chain */
779         u_e = entries->entries->next;
780         for (i = 0; i < begin; i++)
781                 u_e = u_e->next;
782         u_e3 = u_e->prev;
783         /* Remove the rules */
784         for (i = 0; i < nr_deletes; i++) {
785                 u_e2 = u_e;
786                 ebt_delete_cc(u_e2->cc);
787                 u_e = u_e->next;
788                 /* Free everything */
789                 ebt_free_u_entry(u_e2);
790                 free(u_e2);
791         }
792         u_e3->next = u_e;
793         u_e->prev = u_e3;
794         /* Update the counter_offset of chains behind this one */
795         for (i = replace->selected_chain+1; i < replace->num_chains; i++) {
796                 if (!(entries = replace->chains[i]))
797                         continue;
798                 entries->counter_offset -= nr_deletes;
799         }
800 }
801
802 /* Change the counters of a rule or rules
803  * begin == end == 0: change counters of the rule corresponding to new_entry
804  *
805  * The first rule has rule nr 1, the last rule has rule nr -1, etc.
806  * This function expects the ebt_{match,watcher,target} members of new_entry
807  * to contain pointers to ebt_u_{match,watcher,target}.
808  * The mask denotes the following:
809  *    pcnt: mask % 3 = 0 : change; = 1: increment; = 2: decrement
810  *    bcnt: mask / 3 = 0 : change; = 1: increment = 2: increment
811  * In daemon mode, mask==0 must hold */
812 void ebt_change_counters(struct ebt_u_replace *replace,
813                      struct ebt_u_entry *new_entry, int begin, int end,
814                      struct ebt_counter *cnt, int mask)
815 {
816         int i;
817         struct ebt_u_entry *u_e;
818         struct ebt_u_entries *entries = ebt_to_chain(replace);
819
820         if (check_and_change_rule_number(replace, new_entry, &begin, &end))
821                 return;
822         u_e = entries->entries->next;
823         for (i = 0; i < begin; i++)
824                 u_e = u_e->next;
825         for (i = end-begin+1; i > 0; i--) {
826                 if (mask % 3 == 0) {
827                         u_e->cnt.pcnt = (*cnt).pcnt;
828                         u_e->cnt_surplus.pcnt = 0;
829                 } else {
830 #ifdef EBT_DEBUG
831                         if (u_e->cc->type != CNT_NORM)
832                                 ebt_print_bug("cc->type != CNT_NORM");
833 #endif
834                         u_e->cnt_surplus.pcnt = (*cnt).pcnt;
835                 }
836
837                 if (mask / 3 == 0) {
838                         u_e->cnt.bcnt = (*cnt).bcnt;
839                         u_e->cnt_surplus.bcnt = 0;
840                 } else {
841 #ifdef EBT_DEBUG
842                         if (u_e->cc->type != CNT_NORM)
843                                 ebt_print_bug("cc->type != CNT_NORM");
844 #endif
845                         u_e->cnt_surplus.bcnt = (*cnt).bcnt;
846                 }
847                 if (u_e->cc->type != CNT_ADD)
848                         u_e->cc->type = CNT_CHANGE;
849                 u_e->cc->change = mask;
850                 u_e = u_e->next;
851         }
852 }
853
854 /* If selected_chain == -1 then zero all counters,
855  * otherwise, zero the counters of selected_chain */
856 void ebt_zero_counters(struct ebt_u_replace *replace)
857 {
858         struct ebt_u_entries *entries = ebt_to_chain(replace);
859         struct ebt_u_entry *next;
860         int i;
861
862         if (!entries) {
863                 for (i = 0; i < replace->num_chains; i++) {
864                         if (!(entries = replace->chains[i]))
865                                 continue;
866                         next = entries->entries->next;
867                         while (next != entries->entries) {
868                                 if (next->cc->type == CNT_NORM)
869                                         next->cc->type = CNT_CHANGE;
870                                 next->cnt.bcnt = next->cnt.pcnt = 0;
871                                 next->cc->change = 0;
872                                 next = next->next;
873                         }
874                 }
875         } else {
876                 if (entries->nentries == 0)
877                         return;
878
879                 next = entries->entries->next;
880                 while (next != entries->entries) {
881                         if (next->cc->type == CNT_NORM)
882                                 next->cc->type = CNT_CHANGE;
883                         next->cnt.bcnt = next->cnt.pcnt = 0;
884                         next = next->next;
885                 }
886         }
887 }
888
889 /* Add a new chain and specify its policy */
890 void ebt_new_chain(struct ebt_u_replace *replace, const char *name, int policy)
891 {
892         struct ebt_u_entries *new;
893
894         if (replace->num_chains == replace->max_chains)
895                 ebt_double_chains(replace);
896         new = (struct ebt_u_entries *)malloc(sizeof(struct ebt_u_entries));
897         if (!new)
898                 ebt_print_memory();
899         replace->chains[replace->num_chains++] = new;
900         new->nentries = 0;
901         new->policy = policy;
902         new->counter_offset = replace->nentries;
903         new->hook_mask = 0;
904         strcpy(new->name, name);
905         new->entries = (struct ebt_u_entry *)malloc(sizeof(struct ebt_u_entry));
906         if (!new->entries)
907                 ebt_print_memory();
908         new->entries->next = new->entries->prev = new->entries;
909         new->kernel_start = NULL;
910 }
911
912 /* returns -1 if the chain is referenced, 0 on success */
913 static int ebt_delete_a_chain(struct ebt_u_replace *replace, int chain, int print_err)
914 {
915         int tmp = replace->selected_chain;
916         /* If the chain is referenced, don't delete it,
917          * also decrement jumps to a chain behind the
918          * one we're deleting */
919         replace->selected_chain = chain;
920         if (ebt_check_for_references(replace, print_err))
921                 return -1;
922         decrease_chain_jumps(replace);
923         ebt_flush_chains(replace);
924         replace->selected_chain = tmp;
925         free(replace->chains[chain]->entries);
926         free(replace->chains[chain]);
927         memmove(replace->chains+chain, replace->chains+chain+1, (replace->num_chains-chain-1)*sizeof(void *));
928         replace->num_chains--;
929         return 0;
930 }
931
932 /* Selected_chain == -1: delete all non-referenced udc
933  * selected_chain < NF_BR_NUMHOOKS is illegal */
934 void ebt_delete_chain(struct ebt_u_replace *replace)
935 {
936         if (replace->selected_chain != -1 && replace->selected_chain < NF_BR_NUMHOOKS)
937                 ebt_print_bug("You can't remove a standard chain");
938         if (replace->selected_chain == -1) {
939                 int i = NF_BR_NUMHOOKS;
940
941                 while (i < replace->num_chains)
942                         if (ebt_delete_a_chain(replace, i, 0))
943                                 i++;
944         } else
945                 ebt_delete_a_chain(replace, replace->selected_chain, 1);
946 }
947
948 /* Rename an existing chain. */
949 void ebt_rename_chain(struct ebt_u_replace *replace, const char *name)
950 {
951         struct ebt_u_entries *entries = ebt_to_chain(replace);
952
953         if (!entries)
954                 ebt_print_bug("ebt_rename_chain: entries == NULL");
955         strcpy(entries->name, name);
956 }
957
958
959            /*
960 *************************
961 *************************
962 **SPECIALIZED*FUNCTIONS**
963 *************************
964 *************************
965             */
966
967
968 void ebt_double_chains(struct ebt_u_replace *replace)
969 {
970         struct ebt_u_entries **new;
971
972         replace->max_chains *= 2;
973         new = (struct ebt_u_entries **)malloc(replace->max_chains*sizeof(void *));
974         if (!new)
975                 ebt_print_memory();
976         memcpy(new, replace->chains, replace->max_chains/2*sizeof(void *));
977         free(replace->chains);
978         replace->chains = new;
979 }
980
981 /* Executes the final_check() function for all extensions used by the rule
982  * ebt_check_for_loops should have been executed earlier, to make sure the
983  * hook_mask is correct. The time argument to final_check() is set to 1,
984  * meaning it's the second time the final_check() function is executed. */
985 void ebt_do_final_checks(struct ebt_u_replace *replace, struct ebt_u_entry *e,
986                          struct ebt_u_entries *entries)
987 {
988         struct ebt_u_match_list *m_l;
989         struct ebt_u_watcher_list *w_l;
990         struct ebt_u_target *t;
991         struct ebt_u_match *m;
992         struct ebt_u_watcher *w;
993
994         m_l = e->m_list;
995         w_l = e->w_list;
996         while (m_l) {
997                 m = ebt_find_match(m_l->m->u.name);
998                 m->final_check(e, m_l->m, replace->name,
999                    entries->hook_mask, 1);
1000                 if (ebt_errormsg[0] != '\0')
1001                         return;
1002                 m_l = m_l->next;
1003         }
1004         while (w_l) {
1005                 w = ebt_find_watcher(w_l->w->u.name);
1006                 w->final_check(e, w_l->w, replace->name,
1007                    entries->hook_mask, 1);
1008                 if (ebt_errormsg[0] != '\0')
1009                         return;
1010                 w_l = w_l->next;
1011         }
1012         t = ebt_find_target(e->t->u.name);
1013         t->final_check(e, e->t, replace->name,
1014            entries->hook_mask, 1);
1015 }
1016
1017 /* Returns 1 (if it returns) when the chain is referenced, 0 when it isn't.
1018  * print_err: 0 (resp. 1) = don't (resp. do) print error when referenced */
1019 int ebt_check_for_references(struct ebt_u_replace *replace, int print_err)
1020 {
1021         if (print_err)
1022                 return iterate_entries(replace, 1);
1023         else
1024                 return iterate_entries(replace, 2);
1025 }
1026
1027 /* chain_nr: nr of the udc (>= NF_BR_NUMHOOKS)
1028  * Returns 1 (if it returns) when the chain is referenced, 0 when it isn't.
1029  * print_err: 0 (resp. 1) = don't (resp. do) print error when referenced */
1030 int ebt_check_for_references2(struct ebt_u_replace *replace, int chain_nr,
1031                               int print_err)
1032 {
1033         int tmp = replace->selected_chain, ret;
1034
1035         replace->selected_chain = chain_nr;
1036         if (print_err)
1037                 ret = iterate_entries(replace, 1);
1038         else
1039                 ret = iterate_entries(replace, 2);
1040         replace->selected_chain = tmp;
1041         return ret;
1042 }
1043
1044 struct ebt_u_stack
1045 {
1046         int chain_nr;
1047         int n;
1048         struct ebt_u_entry *e;
1049         struct ebt_u_entries *entries;
1050 };
1051
1052 /* Checks for loops
1053  * As a by-product, the hook_mask member of each chain is filled in
1054  * correctly. The check functions of the extensions need this hook_mask
1055  * to know from which standard chains they can be called. */
1056 void ebt_check_for_loops(struct ebt_u_replace *replace)
1057 {
1058         int chain_nr , i, j , k, sp = 0, verdict;
1059         struct ebt_u_entries *entries, *entries2;
1060         struct ebt_u_stack *stack = NULL;
1061         struct ebt_u_entry *e;
1062
1063         /* Initialize hook_mask to 0 */
1064         for (i = 0; i < replace->num_chains; i++) {
1065                 if (!(entries = replace->chains[i]))
1066                         continue;
1067                 if (i < NF_BR_NUMHOOKS)
1068                         /* (1 << NF_BR_NUMHOOKS) implies it's a standard chain
1069                          * (usefull in the final_check() funtions) */
1070                         entries->hook_mask = (1 << i) | (1 << NF_BR_NUMHOOKS);
1071                 else
1072                         entries->hook_mask = 0;
1073         }
1074         if (replace->num_chains == NF_BR_NUMHOOKS)
1075                 return;
1076         stack = (struct ebt_u_stack *)malloc((replace->num_chains - NF_BR_NUMHOOKS) * sizeof(struct ebt_u_stack));
1077         if (!stack)
1078                 ebt_print_memory();
1079
1080         /* Check for loops, starting from every base chain */
1081         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
1082                 if (!(entries = replace->chains[i]))
1083                         continue;
1084                 chain_nr = i;
1085
1086                 e = entries->entries->next;
1087                 for (j = 0; j < entries->nentries; j++) {
1088                         if (strcmp(e->t->u.name, EBT_STANDARD_TARGET))
1089                                 goto letscontinue;
1090                         verdict = ((struct ebt_standard_target *)(e->t))->verdict;
1091                         if (verdict < 0)
1092                                 goto letscontinue;
1093                         /* Now see if we've been here before */
1094                         for (k = 0; k < sp; k++)
1095                                 if (stack[k].chain_nr == verdict + NF_BR_NUMHOOKS) {
1096                                         ebt_print_error("Loop from chain '%s' to chain '%s'",
1097                                            replace->chains[chain_nr]->name,
1098                                            replace->chains[stack[k].chain_nr]->name);
1099                                         goto free_stack;
1100                                 }
1101                         entries2 = replace->chains[verdict + NF_BR_NUMHOOKS];
1102                         /* check if we've dealt with this chain already */
1103                         if (entries2->hook_mask & (1<<i))
1104                                 goto letscontinue;
1105                         entries2->hook_mask |= entries->hook_mask;
1106                         /* Jump to the chain, make sure we know how to get back */
1107                         stack[sp].chain_nr = chain_nr;
1108                         stack[sp].n = j;
1109                         stack[sp].entries = entries;
1110                         stack[sp].e = e;
1111                         sp++;
1112                         j = -1;
1113                         e = entries2->entries->next;
1114                         chain_nr = verdict + NF_BR_NUMHOOKS;
1115                         entries = entries2;
1116                         continue;
1117 letscontinue:
1118                         e = e->next;
1119                 }
1120                 /* We are at the end of a standard chain */
1121                 if (sp == 0)
1122                         continue;
1123                 /* Go back to the chain one level higher */
1124                 sp--;
1125                 j = stack[sp].n;
1126                 chain_nr = stack[sp].chain_nr;
1127                 e = stack[sp].e;
1128                 entries = stack[sp].entries;
1129                 goto letscontinue;
1130         }
1131 free_stack:
1132         free(stack);
1133         return;
1134 }
1135
1136 /* The user will use the match, so put it in new_entry. The ebt_u_match
1137  * pointer is put in the ebt_entry_match pointer. ebt_add_rule will
1138  * fill in the final value for new->m. Unless the rule is added to a chain,
1139  * the pointer will keep pointing to the ebt_u_match (until the new_entry
1140  * is freed). I know, I should use a union for these 2 pointer types... */
1141 void ebt_add_match(struct ebt_u_entry *new_entry, struct ebt_u_match *m)
1142 {
1143         struct ebt_u_match_list **m_list, *new;
1144
1145         for (m_list = &new_entry->m_list; *m_list; m_list = &(*m_list)->next);
1146         new = (struct ebt_u_match_list *)
1147            malloc(sizeof(struct ebt_u_match_list));
1148         if (!new)
1149                 ebt_print_memory();
1150         *m_list = new;
1151         new->next = NULL;
1152         new->m = (struct ebt_entry_match *)m;
1153 }
1154
1155 void ebt_add_watcher(struct ebt_u_entry *new_entry, struct ebt_u_watcher *w)
1156 {
1157         struct ebt_u_watcher_list **w_list;
1158         struct ebt_u_watcher_list *new;
1159
1160         for (w_list = &new_entry->w_list; *w_list; w_list = &(*w_list)->next);
1161         new = (struct ebt_u_watcher_list *)
1162            malloc(sizeof(struct ebt_u_watcher_list));
1163         if (!new)
1164                 ebt_print_memory();
1165         *w_list = new;
1166         new->next = NULL;
1167         new->w = (struct ebt_entry_watcher *)w;
1168 }
1169
1170
1171         /*
1172 *******************
1173 *******************
1174 **OTHER*FUNCTIONS**
1175 *******************
1176 *******************
1177          */
1178
1179
1180 /* type = 0 => update chain jumps
1181  * type = 1 => check for reference, print error when referenced
1182  * type = 2 => check for reference, don't print error when referenced
1183  *
1184  * Returns 1 when type == 1 and the chain is referenced
1185  * returns 0 otherwise */
1186 static int iterate_entries(struct ebt_u_replace *replace, int type)
1187 {
1188         int i, j, chain_nr = replace->selected_chain - NF_BR_NUMHOOKS;
1189         struct ebt_u_entries *entries;
1190         struct ebt_u_entry *e;
1191
1192         if (chain_nr < 0)
1193                 ebt_print_bug("iterate_entries: udc = %d < 0", chain_nr);
1194         for (i = 0; i < replace->num_chains; i++) {
1195                 if (!(entries = replace->chains[i]))
1196                         continue;
1197                 e = entries->entries->next;
1198                 for (j = 0; j < entries->nentries; j++) {
1199                         int chain_jmp;
1200
1201                         if (strcmp(e->t->u.name, EBT_STANDARD_TARGET)) {
1202                                 e = e->next;
1203                                 continue;
1204                         }
1205                         chain_jmp = ((struct ebt_standard_target *)e->t)->
1206                                     verdict;
1207                         switch (type) {
1208                         case 1:
1209                         case 2:
1210                         if (chain_jmp == chain_nr) {
1211                                 if (type == 2)
1212                                         return 1;
1213                                 ebt_print_error("Can't delete the chain '%s', it's referenced in chain '%s', rule %d",
1214                                                 replace->chains[chain_nr + NF_BR_NUMHOOKS]->name, entries->name, j);
1215                                 return 1;
1216                         }
1217                         break;
1218                         case 0:
1219                         /* Adjust the chain jumps when necessary */
1220                         if (chain_jmp > chain_nr)
1221                                 ((struct ebt_standard_target *)e->t)->verdict--;
1222                         break;
1223                         } /* End switch */
1224                         e = e->next;
1225                 }
1226         }
1227         return 0;
1228 }
1229
1230 static void decrease_chain_jumps(struct ebt_u_replace *replace)
1231 {
1232         iterate_entries(replace, 0);
1233 }
1234
1235 /* Used in initialization code of modules */
1236 void ebt_register_match(struct ebt_u_match *m)
1237 {
1238         int size = EBT_ALIGN(m->size) + sizeof(struct ebt_entry_match);
1239         struct ebt_u_match **i;
1240
1241         m->m = (struct ebt_entry_match *)malloc(size);
1242         if (!m->m)
1243                 ebt_print_memory();
1244         strcpy(m->m->u.name, m->name);
1245         m->m->match_size = EBT_ALIGN(m->size);
1246         m->init(m->m);
1247
1248         for (i = &ebt_matches; *i; i = &((*i)->next));
1249         m->next = NULL;
1250         *i = m;
1251 }
1252
1253 void ebt_register_watcher(struct ebt_u_watcher *w)
1254 {
1255         int size = EBT_ALIGN(w->size) + sizeof(struct ebt_entry_watcher);
1256         struct ebt_u_watcher **i;
1257
1258         w->w = (struct ebt_entry_watcher *)malloc(size);
1259         if (!w->w)
1260                 ebt_print_memory();
1261         strcpy(w->w->u.name, w->name);
1262         w->w->watcher_size = EBT_ALIGN(w->size);
1263         w->init(w->w);
1264
1265         for (i = &ebt_watchers; *i; i = &((*i)->next));
1266         w->next = NULL;
1267         *i = w;
1268 }
1269
1270 void ebt_register_target(struct ebt_u_target *t)
1271 {
1272         int size = EBT_ALIGN(t->size) + sizeof(struct ebt_entry_target);
1273         struct ebt_u_target **i;
1274
1275         t->t = (struct ebt_entry_target *)malloc(size);
1276         if (!t->t)
1277                 ebt_print_memory();
1278         strcpy(t->t->u.name, t->name);
1279         t->t->target_size = EBT_ALIGN(t->size);
1280         t->init(t->t);
1281
1282         for (i = &ebt_targets; *i; i = &((*i)->next));
1283         t->next = NULL;
1284         *i = t;
1285 }
1286
1287 void ebt_register_table(struct ebt_u_table *t)
1288 {
1289         t->next = ebt_tables;
1290         ebt_tables = t;
1291 }
1292
1293 void ebt_iterate_matches(void (*f)(struct ebt_u_match *))
1294 {
1295         struct ebt_u_match *i;
1296
1297         for (i = ebt_matches; i; i = i->next)
1298                 f(i);
1299 }
1300
1301 void ebt_iterate_watchers(void (*f)(struct ebt_u_watcher *))
1302 {
1303         struct ebt_u_watcher *i;
1304
1305         for (i = ebt_watchers; i; i = i->next)
1306                 f(i);
1307 }
1308
1309 void ebt_iterate_targets(void (*f)(struct ebt_u_target *))
1310 {
1311         struct ebt_u_target *i;
1312
1313         for (i = ebt_targets; i; i = i->next)
1314                 f(i);
1315 }
1316
1317 /* Don't use this function, use ebt_print_bug() */
1318 void __ebt_print_bug(char *file, int line, char *format, ...)
1319 {
1320         va_list l;
1321
1322         va_start(l, format);
1323         fprintf(stderr, PROGNAME" v"PROGVERSION":%s:%d:--BUG--: \n", file, line);
1324         vfprintf(stderr, format, l);
1325         fprintf(stderr, "\n");
1326         va_end(l);
1327         exit (-1);
1328 }
1329
1330 /* The error messages are put in here when ebt_silent == 1
1331  * ebt_errormsg[0] == '\0' implies there was no error */
1332 char ebt_errormsg[ERRORMSG_MAXLEN];
1333 /* When error messages should not be printed on the screen, after which
1334  * the program exit()s, set ebt_silent to 1. */
1335 int ebt_silent;
1336 /* Don't use this function, use ebt_print_error() */
1337 void __ebt_print_error(char *format, ...)
1338 {
1339         va_list l;
1340
1341         va_start(l, format);
1342         if (ebt_silent && ebt_errormsg[0] == '\0') {
1343                 vsnprintf(ebt_errormsg, ERRORMSG_MAXLEN, format, l);
1344                 va_end(l);
1345         } else {
1346                 vfprintf(stderr, format, l);
1347                 fprintf(stderr, ".\n");
1348                 va_end(l);
1349                 exit (-1);
1350         }
1351 }