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