iptables: Reinitialize global parser table
[platform/upstream/connman.git] / src / iptables.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2012  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <getopt.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/errno.h>
32 #include <sys/socket.h>
33 #include <xtables.h>
34
35 #include <linux/netfilter_ipv4/ip_tables.h>
36
37 #include "connman.h"
38
39 void flush_table(const char *name);
40
41 /*
42  * Some comments on how the iptables API works (some of them from the
43  * source code from iptables and the kernel):
44  *
45  * - valid_hooks: bit indicates valid IDs for hook_entry
46  * - hook_entry[ID] offset to the chain start
47  * - overflows should be end of entry chains, and uncodintional policy nodes.
48  * - policy entry: last entry in a chain
49  * - user chain: end of last builtin + policy entry
50  * - final entry must be error node
51  * - Underflows must be unconditional and use the STANDARD target with
52  *   ACCEPT/DROP
53  * - IPT_SO_GET_INFO and IPT_SO_GET_ENTRIES are used to read a table
54  * - IPT_SO_GET_INFO: struct ipt_getinfo (note the lack of table content)
55  * - IPT_SO_GET_ENTRIES: struct ipt_get_entries (contains only parts of the
56  *   table header/meta info. The table is appended after the header. The entries
57  *   are of the type struct ipt_entry.
58  * - After the ipt_entry the matches are appended. After the matches
59  *   the target is appended.
60  * - ipt_entry->target_offset =  Size of ipt_entry + matches
61  * - ipt_entry->next_offset =  Size of ipt_entry + matches + target
62  * - IPT_SO_SET_REPLACE is used to write a table (contains the complete
63  * - hook_entry and overflow mark the begining and the end of a chain, e.g
64  *     entry hook: pre/in/fwd/out/post -1/0/352/504/-1
65  *     underflow:  pre/in/fwd/out/post -1/200/352/904/-1
66  *   means that INPUT starts at offset 0 and ends at 200 (the start offset to
67  *   the last element). FORWARD has one entry starting/ending at 352. The entry
68  *   has a size of 152. 352 + 152 = 504 which is the start of the OUTPUT chain
69  *   which then ends at 904. PREROUTING and POSTROUTING are invalid hooks in
70  *   the filter table.
71  * - 'iptables -t filter -A INPUT -m mark --mark 999 -j LOG'
72  *   writing that table looks like this:
73  *
74  *   filter valid_hooks 0x0000000e  num_entries 5  size 856
75  *   entry hook: pre/in/fwd/out/post -1/0/376/528/-1
76  *   underflow:  pre/in/fwd/out/post -1/224/376/528/-1
77  *   entry 0x699d30  offset 0  size 224
78  *     RULE  match 0x699da0  target 0x699dd0
79  *             match  mark match 0x3e7
80  *             target  LOG flags 0 level 4
81  *             src 0.0.0.0/0.0.0.0
82  *             dst 0.0.0.0/0.0.0.0
83  *   entry 0x699e10  offset 224  size 152
84  *     RULE  match 0x699e80  target 0x699e80
85  *             target ACCEPT
86  *             src 0.0.0.0/0.0.0.0
87  *             dst 0.0.0.0/0.0.0.0
88  *   entry 0x699ea8  offset 376  size 152
89  *     RULE  match 0x699f18  target 0x699f18
90  *             target ACCEPT
91  *             src 0.0.0.0/0.0.0.0
92  *             dst 0.0.0.0/0.0.0.0
93  *   entry 0x699f40  offset 528  size 152
94  *     RULE  match 0x699fb0  target 0x699fb0
95  *             target ACCEPT
96  *             src 0.0.0.0/0.0.0.0
97  *             dst 0.0.0.0/0.0.0.0
98  *   entry 0x699fd8  offset 680  size 176
99  *     USER CHAIN (ERROR)  match 0x69a048  target 0x69a048
100  *
101  *   Reading the filter table looks like this:
102  *
103  *   filter valid_hooks 0x0000000e  num_entries 5  size 856
104  *   entry hook: pre/in/fwd/out/post -1/0/376/528/-1
105  *   underflow:  pre/in/fwd/out/post -1/224/376/528/-1
106  *   entry 0x25fec28  offset 0  size 224
107  *     CHAIN (INPUT)  match 0x25fec98  target 0x25fecc8
108  *             match  mark match 0x3e7
109  *             target  LOG flags 0 level 4
110  *             src 0.0.0.0/0.0.0.0
111  *             dst 0.0.0.0/0.0.0.0
112  *   entry 0x25fed08  offset 224  size 152
113  *     RULE  match 0x25fed78  target 0x25fed78
114  *             target ACCEPT
115  *             src 0.0.0.0/0.0.0.0
116  *             dst 0.0.0.0/0.0.0.0
117  *   entry 0x25feda0  offset 376  size 152
118  *     CHAIN (FORWARD)  match 0x25fee10  target 0x25fee10
119  *             target ACCEPT
120  *             src 0.0.0.0/0.0.0.0
121  *             dst 0.0.0.0/0.0.0.0
122  *   entry 0x25fee38  offset 528  size 152
123  *     CHAIN (OUTPUT)  match 0x25feea8  target 0x25feea8
124  *             target ACCEPT
125  *             src 0.0.0.0/0.0.0.0
126  *             dst 0.0.0.0/0.0.0.0
127  *   entry 0x25feed0  offset 680  size 176
128  *     End of CHAIN
129  */
130
131 static const char *hooknames[] = {
132         [NF_IP_PRE_ROUTING]     = "PREROUTING",
133         [NF_IP_LOCAL_IN]        = "INPUT",
134         [NF_IP_FORWARD]         = "FORWARD",
135         [NF_IP_LOCAL_OUT]       = "OUTPUT",
136         [NF_IP_POST_ROUTING]    = "POSTROUTING",
137 };
138
139 #define LABEL_ACCEPT  "ACCEPT"
140 #define LABEL_DROP    "DROP"
141 #define LABEL_QUEUE   "QUEUE"
142 #define LABEL_RETURN  "RETURN"
143
144 #define XT_OPTION_OFFSET_SCALE 256
145
146 #define MIN_ALIGN (__alignof__(struct ipt_entry))
147
148 #define ALIGN(s) (((s) + ((MIN_ALIGN)-1)) & ~((MIN_ALIGN)-1))
149
150 struct error_target {
151         struct xt_entry_target t;
152         char error[IPT_TABLE_MAXNAMELEN];
153 };
154
155 struct connman_iptables_entry {
156         int offset;
157         int builtin;
158
159         struct ipt_entry *entry;
160 };
161
162 struct connman_iptables {
163         int ipt_sock;
164
165         struct ipt_getinfo *info;
166         struct ipt_get_entries *blob_entries;
167
168         unsigned int num_entries;
169         unsigned int old_entries;
170         unsigned int size;
171
172         unsigned int underflow[NF_INET_NUMHOOKS];
173         unsigned int hook_entry[NF_INET_NUMHOOKS];
174
175         GList *entries;
176 };
177
178 static GHashTable *table_hash = NULL;
179 static gboolean debug_enabled = FALSE;
180
181 typedef int (*iterate_entries_cb_t)(struct ipt_entry *entry, int builtin,
182                                         unsigned int hook,size_t size,
183                                         unsigned int offset, void *user_data);
184
185 static int iterate_entries(struct ipt_entry *entries,
186                                 unsigned int valid_hooks,
187                                 unsigned int *hook_entry,
188                                 size_t size, iterate_entries_cb_t cb,
189                                 void *user_data)
190 {
191         unsigned int i, h;
192         int builtin, err;
193         struct ipt_entry *entry;
194
195         if (valid_hooks != 0)
196                 h = __builtin_ffs(valid_hooks) - 1;
197         else
198                 h = NF_INET_NUMHOOKS;
199
200         for (i = 0, entry = entries; i < size;
201                         i += entry->next_offset) {
202                 builtin = -1;
203                 entry = (void *)entries + i;
204
205                 /*
206                  * Find next valid hook which offset is higher
207                  * or equal with the current offset.
208                  */
209                 if (h < NF_INET_NUMHOOKS) {
210                         if (hook_entry[h] < i) {
211                                 valid_hooks ^= (1 << h);
212
213                                 if (valid_hooks != 0)
214                                         h = __builtin_ffs(valid_hooks) - 1;
215                                 else
216                                         h = NF_INET_NUMHOOKS;
217                         }
218
219                         if (hook_entry[h] == i)
220                                 builtin = h;
221                 }
222
223                 err = cb(entry, builtin, h, size, i, user_data);
224                 if (err < 0)
225                         return err;
226
227         }
228
229         return 0;
230 }
231
232 static int print_entry(struct ipt_entry *entry, int builtin, unsigned int hook,
233                                         size_t size, unsigned int offset,
234                                         void *user_data)
235 {
236         iterate_entries_cb_t cb = user_data;
237
238         DBG("entry %p  hook %d  offset %d  size %d", entry, hook,
239                         offset, entry->next_offset);
240
241         return cb(entry, builtin, hook, size, offset, NULL);
242 }
243
244 static int target_to_verdict(const char *target_name)
245 {
246         if (!strcmp(target_name, LABEL_ACCEPT))
247                 return -NF_ACCEPT - 1;
248
249         if (!strcmp(target_name, LABEL_DROP))
250                 return -NF_DROP - 1;
251
252         if (!strcmp(target_name, LABEL_QUEUE))
253                 return -NF_QUEUE - 1;
254
255         if (!strcmp(target_name, LABEL_RETURN))
256                 return XT_RETURN;
257
258         return 0;
259 }
260
261 static gboolean is_builtin_target(const char *target_name)
262 {
263         if (!strcmp(target_name, LABEL_ACCEPT) ||
264                 !strcmp(target_name, LABEL_DROP) ||
265                 !strcmp(target_name, LABEL_QUEUE) ||
266                 !strcmp(target_name, LABEL_RETURN))
267                 return TRUE;
268
269         return FALSE;
270 }
271
272 static gboolean is_jump(struct connman_iptables_entry *e)
273 {
274         struct xt_entry_target *target;
275
276         target = ipt_get_target(e->entry);
277
278         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
279                 struct xt_standard_target *t;
280
281                 t = (struct xt_standard_target *)target;
282
283                 switch (t->verdict) {
284                 case XT_RETURN:
285                 case -NF_ACCEPT - 1:
286                 case -NF_DROP - 1:
287                 case -NF_QUEUE - 1:
288                 case -NF_STOP - 1:
289                         return false;
290
291                 default:
292                         return true;
293                 }
294         }
295
296         return false;
297 }
298
299 static gboolean is_fallthrough(struct connman_iptables_entry *e)
300 {
301         struct xt_entry_target *target;
302
303         target = ipt_get_target(e->entry);
304         if (!strcmp(target->u.user.name, ""))
305                 return true;
306
307         return false;
308 }
309
310 static gboolean is_chain(struct connman_iptables *table,
311                                 struct connman_iptables_entry *e)
312 {
313         struct ipt_entry *entry;
314         struct xt_entry_target *target;
315
316         entry = e->entry;
317         if (e->builtin >= 0)
318                 return TRUE;
319
320         target = ipt_get_target(entry);
321         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
322                 return TRUE;
323
324         return FALSE;
325 }
326
327 static GList *find_chain_head(struct connman_iptables *table,
328                                 const char *chain_name)
329 {
330         GList *list;
331         struct connman_iptables_entry *head;
332         struct ipt_entry *entry;
333         struct xt_entry_target *target;
334         int builtin;
335
336         for (list = table->entries; list; list = list->next) {
337                 head = list->data;
338                 entry = head->entry;
339
340                 /* Buit-in chain */
341                 builtin = head->builtin;
342                 if (builtin >= 0 && !strcmp(hooknames[builtin], chain_name))
343                         break;
344
345                 /* User defined chain */
346                 target = ipt_get_target(entry);
347                 if (!strcmp(target->u.user.name, IPT_ERROR_TARGET) &&
348                     !strcmp((char *)target->data, chain_name))
349                         break;
350         }
351
352         return list;
353 }
354
355 static GList *find_chain_tail(struct connman_iptables *table,
356                                 const char *chain_name)
357 {
358         struct connman_iptables_entry *tail;
359         GList *chain_head, *list;
360
361         chain_head = find_chain_head(table, chain_name);
362         if (chain_head == NULL)
363                 return NULL;
364
365         /* Then we look for the next chain */
366         for (list = chain_head->next; list; list = list->next) {
367                 tail = list->data;
368
369                 if (is_chain(table, tail))
370                         return list;
371         }
372
373         /* Nothing found, we return the table end */
374         return g_list_last(table->entries);
375 }
376
377
378 static void update_offsets(struct connman_iptables *table)
379 {
380         GList *list, *prev;
381         struct connman_iptables_entry *entry, *prev_entry;
382
383         for (list = table->entries; list; list = list->next) {
384                 entry = list->data;
385
386                 if (list == table->entries) {
387                         entry->offset = 0;
388
389                         continue;
390                 }
391
392                 prev = list->prev;
393                 prev_entry = prev->data;
394
395                 entry->offset = prev_entry->offset +
396                                         prev_entry->entry->next_offset;
397         }
398 }
399
400 static void update_targets_reference(struct connman_iptables *table,
401                                 struct connman_iptables_entry *entry_before,
402                                 struct connman_iptables_entry *modified_entry,
403                                 gboolean is_removing)
404 {
405         struct connman_iptables_entry *tmp;
406         struct xt_standard_target *t;
407         GList *list;
408         int offset;
409
410         offset = modified_entry->entry->next_offset;
411
412         for (list = table->entries; list; list = list->next) {
413                 tmp = list->data;
414
415                 if (!is_jump(tmp))
416                         continue;
417
418                 t = (struct xt_standard_target *)ipt_get_target(tmp->entry);
419
420                 if (is_removing == TRUE) {
421                         if (t->verdict >= entry_before->offset)
422                                 t->verdict -= offset;
423                 } else {
424                         if (t->verdict > entry_before->offset)
425                                 t->verdict += offset;
426                 }
427         }
428
429         if (is_fallthrough(modified_entry)) {
430                 t = (struct xt_standard_target *) ipt_get_target(modified_entry->entry);
431
432                 t->verdict = entry_before->offset +
433                         modified_entry->entry->target_offset +
434                         ALIGN(sizeof(struct xt_standard_target));
435                 t->target.u.target_size =
436                         ALIGN(sizeof(struct xt_standard_target));
437         }
438 }
439
440 static int iptables_add_entry(struct connman_iptables *table,
441                                 struct ipt_entry *entry, GList *before,
442                                         int builtin)
443 {
444         struct connman_iptables_entry *e, *entry_before;
445
446         if (table == NULL)
447                 return -1;
448
449         e = g_try_malloc0(sizeof(struct connman_iptables_entry));
450         if (e == NULL)
451                 return -1;
452
453         e->entry = entry;
454         e->builtin = builtin;
455
456         table->entries = g_list_insert_before(table->entries, before, e);
457         table->num_entries++;
458         table->size += entry->next_offset;
459
460         if (before == NULL) {
461                 e->offset = table->size - entry->next_offset;
462
463                 return 0;
464         }
465
466         entry_before = before->data;
467
468         /*
469          * We've just appended/insterted a new entry. All references
470          * should be bumped accordingly.
471          */
472         update_targets_reference(table, entry_before, e, FALSE);
473
474         update_offsets(table);
475
476         return 0;
477 }
478
479 static int remove_table_entry(struct connman_iptables *table,
480                                 struct connman_iptables_entry *entry)
481 {
482         int removed = 0;
483
484         table->num_entries--;
485         table->size -= entry->entry->next_offset;
486         removed = entry->entry->next_offset;
487
488         table->entries = g_list_remove(table->entries, entry);
489
490         g_free(entry->entry);
491         g_free(entry);
492
493         return removed;
494 }
495
496 static int iptables_flush_chain(struct connman_iptables *table,
497                                                 const char *name)
498 {
499         GList *chain_head, *chain_tail, *list, *next;
500         struct connman_iptables_entry *entry;
501         int builtin, removed = 0;
502
503         chain_head = find_chain_head(table, name);
504         if (chain_head == NULL)
505                 return -EINVAL;
506
507         chain_tail = find_chain_tail(table, name);
508         if (chain_tail == NULL)
509                 return -EINVAL;
510
511         entry = chain_head->data;
512         builtin = entry->builtin;
513
514         if (builtin >= 0)
515                 list = chain_head;
516         else
517                 list = chain_head->next;
518
519         if (list == chain_tail->prev)
520                 return 0;
521
522         while (list != chain_tail->prev) {
523                 entry = list->data;
524                 next = g_list_next(list);
525
526                 removed += remove_table_entry(table, entry);
527
528                 list = next;
529         }
530
531         if (builtin >= 0) {
532                 struct connman_iptables_entry *e;
533
534                 entry = list->data;
535
536                 entry->builtin = builtin;
537
538                 table->underflow[builtin] -= removed;
539
540                 for (list = chain_tail; list; list = list->next) {
541                         e = list->data;
542
543                         builtin = e->builtin;
544                         if (builtin < 0)
545                                 continue;
546
547                         table->hook_entry[builtin] -= removed;
548                         table->underflow[builtin] -= removed;
549                 }
550         }
551
552         update_offsets(table);
553
554         return 0;
555 }
556
557 static int iptables_add_chain(struct connman_iptables *table,
558                                 const char *name)
559 {
560         GList *last;
561         struct ipt_entry *entry_head;
562         struct ipt_entry *entry_return;
563         struct error_target *error;
564         struct ipt_standard_target *standard;
565         u_int16_t entry_head_size, entry_return_size;
566
567         last = g_list_last(table->entries);
568
569         /*
570          * An empty chain is composed of:
571          * - A head entry, with no match and an error target.
572          *   The error target data is the chain name.
573          * - A tail entry, with no match and a standard target.
574          *   The standard target verdict is XT_RETURN (return to the
575          *   caller).
576          */
577
578         /* head entry */
579         entry_head_size = sizeof(struct ipt_entry) +
580                                 sizeof(struct error_target);
581         entry_head = g_try_malloc0(entry_head_size);
582         if (entry_head == NULL)
583                 goto err_head;
584
585         memset(entry_head, 0, entry_head_size);
586
587         entry_head->target_offset = sizeof(struct ipt_entry);
588         entry_head->next_offset = entry_head_size;
589
590         error = (struct error_target *) entry_head->elems;
591         strcpy(error->t.u.user.name, IPT_ERROR_TARGET);
592         error->t.u.user.target_size = ALIGN(sizeof(struct error_target));
593         strcpy(error->error, name);
594
595         if (iptables_add_entry(table, entry_head, last, -1) < 0)
596                 goto err_head;
597
598         /* tail entry */
599         entry_return_size = sizeof(struct ipt_entry) +
600                                 sizeof(struct ipt_standard_target);
601         entry_return = g_try_malloc0(entry_return_size);
602         if (entry_return == NULL)
603                 goto err;
604
605         memset(entry_return, 0, entry_return_size);
606
607         entry_return->target_offset = sizeof(struct ipt_entry);
608         entry_return->next_offset = entry_return_size;
609
610         standard = (struct ipt_standard_target *) entry_return->elems;
611         standard->target.u.user.target_size =
612                                 ALIGN(sizeof(struct ipt_standard_target));
613         standard->verdict = XT_RETURN;
614
615         if (iptables_add_entry(table, entry_return, last, -1) < 0)
616                 goto err;
617
618         return 0;
619
620 err:
621         g_free(entry_return);
622 err_head:
623         g_free(entry_head);
624
625         return -ENOMEM;
626 }
627
628 static int iptables_delete_chain(struct connman_iptables *table,
629                                         const char *name)
630 {
631         struct connman_iptables_entry *entry;
632         GList *chain_head, *chain_tail;
633
634         chain_head = find_chain_head(table, name);
635         if (chain_head == NULL)
636                 return -EINVAL;
637
638         entry = chain_head->data;
639
640         /* We cannot remove builtin chain */
641         if (entry->builtin >= 0)
642                 return -EINVAL;
643
644         chain_tail = find_chain_tail(table, name);
645         if (chain_tail == NULL)
646                 return -EINVAL;
647
648         /* Chain must be flushed */
649         if (chain_head->next != chain_tail->prev)
650                 return -EINVAL;
651
652         remove_table_entry(table, entry);
653
654         entry = chain_tail->prev->data;
655         remove_table_entry(table, entry);
656
657         update_offsets(table);
658
659         return 0;
660 }
661
662 static struct ipt_entry *new_rule(struct ipt_ip *ip,
663                 const char *target_name, struct xtables_target *xt_t,
664                 struct xtables_rule_match *xt_rm)
665 {
666         struct xtables_rule_match *tmp_xt_rm;
667         struct ipt_entry *new_entry;
668         size_t match_size, target_size;
669
670         match_size = 0;
671         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL; tmp_xt_rm = tmp_xt_rm->next)
672                 match_size += tmp_xt_rm->match->m->u.match_size;
673
674         if (xt_t)
675                 target_size = ALIGN(xt_t->t->u.target_size);
676         else
677                 target_size = ALIGN(sizeof(struct xt_standard_target));
678
679         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
680                                                                 match_size);
681         if (new_entry == NULL)
682                 return NULL;
683
684         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
685
686         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
687         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
688                                                                 match_size;
689
690         match_size = 0;
691         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
692                                 tmp_xt_rm = tmp_xt_rm->next) {
693                 memcpy(new_entry->elems + match_size, tmp_xt_rm->match->m,
694                                         tmp_xt_rm->match->m->u.match_size);
695                 match_size += tmp_xt_rm->match->m->u.match_size;
696         }
697
698         if (xt_t) {
699                 struct xt_entry_target *entry_target;
700
701                 entry_target = ipt_get_target(new_entry);
702                 memcpy(entry_target, xt_t->t, target_size);
703         }
704
705         return new_entry;
706 }
707
708 static void update_hooks(struct connman_iptables *table, GList *chain_head,
709                                 struct ipt_entry *entry)
710 {
711         GList *list;
712         struct connman_iptables_entry *head, *e;
713         int builtin;
714
715         if (chain_head == NULL)
716                 return;
717
718         head = chain_head->data;
719
720         builtin = head->builtin;
721         if (builtin < 0)
722                 return;
723
724         table->underflow[builtin] += entry->next_offset;
725
726         for (list = chain_head->next; list; list = list->next) {
727                 e = list->data;
728
729                 builtin = e->builtin;
730                 if (builtin < 0)
731                         continue;
732
733                 table->hook_entry[builtin] += entry->next_offset;
734                 table->underflow[builtin] += entry->next_offset;
735         }
736 }
737
738 static struct ipt_entry *prepare_rule_inclusion(struct connman_iptables *table,
739                                 struct ipt_ip *ip, const char *chain_name,
740                                 const char *target_name,
741                                 struct xtables_target *xt_t,
742                                 int *builtin, struct xtables_rule_match *xt_rm)
743 {
744         GList *chain_tail, *chain_head;
745         struct ipt_entry *new_entry;
746         struct connman_iptables_entry *head;
747
748         chain_head = find_chain_head(table, chain_name);
749         if (chain_head == NULL)
750                 return NULL;
751
752         chain_tail = find_chain_tail(table, chain_name);
753         if (chain_tail == NULL)
754                 return NULL;
755
756         new_entry = new_rule(ip, target_name, xt_t, xt_rm);
757         if (new_entry == NULL)
758                 return NULL;
759
760         update_hooks(table, chain_head, new_entry);
761
762         /*
763          * If the chain is builtin, and does not have any rule,
764          * then the one that we're inserting is becoming the head
765          * and thus needs the builtin flag.
766          */
767         head = chain_head->data;
768         if (head->builtin < 0)
769                 *builtin = -1;
770         else if (chain_head == chain_tail->prev) {
771                 *builtin = head->builtin;
772                 head->builtin = -1;
773         }
774
775         return new_entry;
776 }
777
778 static int iptables_insert_rule(struct connman_iptables *table,
779                                 struct ipt_ip *ip, const char *chain_name,
780                                 const char *target_name,
781                                 struct xtables_target *xt_t,
782                                 struct xtables_rule_match *xt_rm)
783 {
784         struct ipt_entry *new_entry;
785         int builtin = -1, ret;
786         GList *chain_head;
787
788         chain_head = find_chain_head(table, chain_name);
789         if (chain_head == NULL)
790                 return -EINVAL;
791
792         new_entry = prepare_rule_inclusion(table, ip, chain_name,
793                                         target_name, xt_t, &builtin, xt_rm);
794         if (new_entry == NULL)
795                 return -EINVAL;
796
797         if (builtin == -1)
798                 chain_head = chain_head->next;
799
800         ret = iptables_add_entry(table, new_entry, chain_head, builtin);
801         if (ret < 0)
802                 g_free(new_entry);
803
804         return ret;
805 }
806
807 static gboolean is_same_ipt_entry(struct ipt_entry *i_e1,
808                                         struct ipt_entry *i_e2)
809 {
810         if (memcmp(&i_e1->ip, &i_e2->ip, sizeof(struct ipt_ip)) != 0)
811                 return FALSE;
812
813         if (i_e1->target_offset != i_e2->target_offset)
814                 return FALSE;
815
816         if (i_e1->next_offset != i_e2->next_offset)
817                 return FALSE;
818
819         return TRUE;
820 }
821
822 static gboolean is_same_target(struct xt_entry_target *xt_e_t1,
823                                         struct xt_entry_target *xt_e_t2)
824 {
825         unsigned int i;
826
827         if (xt_e_t1 == NULL || xt_e_t2 == NULL)
828                 return FALSE;
829
830         if (strcmp(xt_e_t1->u.user.name, "") == 0 &&
831                         strcmp(xt_e_t2->u.user.name, "") == 0) {
832                 /* fallthrough */
833                 return TRUE;
834         } else if (strcmp(xt_e_t1->u.user.name, IPT_STANDARD_TARGET) == 0) {
835                 struct xt_standard_target *xt_s_t1;
836                 struct xt_standard_target *xt_s_t2;
837
838                 xt_s_t1 = (struct xt_standard_target *) xt_e_t1;
839                 xt_s_t2 = (struct xt_standard_target *) xt_e_t2;
840
841                 if (xt_s_t1->verdict != xt_s_t2->verdict)
842                         return FALSE;
843         } else {
844                 if (xt_e_t1->u.target_size != xt_e_t2->u.target_size)
845                         return FALSE;
846
847                 if (strcmp(xt_e_t1->u.user.name, xt_e_t2->u.user.name) != 0)
848                         return FALSE;
849
850                 for (i = 0; i < xt_e_t1->u.target_size -
851                                 sizeof(struct xt_standard_target); i++) {
852                         if ((xt_e_t1->data[i] ^ xt_e_t2->data[i]) != 0)
853                                 return FALSE;
854                 }
855         }
856
857         return TRUE;
858 }
859
860 static gboolean is_same_match(struct xt_entry_match *xt_e_m1,
861                                 struct xt_entry_match *xt_e_m2)
862 {
863         unsigned int i;
864
865         if (xt_e_m1 == NULL || xt_e_m2 == NULL)
866                 return FALSE;
867
868         if (xt_e_m1->u.match_size != xt_e_m2->u.match_size)
869                 return FALSE;
870
871         if (xt_e_m1->u.user.revision != xt_e_m2->u.user.revision)
872                 return FALSE;
873
874         if (strcmp(xt_e_m1->u.user.name, xt_e_m2->u.user.name) != 0)
875                 return FALSE;
876
877         for (i = 0; i < xt_e_m1->u.match_size - sizeof(struct xt_entry_match);
878                         i++) {
879                 if ((xt_e_m1->data[i] ^ xt_e_m2->data[i]) != 0)
880                         return FALSE;
881         }
882
883         return TRUE;
884 }
885
886 static GList *find_existing_rule(struct connman_iptables *table,
887                                 struct ipt_ip *ip, const char *chain_name,
888                                 const char *target_name,
889                                 struct xtables_target *xt_t,
890                                 struct xtables_match *xt_m,
891                                 struct xtables_rule_match *xt_rm)
892 {
893         GList *chain_tail, *chain_head, *list;
894         struct xt_entry_target *xt_e_t = NULL;
895         struct xt_entry_match *xt_e_m = NULL;
896         struct connman_iptables_entry *entry;
897         struct ipt_entry *entry_test;
898         int builtin;
899
900         chain_head = find_chain_head(table, chain_name);
901         if (chain_head == NULL)
902                 return NULL;
903
904         chain_tail = find_chain_tail(table, chain_name);
905         if (chain_tail == NULL)
906                 return NULL;
907
908         if (!xt_t && !xt_m)
909                 return NULL;
910
911         entry_test = new_rule(ip, target_name, xt_t, xt_rm);
912         if (entry_test == NULL)
913                 return NULL;
914
915         if (xt_t != NULL)
916                 xt_e_t = ipt_get_target(entry_test);
917         if (xt_m != NULL)
918                 xt_e_m = (struct xt_entry_match *)entry_test->elems;
919
920         entry = chain_head->data;
921         builtin = entry->builtin;
922
923         if (builtin >= 0)
924                 list = chain_head;
925         else
926                 list = chain_head->next;
927
928         for (; list != chain_tail->prev; list = list->next) {
929                 struct connman_iptables_entry *tmp;
930                 struct ipt_entry *tmp_e;
931
932                 tmp = list->data;
933                 tmp_e = tmp->entry;
934
935                 if (is_same_ipt_entry(entry_test, tmp_e) == FALSE)
936                         continue;
937
938                 if (xt_t != NULL) {
939                         struct xt_entry_target *tmp_xt_e_t;
940
941                         tmp_xt_e_t = ipt_get_target(tmp_e);
942
943                         if (!is_same_target(tmp_xt_e_t, xt_e_t))
944                                 continue;
945                 }
946
947                 if (xt_m != NULL) {
948                         struct xt_entry_match *tmp_xt_e_m;
949
950                         tmp_xt_e_m = (struct xt_entry_match *)tmp_e->elems;
951
952                         if (!is_same_match(tmp_xt_e_m, xt_e_m))
953                                 continue;
954                 }
955
956                 break;
957         }
958
959         g_free(entry_test);
960
961         if (list != chain_tail->prev)
962                 return list;
963
964         return NULL;
965 }
966
967 static int iptables_delete_rule(struct connman_iptables *table,
968                                 struct ipt_ip *ip, const char *chain_name,
969                                 const char *target_name,
970                                 struct xtables_target *xt_t,
971                                 struct xtables_match *xt_m,
972                                 struct xtables_rule_match *xt_rm)
973 {
974         struct connman_iptables_entry *entry;
975         GList *chain_head, *chain_tail, *list;
976         int builtin, removed;
977
978         removed = 0;
979
980         chain_head = find_chain_head(table, chain_name);
981         if (chain_head == NULL)
982                 return -EINVAL;
983
984         chain_tail = find_chain_tail(table, chain_name);
985         if (chain_tail == NULL)
986                 return -EINVAL;
987
988         list = find_existing_rule(table, ip, chain_name, target_name,
989                                                         xt_t, xt_m, xt_rm);
990         if (list == NULL)
991                 return -EINVAL;
992
993         entry = chain_head->data;
994         builtin = entry->builtin;
995
996         entry = list->data;
997         if (entry == NULL)
998                 return -EINVAL;
999
1000         /* We have deleted a rule,
1001          * all references should be bumped accordingly */
1002         if (list->next != NULL)
1003                 update_targets_reference(table, list->next->data,
1004                                                 list->data, TRUE);
1005
1006         removed += remove_table_entry(table, entry);
1007
1008         if (builtin >= 0) {
1009                 list = list->next;
1010                 if (list) {
1011                         entry = list->data;
1012                         entry->builtin = builtin;
1013                 }
1014
1015                 table->underflow[builtin] -= removed;
1016                 for (list = chain_tail; list; list = list->next) {
1017                         entry = list->data;
1018
1019                         builtin = entry->builtin;
1020                         if (builtin < 0)
1021                                 continue;
1022
1023                         table->hook_entry[builtin] -= removed;
1024                         table->underflow[builtin] -= removed;
1025                 }
1026         }
1027
1028         update_offsets(table);
1029
1030         return 0;
1031 }
1032
1033 static int iptables_change_policy(struct connman_iptables *table,
1034                                 const char *chain_name, const char *policy)
1035 {
1036         GList *chain_head;
1037         struct connman_iptables_entry *entry;
1038         struct xt_entry_target *target;
1039         struct xt_standard_target *t;
1040         int verdict;
1041
1042         verdict = target_to_verdict(policy);
1043         if (verdict == 0)
1044                 return -EINVAL;
1045
1046         chain_head = find_chain_head(table, chain_name);
1047         if (chain_head == NULL)
1048                 return -EINVAL;
1049
1050         entry = chain_head->data;
1051         if (entry->builtin < 0)
1052                 return -EINVAL;
1053
1054         target = ipt_get_target(entry->entry);
1055
1056         t = (struct xt_standard_target *)target;
1057         t->verdict = verdict;
1058
1059         return 0;
1060 }
1061
1062 static struct ipt_replace *iptables_blob(struct connman_iptables *table)
1063 {
1064         struct ipt_replace *r;
1065         GList *list;
1066         struct connman_iptables_entry *e;
1067         unsigned char *entry_index;
1068
1069         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
1070         if (r == NULL)
1071                 return NULL;
1072
1073         memset(r, 0, sizeof(*r) + table->size);
1074
1075         r->counters = g_try_malloc0(sizeof(struct xt_counters)
1076                                 * table->old_entries);
1077         if (r->counters == NULL) {
1078                 g_free(r);
1079                 return NULL;
1080         }
1081
1082         strcpy(r->name, table->info->name);
1083         r->num_entries = table->num_entries;
1084         r->size = table->size;
1085
1086         r->num_counters = table->old_entries;
1087         r->valid_hooks  = table->info->valid_hooks;
1088
1089         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
1090         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
1091
1092         entry_index = (unsigned char *)r->entries;
1093         for (list = table->entries; list; list = list->next) {
1094                 e = list->data;
1095
1096                 memcpy(entry_index, e->entry, e->entry->next_offset);
1097                 entry_index += e->entry->next_offset;
1098         }
1099
1100         return r;
1101 }
1102
1103 static void dump_ip(struct ipt_entry *entry)
1104 {
1105         struct ipt_ip *ip = &entry->ip;
1106         char ip_string[INET6_ADDRSTRLEN];
1107         char ip_mask[INET6_ADDRSTRLEN];
1108
1109         if (strlen(ip->iniface))
1110                 DBG("\tin %s", ip->iniface);
1111
1112         if (strlen(ip->outiface))
1113                 DBG("\tout %s", ip->outiface);
1114
1115         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
1116                         inet_ntop(AF_INET, &ip->smsk,
1117                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1118                 DBG("\tsrc %s/%s", ip_string, ip_mask);
1119
1120         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
1121                         inet_ntop(AF_INET, &ip->dmsk,
1122                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1123                 DBG("\tdst %s/%s", ip_string, ip_mask);
1124 }
1125
1126 static void dump_target(struct ipt_entry *entry)
1127
1128 {
1129         struct xtables_target *xt_t;
1130         struct xt_entry_target *target;
1131
1132         target = ipt_get_target(entry);
1133
1134         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
1135                 struct xt_standard_target *t;
1136
1137                 t = (struct xt_standard_target *)target;
1138
1139                 switch (t->verdict) {
1140                 case XT_RETURN:
1141                         DBG("\ttarget RETURN");
1142                         break;
1143
1144                 case -NF_ACCEPT - 1:
1145                         DBG("\ttarget ACCEPT");
1146                         break;
1147
1148                 case -NF_DROP - 1:
1149                         DBG("\ttarget DROP");
1150                         break;
1151
1152                 case -NF_QUEUE - 1:
1153                         DBG("\ttarget QUEUE");
1154                         break;
1155
1156                 case -NF_STOP - 1:
1157                         DBG("\ttarget STOP");
1158                         break;
1159
1160                 default:
1161                         DBG("\tJUMP %u", t->verdict);
1162                         break;
1163                 }
1164
1165                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1166                                                 XTF_LOAD_MUST_SUCCEED);
1167
1168                 if(xt_t->print != NULL)
1169                         xt_t->print(NULL, target, 1);
1170         } else {
1171                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
1172                 if (xt_t == NULL) {
1173                         DBG("\ttarget %s", target->u.user.name);
1174                         return;
1175                 }
1176
1177                 if(xt_t->print != NULL) {
1178                         DBG("\ttarget ");
1179                         xt_t->print(NULL, target, 1);
1180                 }
1181         }
1182 }
1183
1184 static void dump_match(struct ipt_entry *entry)
1185 {
1186         struct xtables_match *xt_m;
1187         struct xt_entry_match *match;
1188
1189         if (entry->elems == (unsigned char *)entry + entry->target_offset)
1190                 return;
1191
1192         match = (struct xt_entry_match *) entry->elems;
1193
1194         if (!strlen(match->u.user.name))
1195                 return;
1196
1197         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
1198         if (xt_m == NULL)
1199                 goto out;
1200
1201         if(xt_m->print != NULL) {
1202                 DBG("\tmatch ");
1203                 xt_m->print(NULL, match, 1);
1204
1205                 return;
1206         }
1207
1208 out:
1209         DBG("\tmatch %s", match->u.user.name);
1210
1211 }
1212
1213 static int dump_entry(struct ipt_entry *entry, int builtin,
1214                         unsigned int hook, size_t size, unsigned int offset,
1215                         void *user_data)
1216 {
1217         struct xt_entry_target *target;
1218
1219         target = ipt_get_target(entry);
1220
1221         if (offset + entry->next_offset == size) {
1222                 DBG("\tEnd of CHAIN");
1223                 return 0;
1224         }
1225
1226         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
1227                 DBG("\tUSER CHAIN (%s) match %p  target %p",
1228                         target->data, entry->elems,
1229                         (char *)entry + entry->target_offset);
1230
1231                 return 0;
1232         } else if (builtin >= 0) {
1233                 DBG("\tCHAIN (%s) match %p  target %p",
1234                         hooknames[builtin], entry->elems,
1235                         (char *)entry + entry->target_offset);
1236         } else {
1237                 DBG("\tRULE  match %p  target %p",
1238                         entry->elems,
1239                         (char *)entry + entry->target_offset);
1240         }
1241
1242         dump_match(entry);
1243         dump_target(entry);
1244         dump_ip(entry);
1245
1246         return 0;
1247 }
1248
1249 static void dump_table(struct connman_iptables *table)
1250 {
1251         DBG("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
1252                         table->info->name,
1253                         table->info->valid_hooks, table->info->num_entries,
1254                                 table->info->size);
1255
1256         DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
1257                 table->info->hook_entry[NF_IP_PRE_ROUTING],
1258                 table->info->hook_entry[NF_IP_LOCAL_IN],
1259                 table->info->hook_entry[NF_IP_FORWARD],
1260                 table->info->hook_entry[NF_IP_LOCAL_OUT],
1261                 table->info->hook_entry[NF_IP_POST_ROUTING]);
1262         DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
1263                 table->info->underflow[NF_IP_PRE_ROUTING],
1264                 table->info->underflow[NF_IP_LOCAL_IN],
1265                 table->info->underflow[NF_IP_FORWARD],
1266                 table->info->underflow[NF_IP_LOCAL_OUT],
1267                 table->info->underflow[NF_IP_POST_ROUTING]);
1268
1269         iterate_entries(table->blob_entries->entrytable,
1270                         table->info->valid_hooks,
1271                         table->info->hook_entry,
1272                         table->blob_entries->size,
1273                         print_entry, dump_entry);
1274 }
1275
1276 static void dump_ipt_replace(struct ipt_replace *repl)
1277 {
1278         DBG("%s valid_hooks 0x%08x  num_entries %u  size %u",
1279                         repl->name, repl->valid_hooks, repl->num_entries,
1280                         repl->size);
1281
1282         DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
1283                 repl->hook_entry[NF_IP_PRE_ROUTING],
1284                 repl->hook_entry[NF_IP_LOCAL_IN],
1285                 repl->hook_entry[NF_IP_FORWARD],
1286                 repl->hook_entry[NF_IP_LOCAL_OUT],
1287                 repl->hook_entry[NF_IP_POST_ROUTING]);
1288         DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
1289                 repl->underflow[NF_IP_PRE_ROUTING],
1290                 repl->underflow[NF_IP_LOCAL_IN],
1291                 repl->underflow[NF_IP_FORWARD],
1292                 repl->underflow[NF_IP_LOCAL_OUT],
1293                 repl->underflow[NF_IP_POST_ROUTING]);
1294
1295         iterate_entries(repl->entries, repl->valid_hooks,
1296                         repl->hook_entry, repl->size, print_entry, dump_entry);
1297 }
1298
1299 static int iptables_get_entries(struct connman_iptables *table)
1300 {
1301         socklen_t entry_size;
1302
1303         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
1304
1305         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
1306                                 table->blob_entries, &entry_size);
1307 }
1308
1309 static int iptables_replace(struct connman_iptables *table,
1310                                         struct ipt_replace *r)
1311 {
1312         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
1313                          sizeof(*r) + r->size);
1314 }
1315
1316 static int add_entry(struct ipt_entry *entry, int builtin, unsigned int hook,
1317                         size_t size, unsigned offset, void *user_data)
1318 {
1319         struct connman_iptables *table = user_data;
1320         struct ipt_entry *new_entry;
1321
1322         new_entry = g_try_malloc0(entry->next_offset);
1323         if (new_entry == NULL)
1324                 return -ENOMEM;
1325
1326         memcpy(new_entry, entry, entry->next_offset);
1327
1328         return iptables_add_entry(table, new_entry, NULL, builtin);
1329 }
1330
1331 static void table_cleanup(struct connman_iptables *table)
1332 {
1333         GList *list;
1334         struct connman_iptables_entry *entry;
1335
1336         if (table == NULL)
1337                 return;
1338
1339         if (table->ipt_sock >= 0)
1340                 close(table->ipt_sock);
1341
1342         for (list = table->entries; list; list = list->next) {
1343                 entry = list->data;
1344
1345                 g_free(entry->entry);
1346                 g_free(entry);
1347         }
1348
1349         g_list_free(table->entries);
1350         g_free(table->info);
1351         g_free(table->blob_entries);
1352         g_free(table);
1353 }
1354
1355 static struct connman_iptables *iptables_init(const char *table_name)
1356 {
1357         struct connman_iptables *table = NULL;
1358         char *module = NULL;
1359         socklen_t s;
1360
1361         if (table_name == NULL)
1362                 table_name = "filter";
1363
1364         DBG("%s", table_name);
1365
1366         if (xtables_insmod("ip_tables", NULL, TRUE) != 0)
1367                 DBG("ip_tables module loading gives error but trying anyway");
1368
1369         module = g_strconcat("iptable_", table_name, NULL);
1370         if (module == NULL)
1371                 return NULL;
1372
1373         if (xtables_insmod(module, NULL, TRUE) != 0)
1374                 DBG("%s module loading gives error but trying anyway", module);
1375
1376         g_free(module);
1377
1378         table = g_hash_table_lookup(table_hash, table_name);
1379         if (table != NULL)
1380                 return table;
1381
1382         table = g_try_new0(struct connman_iptables, 1);
1383         if (table == NULL)
1384                 return NULL;
1385
1386         table->info = g_try_new0(struct ipt_getinfo, 1);
1387         if (table->info == NULL)
1388                 goto err;
1389
1390         table->ipt_sock = socket(AF_INET, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_RAW);
1391         if (table->ipt_sock < 0)
1392                 goto err;
1393
1394         s = sizeof(*table->info);
1395         strcpy(table->info->name, table_name);
1396         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
1397                                                 table->info, &s) < 0) {
1398                 connman_error("iptables support missing error %d (%s)", errno,
1399                         strerror(errno));
1400                 goto err;
1401         }
1402
1403         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
1404                                                 table->info->size);
1405         if (table->blob_entries == NULL)
1406                 goto err;
1407
1408         strcpy(table->blob_entries->name, table_name);
1409         table->blob_entries->size = table->info->size;
1410
1411         if (iptables_get_entries(table) < 0)
1412                 goto err;
1413
1414         table->num_entries = 0;
1415         table->old_entries = table->info->num_entries;
1416         table->size = 0;
1417
1418         memcpy(table->underflow, table->info->underflow,
1419                                 sizeof(table->info->underflow));
1420         memcpy(table->hook_entry, table->info->hook_entry,
1421                                 sizeof(table->info->hook_entry));
1422
1423         iterate_entries(table->blob_entries->entrytable,
1424                         table->info->valid_hooks, table->info->hook_entry,
1425                         table->blob_entries->size, add_entry, table);
1426
1427         g_hash_table_insert(table_hash, g_strdup(table_name), table);
1428
1429         if (debug_enabled == TRUE)
1430                 dump_table(table);
1431
1432         return table;
1433
1434 err:
1435         table_cleanup(table);
1436
1437         return NULL;
1438 }
1439
1440 static struct option iptables_opts[] = {
1441         {.name = "append",        .has_arg = 1, .val = 'A'},
1442         {.name = "compare",       .has_arg = 1, .val = 'C'},
1443         {.name = "delete",        .has_arg = 1, .val = 'D'},
1444         {.name = "flush-chain",   .has_arg = 1, .val = 'F'},
1445         {.name = "insert",        .has_arg = 1, .val = 'I'},
1446         {.name = "list",          .has_arg = 2, .val = 'L'},
1447         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
1448         {.name = "policy",        .has_arg = 1, .val = 'P'},
1449         {.name = "delete-chain",  .has_arg = 1, .val = 'X'},
1450         {.name = "destination",   .has_arg = 1, .val = 'd'},
1451         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
1452         {.name = "jump",          .has_arg = 1, .val = 'j'},
1453         {.name = "match",         .has_arg = 1, .val = 'm'},
1454         {.name = "out-interface", .has_arg = 1, .val = 'o'},
1455         {.name = "source",        .has_arg = 1, .val = 's'},
1456         {.name = "table",         .has_arg = 1, .val = 't'},
1457         {NULL},
1458 };
1459
1460 struct xtables_globals iptables_globals = {
1461         .option_offset = 0,
1462         .opts = iptables_opts,
1463         .orig_opts = iptables_opts,
1464 };
1465
1466 static struct xtables_target *prepare_target(struct connman_iptables *table,
1467                                                         const char *target_name)
1468 {
1469         struct xtables_target *xt_t = NULL;
1470         gboolean is_builtin, is_user_defined;
1471         GList *chain_head = NULL;
1472         size_t target_size;
1473
1474         is_builtin = FALSE;
1475         is_user_defined = FALSE;
1476
1477         if (is_builtin_target(target_name))
1478                 is_builtin = TRUE;
1479         else {
1480                 chain_head = find_chain_head(table, target_name);
1481                 if (chain_head != NULL && chain_head->next != NULL)
1482                         is_user_defined = TRUE;
1483         }
1484
1485         if (is_builtin || is_user_defined)
1486                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1487                                                 XTF_LOAD_MUST_SUCCEED);
1488         else
1489                 xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1490
1491         if (xt_t == NULL)
1492                 return NULL;
1493
1494         target_size = ALIGN(sizeof(struct ipt_entry_target)) + xt_t->size;
1495
1496         xt_t->t = g_try_malloc0(target_size);
1497         if (xt_t->t == NULL)
1498                 return NULL;
1499
1500         xt_t->t->u.target_size = target_size;
1501
1502         if (is_builtin || is_user_defined) {
1503                 struct xt_standard_target *target;
1504
1505                 target = (struct xt_standard_target *)(xt_t->t);
1506                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
1507
1508                 if (is_builtin == TRUE)
1509                         target->verdict = target_to_verdict(target_name);
1510                 else if (is_user_defined == TRUE) {
1511                         struct connman_iptables_entry *target_rule;
1512
1513                         if (chain_head == NULL) {
1514                                 g_free(xt_t->t);
1515                                 return NULL;
1516                         }
1517
1518                         target_rule = chain_head->next->data;
1519                         target->verdict = target_rule->offset;
1520                 }
1521         } else {
1522                 strcpy(xt_t->t->u.user.name, target_name);
1523                 xt_t->t->u.user.revision = xt_t->revision;
1524                 if (xt_t->init != NULL)
1525                         xt_t->init(xt_t->t);
1526         }
1527
1528 #if XTABLES_VERSION_CODE > 5
1529         if (xt_t->x6_options != NULL)
1530                 iptables_globals.opts =
1531                         xtables_options_xfrm(
1532                                 iptables_globals.orig_opts,
1533                                 iptables_globals.opts,
1534                                 xt_t->x6_options,
1535                                 &xt_t->option_offset);
1536         else
1537 #endif
1538                 iptables_globals.opts =
1539                         xtables_merge_options(
1540 #if XTABLES_VERSION_CODE > 5
1541                                 iptables_globals.orig_opts,
1542 #endif
1543                                 iptables_globals.opts,
1544                                 xt_t->extra_opts,
1545                                 &xt_t->option_offset);
1546
1547         if (iptables_globals.opts == NULL) {
1548                 g_free(xt_t->t);
1549                 xt_t = NULL;
1550         }
1551
1552         return xt_t;
1553 }
1554
1555 static struct xtables_match *prepare_matches(struct connman_iptables *table,
1556                                         struct xtables_rule_match **xt_rm,
1557                                         const char *match_name)
1558 {
1559         struct xtables_match *xt_m;
1560         size_t match_size;
1561
1562         if (match_name == NULL)
1563                 return NULL;
1564
1565         xt_m = xtables_find_match(match_name, XTF_LOAD_MUST_SUCCEED, xt_rm);
1566         match_size = ALIGN(sizeof(struct ipt_entry_match)) + xt_m->size;
1567
1568         xt_m->m = g_try_malloc0(match_size);
1569         if (xt_m->m == NULL)
1570                 return NULL;
1571
1572         xt_m->m->u.match_size = match_size;
1573         strcpy(xt_m->m->u.user.name, xt_m->name);
1574         xt_m->m->u.user.revision = xt_m->revision;
1575
1576         if (xt_m->init != NULL)
1577                 xt_m->init(xt_m->m);
1578
1579         if (xt_m == xt_m->next)
1580                 goto done;
1581
1582 #if XTABLES_VERSION_CODE > 5
1583         if (xt_m->x6_options != NULL)
1584                 iptables_globals.opts =
1585                         xtables_options_xfrm(
1586                                 iptables_globals.orig_opts,
1587                                 iptables_globals.opts,
1588                                 xt_m->x6_options,
1589                                 &xt_m->option_offset);
1590         else
1591 #endif
1592                         iptables_globals.opts =
1593                         xtables_merge_options(
1594 #if XTABLES_VERSION_CODE > 5
1595                                 iptables_globals.orig_opts,
1596 #endif
1597                                 iptables_globals.opts,
1598                                 xt_m->extra_opts,
1599                                 &xt_m->option_offset);
1600
1601         if (iptables_globals.opts == NULL) {
1602                 g_free(xt_m->m);
1603                 xt_m = NULL;
1604         }
1605
1606 done:
1607         return xt_m;
1608 }
1609
1610 static int parse_ip_and_mask(const char *str, struct in_addr *ip, struct in_addr *mask)
1611 {
1612         char **tokens;
1613         uint32_t prefixlength;
1614         uint32_t tmp;
1615         int err;
1616
1617         tokens = g_strsplit(str, "/", 2);
1618         if (tokens == NULL)
1619                 return -1;
1620
1621         if (!inet_pton(AF_INET, tokens[0], ip)) {
1622                 err = -1;
1623                 goto out;
1624         }
1625
1626         if (tokens[1] != NULL) {
1627                 prefixlength = strtol(tokens[1], NULL, 10);
1628                 if (prefixlength > 31) {
1629                         err = -1;
1630                         goto out;
1631                 }
1632
1633                 tmp = ~(0xffffffff >> prefixlength);
1634         } else {
1635                 tmp = 0xffffffff;
1636         }
1637
1638         mask->s_addr = htonl(tmp);
1639         ip->s_addr = ip->s_addr & mask->s_addr;
1640         err = 0;
1641 out:
1642         g_strfreev(tokens);
1643
1644         return err;
1645 }
1646
1647 static struct connman_iptables *pre_load_table(const char *table_name,
1648                                         struct connman_iptables *table)
1649 {
1650         if (table != NULL)
1651                 return table;
1652
1653         return iptables_init(table_name);
1654 }
1655
1656 static void clear_tables_flags(void)
1657 {
1658         struct xtables_match *xt_m;
1659         struct xtables_target *xt_t;
1660
1661         /*
1662          * Clear all flags because the flags are only valid
1663          * for one rule.
1664          */
1665         for (xt_m = xtables_matches; xt_m != NULL; xt_m = xt_m->next)
1666                 xt_m->mflags = 0;
1667
1668         for (xt_t = xtables_targets; xt_t != NULL; xt_t = xt_t->next) {
1669                 xt_t->tflags = 0;
1670                 xt_t->used = 0;
1671         }
1672 }
1673
1674 struct parse_context {
1675         int argc;
1676         char **argv;
1677         struct ipt_ip *ip;
1678         struct xtables_target *xt_t;
1679         struct xtables_match *xt_m;
1680         struct xtables_rule_match *xt_rm;
1681 };
1682
1683 static int prepare_getopt_args(const char *str, struct parse_context *ctx)
1684 {
1685         char **tokens;
1686         int i;
1687
1688         tokens = g_strsplit_set(str, " ", -1);
1689
1690         for (i = 0; tokens[i]; i++);
1691
1692         /* Add space for the argv[0] value */
1693         ctx->argc = i + 1;
1694
1695         /* Don't forget the last NULL entry */
1696         ctx->argv = g_try_malloc0((ctx->argc + 1) * sizeof(char *));
1697         if (ctx->argv == NULL) {
1698                 g_strfreev(tokens);
1699                 return -ENOMEM;
1700         }
1701
1702         /*
1703          * getopt_long() jumps over the first token; we need to add some
1704          * random argv[0] entry.
1705          */
1706         ctx->argv[0] = g_strdup("argh");
1707         for (i = 1; i < ctx->argc; i++)
1708                 ctx->argv[i] = tokens[i - 1];
1709
1710         return 0;
1711 }
1712
1713 #if XTABLES_VERSION_CODE > 5
1714
1715 static int parse_xt_modules(int c, connman_bool_t invert,
1716                                 struct parse_context *ctx)
1717 {
1718         struct xtables_match *m;
1719         struct xtables_rule_match *rm;
1720
1721         DBG("xtables version code > 5");
1722
1723         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
1724                 if (rm->completed != 0)
1725                         continue;
1726
1727                 m = rm->match;
1728
1729                 if (m->x6_parse == NULL && m->parse == NULL)
1730                         continue;
1731
1732                 if (c < (int) m->option_offset ||
1733                                 c >= (int) m->option_offset
1734                                         + XT_OPTION_OFFSET_SCALE)
1735                         continue;
1736
1737                 xtables_option_mpcall(c, ctx->argv, invert, m, NULL);
1738         }
1739
1740         if (ctx->xt_t == NULL)
1741                 return 0;
1742
1743         if (ctx->xt_t->x6_parse == NULL && ctx->xt_t->parse == NULL)
1744                 return 0;
1745
1746         if (c < (int) ctx->xt_t->option_offset ||
1747                         c >= (int) ctx->xt_t->option_offset
1748                                         + XT_OPTION_OFFSET_SCALE)
1749                 return 0;
1750
1751         xtables_option_tpcall(c, ctx->argv, invert, ctx->xt_t, NULL);
1752
1753         return 0;
1754 }
1755
1756 static int final_check_xt_modules(struct parse_context *ctx)
1757 {
1758         struct xtables_rule_match *rm;
1759
1760         DBG("xtables version code > 5");
1761
1762         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
1763                 xtables_option_mfcall(rm->match);
1764
1765         if (ctx->xt_t != NULL)
1766                 xtables_option_tfcall(ctx->xt_t);
1767
1768         return 0;
1769 }
1770
1771 #else
1772
1773 static int parse_xt_modules(int c, connman_bool_t invert,
1774                                 struct parse_context *ctx)
1775 {
1776         struct xtables_match *m;
1777         struct xtables_rule_match *rm;
1778         int err;
1779
1780         DBG("xtables version code <= 5");
1781
1782         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
1783                 if (rm->completed == 1)
1784                         continue;
1785
1786                 m = rm->match;
1787
1788                 if (m->parse == NULL)
1789                         continue;
1790
1791                 err = m->parse(c - m->option_offset,
1792                                 argv, invert, &m->mflags,
1793                                 NULL, &m->m);
1794                 if (err > 0)
1795                         return -err;
1796         }
1797
1798         if (ctx->xt_t == NULL)
1799                 return 0;
1800
1801         if (ctx->xt_t->parse == NULL)
1802                 return 0;
1803
1804         err = ctx->xt_m->parse(c - ctx->xt_m->option_offset,
1805                                 ctx->argv, invert, &ctx->xt_m->mflags,
1806                                 NULL, &ctx->xt_m->m);
1807         return -err;
1808 }
1809
1810 static int final_check_xt_modules(struct parse_context *ctx)
1811 {
1812         struct xtables_rule_match *rm;
1813
1814         DBG("xtables version code <= 5");
1815
1816         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
1817                 if (rm->match->final_check != NULL)
1818                         rm->match->final_check(rm->match->mflags);
1819
1820         if (ctx->xt_t != NULL && ctx->xt_t->final_check != NULL)
1821                 ctx->xt_t->final_check(ctx->xt_t->tflags);
1822
1823         return 0;
1824 }
1825
1826 #endif
1827
1828 static int parse_rule_spec(struct connman_iptables *table,
1829                                 struct parse_context *ctx)
1830 {
1831         /*
1832          * How the parser works:
1833          *
1834          *  - If getopt finds 's', 'd', 'i', 'o'.
1835          *    just extract the information.
1836          *  - if '!' is found, set the invert flag to true and
1837          *    removes the '!' from the optarg string and jumps
1838          *    back to getopt to reparse the current optarg string.
1839          *    After reparsing the invert flag is reseted to false.
1840          *  - If 'm' or 'j' is found then call either
1841          *    prepare_matches() or prepare_target(). Those function
1842          *    will modify (extend) the longopts for getopt_long.
1843          *    That means getopt will change its matching context according
1844          *    the loaded target.
1845          *
1846          *    Here an example with iptables-test
1847          *
1848          *    argv[0] = ./tools/iptables-test
1849          *    argv[1] = -t
1850          *    argv[2] = filter
1851          *    argv[3] = -A
1852          *    argv[4] = INPUT
1853          *    argv[5] = -m
1854          *    argv[6] = mark
1855          *    argv[7] = --mark
1856          *    argv[8] = 999
1857          *    argv[9] = -j
1858          *    argv[10] = LOG
1859          *
1860          *    getopt found 'm' then the optarg is "mark" and optind 7
1861          *    The longopts array containts before hitting the `case 'm'`
1862          *
1863          *    val A has_arg 1 name append
1864          *    val C has_arg 1 name compare
1865          *    val D has_arg 1 name delete
1866          *    val F has_arg 1 name flush-chain
1867          *    val I has_arg 1 name insert
1868          *    val L has_arg 2 name list
1869          *    val N has_arg 1 name new-chain
1870          *    val P has_arg 1 name policy
1871          *    val X has_arg 1 name delete-chain
1872          *    val d has_arg 1 name destination
1873          *    val i has_arg 1 name in-interface
1874          *    val j has_arg 1 name jump
1875          *    val m has_arg 1 name match
1876          *    val o has_arg 1 name out-interface
1877          *    val s has_arg 1 name source
1878          *    val t has_arg 1 name table
1879          *
1880          *    After executing the `case 'm'` block longopts is
1881          *
1882          *    val A has_arg 1 name append
1883          *    val C has_arg 1 name compare
1884          *    val D has_arg 1 name delete
1885          *    val F has_arg 1 name flush-chain
1886          *    val I has_arg 1 name insert
1887          *    val L has_arg 2 name list
1888          *    val N has_arg 1 name new-chain
1889          *    val P has_arg 1 name policy
1890          *    val X has_arg 1 name delete-chain
1891          *    val d has_arg 1 name destination
1892          *    val i has_arg 1 name in-interface
1893          *    val j has_arg 1 name jump
1894          *    val m has_arg 1 name match
1895          *    val o has_arg 1 name out-interface
1896          *    val s has_arg 1 name source
1897          *    val t has_arg 1 name table
1898          *    val   has_arg 1 name mark
1899          *
1900          *    So the 'mark' matcher has added the 'mark' options
1901          *    and getopt will then return c '256' optarg "999" optind 9
1902          *    And we will hit the 'default' statement which then
1903          *    will call the matchers parser (xt_m->parser() or
1904          *    xtables_option_mpcall() depending on which version
1905          *    of libxtables is found.
1906          */
1907         connman_bool_t invert = FALSE;
1908         int len, c, err;
1909
1910         DBG("");
1911
1912         ctx->ip = g_try_new0(struct ipt_ip, 1);
1913         if (ctx->ip == NULL)
1914                 return -ENOMEM;
1915
1916         /*
1917          * As side effect parsing a rule sets some global flags
1918          * which will be evaluated/verified. Let's reset them
1919          * to ensure we can parse more than one rule.
1920          */
1921         clear_tables_flags();
1922
1923         /*
1924          * Tell getopt_long not to generate error messages for unknown
1925          * options and also reset optind back to 0.
1926          */
1927         opterr = 0;
1928         optind = 0;
1929
1930         while ((c = getopt_long(ctx->argc, ctx->argv,
1931                                         "-:d:i:o:s:m:j:",
1932                                         iptables_globals.opts, NULL)) != -1) {
1933                 switch (c) {
1934                 case 's':
1935                         /* Source specification */
1936                         if (!parse_ip_and_mask(optarg,
1937                                                 &ctx->ip->src,
1938                                                 &ctx->ip->smsk))
1939                                 break;
1940
1941                         if (invert)
1942                                 ctx->ip->invflags |= IPT_INV_SRCIP;
1943
1944                         break;
1945                 case 'd':
1946                         /* Destination specification */
1947                         if (!parse_ip_and_mask(optarg,
1948                                                 &ctx->ip->dst,
1949                                                 &ctx->ip->dmsk))
1950                                 break;
1951
1952                         if (invert)
1953                                 ctx->ip->invflags |= IPT_INV_DSTIP;
1954                         break;
1955                 case 'i':
1956                         /* In interface specification */
1957                         len = strlen(optarg);
1958
1959                         if (len + 1 > IFNAMSIZ)
1960                                 break;
1961
1962                         strcpy(ctx->ip->iniface, optarg);
1963                         memset(ctx->ip->iniface_mask, 0xff, len + 1);
1964
1965                         if (invert)
1966                                 ctx->ip->invflags |= IPT_INV_VIA_IN;
1967
1968                         break;
1969                 case 'o':
1970                         /* Out interface specification */
1971                         len = strlen(optarg);
1972
1973                         if (len + 1 > IFNAMSIZ)
1974                                 break;
1975
1976                         strcpy(ctx->ip->outiface, optarg);
1977                         memset(ctx->ip->outiface_mask, 0xff, len + 1);
1978
1979                         if (invert)
1980                                 ctx->ip->invflags |= IPT_INV_VIA_OUT;
1981
1982                         break;
1983                 case 'm':
1984                         /* Matches */
1985                         ctx->xt_m = prepare_matches(table, &ctx->xt_rm, optarg);
1986                         if (ctx->xt_m == NULL) {
1987                                 err = -EINVAL;
1988                                 goto out;
1989                         }
1990
1991                         break;
1992                 case 'j':
1993                         /* Target */
1994                         ctx->xt_t = prepare_target(table, optarg);
1995                         if (ctx->xt_t == NULL) {
1996                                 err = -EINVAL;
1997                                 goto out;
1998                         }
1999
2000                         break;
2001                 case 1:
2002                         if (optarg[0] == '!' && optarg[1] == '\0') {
2003                                 invert = TRUE;
2004
2005                                 /* Remove the '!' from the optarg */
2006                                 optarg[0] = '\0';
2007
2008                                 /*
2009                                  * And recall getopt_long without reseting
2010                                  * invert.
2011                                  */
2012                                 continue;
2013                         }
2014
2015                         break;
2016                 default:
2017                         err = parse_xt_modules(c, invert, ctx);
2018                         if (err == 1)
2019                                 continue;
2020
2021                         break;
2022                 }
2023
2024                 invert = FALSE;
2025         }
2026
2027         err = final_check_xt_modules(ctx);
2028
2029 out:
2030         return err;
2031 }
2032
2033 static void reset_xtables(void)
2034 {
2035         /*
2036          * We need also to free the memory implicitly allocated
2037          * during parsing (see xtables_options_xfrm()).
2038          * Note xt_params is actually iptables_globals.
2039          */
2040         if (xt_params->opts != xt_params->orig_opts) {
2041                 g_free(xt_params->opts);
2042                 xt_params->opts = xt_params->orig_opts;
2043         }
2044         xt_params->option_offset = 0;
2045 }
2046
2047 static void cleanup_parse_context(struct parse_context *ctx)
2048 {
2049         g_strfreev(ctx->argv);
2050         g_free(ctx->ip);
2051         if (ctx->xt_t != NULL)
2052                 g_free(ctx->xt_t->t);
2053         if (ctx->xt_m != NULL)
2054                 g_free(ctx->xt_m->m);
2055         g_free(ctx);
2056 }
2057
2058 int __connman_iptables_new_chain(const char *table_name,
2059                                         const char *chain)
2060 {
2061         struct connman_iptables *table;
2062
2063         DBG("-t %s -N %s", table_name, chain);
2064
2065         table = pre_load_table(table_name, NULL);
2066         if (table == NULL)
2067                 return -EINVAL;
2068
2069         return iptables_add_chain(table, chain);
2070 }
2071
2072 int __connman_iptables_delete_chain(const char *table_name,
2073                                         const char *chain)
2074 {
2075         struct connman_iptables *table;
2076
2077         DBG("-t %s -X %s", table_name, chain);
2078
2079         table = pre_load_table(table_name, NULL);
2080         if (table == NULL)
2081                 return -EINVAL;
2082
2083         return iptables_delete_chain(table, chain);
2084 }
2085
2086 int __connman_iptables_flush_chain(const char *table_name,
2087                                         const char *chain)
2088 {
2089         struct connman_iptables *table;
2090
2091         DBG("-t %s -F %s", table_name, chain);
2092
2093         table = pre_load_table(table_name, NULL);
2094         if (table == NULL)
2095                 return -EINVAL;
2096
2097         return iptables_flush_chain(table, chain);
2098 }
2099
2100 int __connman_iptables_change_policy(const char *table_name,
2101                                         const char *chain,
2102                                         const char *policy)
2103 {
2104         struct connman_iptables *table;
2105
2106         DBG("-t %s -F %s", table_name, chain);
2107
2108         table = pre_load_table(table_name, NULL);
2109         if (table == NULL)
2110                 return -EINVAL;
2111
2112         return iptables_change_policy(table, chain, policy);
2113 }
2114
2115 int __connman_iptables_append(const char *table_name,
2116                                 const char *chain,
2117                                 const char *rule_spec)
2118 {
2119         struct connman_iptables *table;
2120         struct parse_context *ctx;
2121         const char *target_name;
2122         int err;
2123
2124         ctx = g_try_new0(struct parse_context, 1);
2125         if (ctx == NULL)
2126                 return -ENOMEM;
2127
2128         DBG("-t %s -A %s %s", table_name, chain, rule_spec);
2129
2130         err = prepare_getopt_args(rule_spec, ctx);
2131         if (err < 0)
2132                 goto out;
2133
2134         table = pre_load_table(table_name, NULL);
2135         if (table == NULL) {
2136                 err = -EINVAL;
2137                 goto out;
2138         }
2139
2140         err = parse_rule_spec(table, ctx);
2141         if (err < 0)
2142                 goto out;
2143
2144         if (ctx->xt_t == NULL)
2145                 target_name = NULL;
2146         else
2147                 target_name = ctx->xt_t->name;
2148
2149         err = iptables_insert_rule(table, ctx->ip, chain,
2150                                 target_name, ctx->xt_t, ctx->xt_rm);
2151 out:
2152         cleanup_parse_context(ctx);
2153         reset_xtables();
2154
2155         return err;
2156 }
2157
2158 int __connman_iptables_delete(const char *table_name,
2159                                 const char *chain,
2160                                 const char *rule_spec)
2161 {
2162         struct connman_iptables *table;
2163         struct parse_context *ctx;
2164         const char *target_name;
2165         int err;
2166
2167         ctx = g_try_new0(struct parse_context, 1);
2168         if (ctx == NULL)
2169                 return -ENOMEM;
2170
2171         DBG("-t %s -D %s %s", table_name, chain, rule_spec);
2172
2173         err = prepare_getopt_args(rule_spec, ctx);
2174         if (err < 0)
2175                 goto out;
2176
2177         table = pre_load_table(table_name, NULL);
2178         if (table == NULL) {
2179                 err = -EINVAL;
2180                 goto out;
2181         }
2182
2183         err = parse_rule_spec(table, ctx);
2184         if (err < 0)
2185                 goto out;
2186
2187         if (ctx->xt_t == NULL)
2188                 target_name = NULL;
2189         else
2190                 target_name = ctx->xt_t->name;
2191
2192         err = iptables_delete_rule(table, ctx->ip, chain,
2193                                 target_name, ctx->xt_t, ctx->xt_m,
2194                                 ctx->xt_rm);
2195 out:
2196         cleanup_parse_context(ctx);
2197         reset_xtables();
2198
2199         return err;
2200 }
2201
2202 int __connman_iptables_commit(const char *table_name)
2203 {
2204         struct connman_iptables *table;
2205         struct ipt_replace *repl;
2206         int err;
2207
2208         DBG("%s", table_name);
2209
2210         table = g_hash_table_lookup(table_hash, table_name);
2211         if (table == NULL)
2212                 return -EINVAL;
2213
2214         repl = iptables_blob(table);
2215
2216         if (debug_enabled == TRUE)
2217                 dump_ipt_replace(repl);
2218
2219         err = iptables_replace(table, repl);
2220
2221         g_free(repl->counters);
2222         g_free(repl);
2223
2224         if (err < 0)
2225             return err;
2226
2227         g_hash_table_remove(table_hash, table_name);
2228
2229         return 0;
2230 }
2231
2232 static void remove_table(gpointer user_data)
2233 {
2234         struct connman_iptables *table = user_data;
2235
2236         table_cleanup(table);
2237 }
2238
2239 static int flush_table_cb(struct ipt_entry *entry, int builtin,
2240                                 unsigned int hook, size_t size,
2241                                 unsigned int offset, void *user_data)
2242 {
2243         GSList **chains = user_data;
2244         struct xt_entry_target *target;
2245         char *name;
2246
2247         if (offset + entry->next_offset == size)
2248                 return 0;
2249
2250         target = ipt_get_target(entry);
2251
2252         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
2253                 name = g_strdup((const char*)target->data);
2254         else if (builtin >= 0)
2255                   name = g_strdup(hooknames[builtin]);
2256         else
2257                 return 0;
2258
2259         *chains = g_slist_prepend(*chains, name);
2260
2261         return 0;
2262 }
2263
2264 void flush_table(const char *name)
2265 {
2266         GSList *chains = NULL, *list;
2267         struct connman_iptables *table;
2268
2269         table = pre_load_table(name, NULL);
2270         if (table == NULL)
2271                 return;
2272
2273         iterate_entries(table->blob_entries->entrytable,
2274                         table->info->valid_hooks,
2275                         table->info->hook_entry,
2276                         table->blob_entries->size,
2277                         flush_table_cb, &chains);
2278
2279         for (list = chains; list != NULL; list = list->next) {
2280                 char *chain = list->data;
2281
2282                 DBG("chain %s", chain);
2283                 iptables_flush_chain(table, chain);
2284         }
2285
2286         __connman_iptables_commit(name);
2287         g_slist_free_full(chains, g_free);
2288 }
2289
2290 int __connman_iptables_init(void)
2291 {
2292         DBG("");
2293
2294         if (getenv("CONNMAN_IPTABLES_DEBUG"))
2295                 debug_enabled = TRUE;
2296
2297         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
2298                                                 g_free, remove_table);
2299
2300         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
2301
2302         return 0;
2303 }
2304
2305 void __connman_iptables_cleanup(void)
2306 {
2307         DBG("");
2308
2309         g_hash_table_destroy(table_hash);
2310 }