iptables: Fix fallthrough rules
[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         if (xt_e_t1 == NULL || xt_e_t2 == NULL)
824                 return FALSE;
825
826         if (strcmp(xt_e_t1->u.user.name, IPT_STANDARD_TARGET) == 0) {
827                 struct xt_standard_target *xt_s_t1;
828                 struct xt_standard_target *xt_s_t2;
829
830                 xt_s_t1 = (struct xt_standard_target *) xt_e_t1;
831                 xt_s_t2 = (struct xt_standard_target *) xt_e_t2;
832
833                 if (xt_s_t1->verdict != xt_s_t2->verdict)
834                         return FALSE;
835         } else {
836                 if (xt_e_t1->u.target_size != xt_e_t2->u.target_size)
837                         return FALSE;
838
839                 if (strcmp(xt_e_t1->u.user.name, xt_e_t2->u.user.name) != 0)
840                         return FALSE;
841         }
842
843         return TRUE;
844 }
845
846 static gboolean is_same_match(struct xt_entry_match *xt_e_m1,
847                                 struct xt_entry_match *xt_e_m2)
848 {
849         if (xt_e_m1 == NULL || xt_e_m2 == NULL)
850                 return FALSE;
851
852         if (xt_e_m1->u.match_size != xt_e_m2->u.match_size)
853                 return FALSE;
854
855         if (xt_e_m1->u.user.revision != xt_e_m2->u.user.revision)
856                 return FALSE;
857
858         if (strcmp(xt_e_m1->u.user.name, xt_e_m2->u.user.name) != 0)
859                 return FALSE;
860
861         return TRUE;
862 }
863
864 static GList *find_existing_rule(struct connman_iptables *table,
865                                 struct ipt_ip *ip, const char *chain_name,
866                                 const char *target_name,
867                                 struct xtables_target *xt_t,
868                                 struct xtables_match *xt_m,
869                                 struct xtables_rule_match *xt_rm)
870 {
871         GList *chain_tail, *chain_head, *list;
872         struct xt_entry_target *xt_e_t = NULL;
873         struct xt_entry_match *xt_e_m = NULL;
874         struct connman_iptables_entry *entry;
875         struct ipt_entry *entry_test;
876         int builtin;
877
878         chain_head = find_chain_head(table, chain_name);
879         if (chain_head == NULL)
880                 return NULL;
881
882         chain_tail = find_chain_tail(table, chain_name);
883         if (chain_tail == NULL)
884                 return NULL;
885
886         if (!xt_t && !xt_m)
887                 return NULL;
888
889         entry_test = new_rule(ip, target_name, xt_t, xt_rm);
890         if (entry_test == NULL)
891                 return NULL;
892
893         if (xt_t != NULL)
894                 xt_e_t = ipt_get_target(entry_test);
895         if (xt_m != NULL)
896                 xt_e_m = (struct xt_entry_match *)entry_test->elems;
897
898         entry = chain_head->data;
899         builtin = entry->builtin;
900
901         if (builtin >= 0)
902                 list = chain_head;
903         else
904                 list = chain_head->next;
905
906         for (; list != chain_tail->prev; list = list->next) {
907                 struct connman_iptables_entry *tmp;
908                 struct ipt_entry *tmp_e;
909
910                 tmp = list->data;
911                 tmp_e = tmp->entry;
912
913                 if (is_same_ipt_entry(entry_test, tmp_e) == FALSE)
914                         continue;
915
916                 if (xt_t != NULL) {
917                         struct xt_entry_target *tmp_xt_e_t;
918
919                         tmp_xt_e_t = ipt_get_target(tmp_e);
920
921                         if (!is_same_target(tmp_xt_e_t, xt_e_t))
922                                 continue;
923                 }
924
925                 if (xt_m != NULL) {
926                         struct xt_entry_match *tmp_xt_e_m;
927
928                         tmp_xt_e_m = (struct xt_entry_match *)tmp_e->elems;
929
930                         if (!is_same_match(tmp_xt_e_m, xt_e_m))
931                                 continue;
932                 }
933
934                 break;
935         }
936
937         g_free(entry_test);
938
939         if (list != chain_tail->prev)
940                 return list;
941
942         return NULL;
943 }
944
945 static int iptables_delete_rule(struct connman_iptables *table,
946                                 struct ipt_ip *ip, const char *chain_name,
947                                 const char *target_name,
948                                 struct xtables_target *xt_t,
949                                 struct xtables_match *xt_m,
950                                 struct xtables_rule_match *xt_rm)
951 {
952         struct connman_iptables_entry *entry;
953         GList *chain_tail, *list;
954         int builtin, removed;
955
956         removed = 0;
957
958         chain_tail = find_chain_tail(table, chain_name);
959         if (chain_tail == NULL)
960                 return -EINVAL;
961
962         list = find_existing_rule(table, ip, chain_name, target_name,
963                                                         xt_t, xt_m, xt_rm);
964         if (list == NULL)
965                 return -EINVAL;
966
967         entry = list->data;
968         if (entry == NULL)
969                 return -EINVAL;
970
971         builtin = entry->builtin;
972
973         /* We have deleted a rule,
974          * all references should be bumped accordingly */
975         if (list->next != NULL)
976                 update_targets_reference(table, list->next->data,
977                                                 list->data, TRUE);
978
979         removed += remove_table_entry(table, entry);
980
981         if (builtin >= 0) {
982                 list = list->next;
983                 if (list) {
984                         entry = list->data;
985                         entry->builtin = builtin;
986                 }
987
988                 table->underflow[builtin] -= removed;
989                 for (list = chain_tail; list; list = list->next) {
990                         entry = list->data;
991
992                         builtin = entry->builtin;
993                         if (builtin < 0)
994                                 continue;
995
996                         table->hook_entry[builtin] -= removed;
997                         table->underflow[builtin] -= removed;
998                 }
999         }
1000
1001         update_offsets(table);
1002
1003         return 0;
1004 }
1005
1006 static int iptables_change_policy(struct connman_iptables *table,
1007                                 const char *chain_name, const char *policy)
1008 {
1009         GList *chain_head;
1010         struct connman_iptables_entry *entry;
1011         struct xt_entry_target *target;
1012         struct xt_standard_target *t;
1013         int verdict;
1014
1015         verdict = target_to_verdict(policy);
1016         if (verdict == 0)
1017                 return -EINVAL;
1018
1019         chain_head = find_chain_head(table, chain_name);
1020         if (chain_head == NULL)
1021                 return -EINVAL;
1022
1023         entry = chain_head->data;
1024         if (entry->builtin < 0)
1025                 return -EINVAL;
1026
1027         target = ipt_get_target(entry->entry);
1028
1029         t = (struct xt_standard_target *)target;
1030         t->verdict = verdict;
1031
1032         return 0;
1033 }
1034
1035 static struct ipt_replace *iptables_blob(struct connman_iptables *table)
1036 {
1037         struct ipt_replace *r;
1038         GList *list;
1039         struct connman_iptables_entry *e;
1040         unsigned char *entry_index;
1041
1042         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
1043         if (r == NULL)
1044                 return NULL;
1045
1046         memset(r, 0, sizeof(*r) + table->size);
1047
1048         r->counters = g_try_malloc0(sizeof(struct xt_counters)
1049                                 * table->old_entries);
1050         if (r->counters == NULL) {
1051                 g_free(r);
1052                 return NULL;
1053         }
1054
1055         strcpy(r->name, table->info->name);
1056         r->num_entries = table->num_entries;
1057         r->size = table->size;
1058
1059         r->num_counters = table->old_entries;
1060         r->valid_hooks  = table->info->valid_hooks;
1061
1062         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
1063         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
1064
1065         entry_index = (unsigned char *)r->entries;
1066         for (list = table->entries; list; list = list->next) {
1067                 e = list->data;
1068
1069                 memcpy(entry_index, e->entry, e->entry->next_offset);
1070                 entry_index += e->entry->next_offset;
1071         }
1072
1073         return r;
1074 }
1075
1076 static void dump_ip(struct ipt_entry *entry)
1077 {
1078         struct ipt_ip *ip = &entry->ip;
1079         char ip_string[INET6_ADDRSTRLEN];
1080         char ip_mask[INET6_ADDRSTRLEN];
1081
1082         if (strlen(ip->iniface))
1083                 DBG("\tin %s", ip->iniface);
1084
1085         if (strlen(ip->outiface))
1086                 DBG("\tout %s", ip->outiface);
1087
1088         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
1089                         inet_ntop(AF_INET, &ip->smsk,
1090                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1091                 DBG("\tsrc %s/%s", ip_string, ip_mask);
1092
1093         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
1094                         inet_ntop(AF_INET, &ip->dmsk,
1095                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1096                 DBG("\tdst %s/%s", ip_string, ip_mask);
1097 }
1098
1099 static void dump_target(struct ipt_entry *entry)
1100
1101 {
1102         struct xtables_target *xt_t;
1103         struct xt_entry_target *target;
1104
1105         target = ipt_get_target(entry);
1106
1107         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
1108                 struct xt_standard_target *t;
1109
1110                 t = (struct xt_standard_target *)target;
1111
1112                 switch (t->verdict) {
1113                 case XT_RETURN:
1114                         DBG("\ttarget RETURN");
1115                         break;
1116
1117                 case -NF_ACCEPT - 1:
1118                         DBG("\ttarget ACCEPT");
1119                         break;
1120
1121                 case -NF_DROP - 1:
1122                         DBG("\ttarget DROP");
1123                         break;
1124
1125                 case -NF_QUEUE - 1:
1126                         DBG("\ttarget QUEUE");
1127                         break;
1128
1129                 case -NF_STOP - 1:
1130                         DBG("\ttarget STOP");
1131                         break;
1132
1133                 default:
1134                         DBG("\tJUMP %u", t->verdict);
1135                         break;
1136                 }
1137
1138                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1139                                                 XTF_LOAD_MUST_SUCCEED);
1140
1141                 if(xt_t->print != NULL)
1142                         xt_t->print(NULL, target, 1);
1143         } else {
1144                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
1145                 if (xt_t == NULL) {
1146                         DBG("\ttarget %s", target->u.user.name);
1147                         return;
1148                 }
1149
1150                 if(xt_t->print != NULL) {
1151                         DBG("\ttarget ");
1152                         xt_t->print(NULL, target, 1);
1153                 }
1154         }
1155 }
1156
1157 static void dump_match(struct ipt_entry *entry)
1158 {
1159         struct xtables_match *xt_m;
1160         struct xt_entry_match *match;
1161
1162         if (entry->elems == (unsigned char *)entry + entry->target_offset)
1163                 return;
1164
1165         match = (struct xt_entry_match *) entry->elems;
1166
1167         if (!strlen(match->u.user.name))
1168                 return;
1169
1170         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
1171         if (xt_m == NULL)
1172                 goto out;
1173
1174         if(xt_m->print != NULL) {
1175                 DBG("\tmatch ");
1176                 xt_m->print(NULL, match, 1);
1177
1178                 return;
1179         }
1180
1181 out:
1182         DBG("\tmatch %s", match->u.user.name);
1183
1184 }
1185
1186 static int dump_entry(struct ipt_entry *entry, int builtin,
1187                         unsigned int hook, size_t size, unsigned int offset,
1188                         void *user_data)
1189 {
1190         struct xt_entry_target *target;
1191
1192         target = ipt_get_target(entry);
1193
1194         if (offset + entry->next_offset == size) {
1195                 DBG("\tEnd of CHAIN");
1196                 return 0;
1197         }
1198
1199         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
1200                 DBG("\tUSER CHAIN (%s) match %p  target %p",
1201                         target->data, entry->elems,
1202                         (char *)entry + entry->target_offset);
1203
1204                 return 0;
1205         } else if (builtin >= 0) {
1206                 DBG("\tCHAIN (%s) match %p  target %p",
1207                         hooknames[builtin], entry->elems,
1208                         (char *)entry + entry->target_offset);
1209         } else {
1210                 DBG("\tRULE  match %p  target %p",
1211                         entry->elems,
1212                         (char *)entry + entry->target_offset);
1213         }
1214
1215         dump_match(entry);
1216         dump_target(entry);
1217         dump_ip(entry);
1218
1219         return 0;
1220 }
1221
1222 static void dump_table(struct connman_iptables *table)
1223 {
1224         DBG("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
1225                         table->info->name,
1226                         table->info->valid_hooks, table->info->num_entries,
1227                                 table->info->size);
1228
1229         DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
1230                 table->info->hook_entry[NF_IP_PRE_ROUTING],
1231                 table->info->hook_entry[NF_IP_LOCAL_IN],
1232                 table->info->hook_entry[NF_IP_FORWARD],
1233                 table->info->hook_entry[NF_IP_LOCAL_OUT],
1234                 table->info->hook_entry[NF_IP_POST_ROUTING]);
1235         DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
1236                 table->info->underflow[NF_IP_PRE_ROUTING],
1237                 table->info->underflow[NF_IP_LOCAL_IN],
1238                 table->info->underflow[NF_IP_FORWARD],
1239                 table->info->underflow[NF_IP_LOCAL_OUT],
1240                 table->info->underflow[NF_IP_POST_ROUTING]);
1241
1242         iterate_entries(table->blob_entries->entrytable,
1243                         table->info->valid_hooks,
1244                         table->info->hook_entry,
1245                         table->blob_entries->size,
1246                         print_entry, dump_entry);
1247 }
1248
1249 static void dump_ipt_replace(struct ipt_replace *repl)
1250 {
1251         DBG("%s valid_hooks 0x%08x  num_entries %u  size %u",
1252                         repl->name, repl->valid_hooks, repl->num_entries,
1253                         repl->size);
1254
1255         DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
1256                 repl->hook_entry[NF_IP_PRE_ROUTING],
1257                 repl->hook_entry[NF_IP_LOCAL_IN],
1258                 repl->hook_entry[NF_IP_FORWARD],
1259                 repl->hook_entry[NF_IP_LOCAL_OUT],
1260                 repl->hook_entry[NF_IP_POST_ROUTING]);
1261         DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
1262                 repl->underflow[NF_IP_PRE_ROUTING],
1263                 repl->underflow[NF_IP_LOCAL_IN],
1264                 repl->underflow[NF_IP_FORWARD],
1265                 repl->underflow[NF_IP_LOCAL_OUT],
1266                 repl->underflow[NF_IP_POST_ROUTING]);
1267
1268         iterate_entries(repl->entries, repl->valid_hooks,
1269                         repl->hook_entry, repl->size, print_entry, dump_entry);
1270 }
1271
1272 static int iptables_get_entries(struct connman_iptables *table)
1273 {
1274         socklen_t entry_size;
1275
1276         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
1277
1278         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
1279                                 table->blob_entries, &entry_size);
1280 }
1281
1282 static int iptables_replace(struct connman_iptables *table,
1283                                         struct ipt_replace *r)
1284 {
1285         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
1286                          sizeof(*r) + r->size);
1287 }
1288
1289 static int add_entry(struct ipt_entry *entry, int builtin, unsigned int hook,
1290                         size_t size, unsigned offset, void *user_data)
1291 {
1292         struct connman_iptables *table = user_data;
1293         struct ipt_entry *new_entry;
1294
1295         new_entry = g_try_malloc0(entry->next_offset);
1296         if (new_entry == NULL)
1297                 return -ENOMEM;
1298
1299         memcpy(new_entry, entry, entry->next_offset);
1300
1301         return iptables_add_entry(table, new_entry, NULL, builtin);
1302 }
1303
1304 static void table_cleanup(struct connman_iptables *table)
1305 {
1306         GList *list;
1307         struct connman_iptables_entry *entry;
1308
1309         if (table == NULL)
1310                 return;
1311
1312         if (table->ipt_sock >= 0)
1313                 close(table->ipt_sock);
1314
1315         for (list = table->entries; list; list = list->next) {
1316                 entry = list->data;
1317
1318                 g_free(entry->entry);
1319                 g_free(entry);
1320         }
1321
1322         g_list_free(table->entries);
1323         g_free(table->info);
1324         g_free(table->blob_entries);
1325         g_free(table);
1326 }
1327
1328 static struct connman_iptables *iptables_init(const char *table_name)
1329 {
1330         struct connman_iptables *table = NULL;
1331         char *module = NULL;
1332         socklen_t s;
1333
1334         if (table_name == NULL)
1335                 table_name = "filter";
1336
1337         DBG("%s", table_name);
1338
1339         if (xtables_insmod("ip_tables", NULL, TRUE) != 0)
1340                 DBG("ip_tables module loading gives error but trying anyway");
1341
1342         module = g_strconcat("iptable_", table_name, NULL);
1343         if (module == NULL)
1344                 return NULL;
1345
1346         if (xtables_insmod(module, NULL, TRUE) != 0)
1347                 DBG("%s module loading gives error but trying anyway", module);
1348
1349         g_free(module);
1350
1351         table = g_hash_table_lookup(table_hash, table_name);
1352         if (table != NULL)
1353                 return table;
1354
1355         table = g_try_new0(struct connman_iptables, 1);
1356         if (table == NULL)
1357                 return NULL;
1358
1359         table->info = g_try_new0(struct ipt_getinfo, 1);
1360         if (table->info == NULL)
1361                 goto err;
1362
1363         table->ipt_sock = socket(AF_INET, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_RAW);
1364         if (table->ipt_sock < 0)
1365                 goto err;
1366
1367         s = sizeof(*table->info);
1368         strcpy(table->info->name, table_name);
1369         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
1370                                                 table->info, &s) < 0) {
1371                 connman_error("iptables support missing error %d (%s)", errno,
1372                         strerror(errno));
1373                 goto err;
1374         }
1375
1376         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
1377                                                 table->info->size);
1378         if (table->blob_entries == NULL)
1379                 goto err;
1380
1381         strcpy(table->blob_entries->name, table_name);
1382         table->blob_entries->size = table->info->size;
1383
1384         if (iptables_get_entries(table) < 0)
1385                 goto err;
1386
1387         table->num_entries = 0;
1388         table->old_entries = table->info->num_entries;
1389         table->size = 0;
1390
1391         memcpy(table->underflow, table->info->underflow,
1392                                 sizeof(table->info->underflow));
1393         memcpy(table->hook_entry, table->info->hook_entry,
1394                                 sizeof(table->info->hook_entry));
1395
1396         iterate_entries(table->blob_entries->entrytable,
1397                         table->info->valid_hooks, table->info->hook_entry,
1398                         table->blob_entries->size, add_entry, table);
1399
1400         g_hash_table_insert(table_hash, g_strdup(table_name), table);
1401
1402         if (debug_enabled == TRUE)
1403                 dump_table(table);
1404
1405         return table;
1406
1407 err:
1408         table_cleanup(table);
1409
1410         return NULL;
1411 }
1412
1413 static struct option iptables_opts[] = {
1414         {.name = "append",        .has_arg = 1, .val = 'A'},
1415         {.name = "compare",       .has_arg = 1, .val = 'C'},
1416         {.name = "delete",        .has_arg = 1, .val = 'D'},
1417         {.name = "flush-chain",   .has_arg = 1, .val = 'F'},
1418         {.name = "insert",        .has_arg = 1, .val = 'I'},
1419         {.name = "list",          .has_arg = 2, .val = 'L'},
1420         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
1421         {.name = "policy",        .has_arg = 1, .val = 'P'},
1422         {.name = "delete-chain",  .has_arg = 1, .val = 'X'},
1423         {.name = "destination",   .has_arg = 1, .val = 'd'},
1424         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
1425         {.name = "jump",          .has_arg = 1, .val = 'j'},
1426         {.name = "match",         .has_arg = 1, .val = 'm'},
1427         {.name = "out-interface", .has_arg = 1, .val = 'o'},
1428         {.name = "source",        .has_arg = 1, .val = 's'},
1429         {.name = "table",         .has_arg = 1, .val = 't'},
1430         {NULL},
1431 };
1432
1433 struct xtables_globals iptables_globals = {
1434         .option_offset = 0,
1435         .opts = iptables_opts,
1436         .orig_opts = iptables_opts,
1437 };
1438
1439 static struct xtables_target *prepare_target(struct connman_iptables *table,
1440                                                         const char *target_name)
1441 {
1442         struct xtables_target *xt_t = NULL;
1443         gboolean is_builtin, is_user_defined;
1444         GList *chain_head = NULL;
1445         size_t target_size;
1446
1447         is_builtin = FALSE;
1448         is_user_defined = FALSE;
1449
1450         if (is_builtin_target(target_name))
1451                 is_builtin = TRUE;
1452         else {
1453                 chain_head = find_chain_head(table, target_name);
1454                 if (chain_head != NULL && chain_head->next != NULL)
1455                         is_user_defined = TRUE;
1456         }
1457
1458         if (is_builtin || is_user_defined)
1459                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1460                                                 XTF_LOAD_MUST_SUCCEED);
1461         else
1462                 xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1463
1464         if (xt_t == NULL)
1465                 return NULL;
1466
1467         target_size = ALIGN(sizeof(struct ipt_entry_target)) + xt_t->size;
1468
1469         xt_t->t = g_try_malloc0(target_size);
1470         if (xt_t->t == NULL)
1471                 return NULL;
1472
1473         xt_t->t->u.target_size = target_size;
1474
1475         if (is_builtin || is_user_defined) {
1476                 struct xt_standard_target *target;
1477
1478                 target = (struct xt_standard_target *)(xt_t->t);
1479                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
1480
1481                 if (is_builtin == TRUE)
1482                         target->verdict = target_to_verdict(target_name);
1483                 else if (is_user_defined == TRUE) {
1484                         struct connman_iptables_entry *target_rule;
1485
1486                         if (chain_head == NULL) {
1487                                 g_free(xt_t->t);
1488                                 return NULL;
1489                         }
1490
1491                         target_rule = chain_head->next->data;
1492                         target->verdict = target_rule->offset;
1493                 }
1494         } else {
1495                 strcpy(xt_t->t->u.user.name, target_name);
1496                 xt_t->t->u.user.revision = xt_t->revision;
1497                 if (xt_t->init != NULL)
1498                         xt_t->init(xt_t->t);
1499         }
1500
1501 #if XTABLES_VERSION_CODE > 5
1502         if (xt_t->x6_options != NULL)
1503                 iptables_globals.opts =
1504                         xtables_options_xfrm(
1505                                 iptables_globals.orig_opts,
1506                                 iptables_globals.opts,
1507                                 xt_t->x6_options,
1508                                 &xt_t->option_offset);
1509         else
1510 #endif
1511                 iptables_globals.opts =
1512                         xtables_merge_options(
1513 #if XTABLES_VERSION_CODE > 5
1514                                 iptables_globals.orig_opts,
1515 #endif
1516                                 iptables_globals.opts,
1517                                 xt_t->extra_opts,
1518                                 &xt_t->option_offset);
1519
1520         if (iptables_globals.opts == NULL) {
1521                 g_free(xt_t->t);
1522                 xt_t = NULL;
1523         }
1524
1525         return xt_t;
1526 }
1527
1528 static struct xtables_match *prepare_matches(struct connman_iptables *table,
1529                                         struct xtables_rule_match **xt_rm,
1530                                         const char *match_name)
1531 {
1532         struct xtables_match *xt_m;
1533         size_t match_size;
1534
1535         if (match_name == NULL)
1536                 return NULL;
1537
1538         xt_m = xtables_find_match(match_name, XTF_LOAD_MUST_SUCCEED, xt_rm);
1539         match_size = ALIGN(sizeof(struct ipt_entry_match)) + xt_m->size;
1540
1541         xt_m->m = g_try_malloc0(match_size);
1542         if (xt_m->m == NULL)
1543                 return NULL;
1544
1545         xt_m->m->u.match_size = match_size;
1546         strcpy(xt_m->m->u.user.name, xt_m->name);
1547         xt_m->m->u.user.revision = xt_m->revision;
1548
1549         if (xt_m->init != NULL)
1550                 xt_m->init(xt_m->m);
1551
1552         if (xt_m == xt_m->next)
1553                 goto done;
1554
1555 #if XTABLES_VERSION_CODE > 5
1556         if (xt_m->x6_options != NULL)
1557                 iptables_globals.opts =
1558                         xtables_options_xfrm(
1559                                 iptables_globals.orig_opts,
1560                                 iptables_globals.opts,
1561                                 xt_m->x6_options,
1562                                 &xt_m->option_offset);
1563         else
1564 #endif
1565                         iptables_globals.opts =
1566                         xtables_merge_options(
1567 #if XTABLES_VERSION_CODE > 5
1568                                 iptables_globals.orig_opts,
1569 #endif
1570                                 iptables_globals.opts,
1571                                 xt_m->extra_opts,
1572                                 &xt_m->option_offset);
1573
1574         if (iptables_globals.opts == NULL) {
1575                 g_free(xt_m->m);
1576                 xt_m = NULL;
1577         }
1578
1579 done:
1580         return xt_m;
1581 }
1582
1583 static int parse_ip_and_mask(const char *str, struct in_addr *ip, struct in_addr *mask)
1584 {
1585         char **tokens;
1586         uint32_t prefixlength;
1587         uint32_t tmp;
1588         int err;
1589
1590         tokens = g_strsplit(str, "/", 2);
1591         if (tokens == NULL)
1592                 return -1;
1593
1594         if (!inet_pton(AF_INET, tokens[0], ip)) {
1595                 err = -1;
1596                 goto out;
1597         }
1598
1599         if (tokens[1] != NULL) {
1600                 prefixlength = strtol(tokens[1], NULL, 10);
1601                 if (prefixlength > 31) {
1602                         err = -1;
1603                         goto out;
1604                 }
1605
1606                 tmp = ~(0xffffffff >> prefixlength);
1607         } else {
1608                 tmp = 0xffffffff;
1609         }
1610
1611         mask->s_addr = htonl(tmp);
1612         ip->s_addr = ip->s_addr & mask->s_addr;
1613         err = 0;
1614 out:
1615         g_strfreev(tokens);
1616
1617         return err;
1618 }
1619
1620 static struct connman_iptables *pre_load_table(const char *table_name,
1621                                         struct connman_iptables *table)
1622 {
1623         if (table != NULL)
1624                 return table;
1625
1626         return iptables_init(table_name);
1627 }
1628
1629 static void clear_tables_flags(void)
1630 {
1631         struct xtables_match *xt_m;
1632         struct xtables_target *xt_t;
1633
1634         /*
1635          * Clear all flags because the flags are only valid
1636          * for one rule.
1637          */
1638         for (xt_m = xtables_matches; xt_m != NULL; xt_m = xt_m->next)
1639                 xt_m->mflags = 0;
1640
1641         for (xt_t = xtables_targets; xt_t != NULL; xt_t = xt_t->next) {
1642                 xt_t->tflags = 0;
1643                 xt_t->used = 0;
1644         }
1645 }
1646
1647 struct parse_context {
1648         int argc;
1649         char **argv;
1650         struct ipt_ip *ip;
1651         struct xtables_target *xt_t;
1652         struct xtables_match *xt_m;
1653         struct xtables_rule_match *xt_rm;
1654 };
1655
1656 static int prepare_getopt_args(const char *str, struct parse_context *ctx)
1657 {
1658         char **tokens;
1659         int i;
1660
1661         tokens = g_strsplit_set(str, " ", -1);
1662
1663         for (i = 0; tokens[i]; i++);
1664
1665         /* Add space for the argv[0] value */
1666         ctx->argc = i + 1;
1667
1668         /* Don't forget the last NULL entry */
1669         ctx->argv = g_try_malloc0((ctx->argc + 1) * sizeof(char *));
1670         if (ctx->argv == NULL) {
1671                 g_strfreev(tokens);
1672                 return -ENOMEM;
1673         }
1674
1675         /*
1676          * getopt_long() jumps over the first token; we need to add some
1677          * random argv[0] entry.
1678          */
1679         ctx->argv[0] = g_strdup("argh");
1680         for (i = 1; i < ctx->argc; i++)
1681                 ctx->argv[i] = tokens[i - 1];
1682
1683         return 0;
1684 }
1685
1686 #if XTABLES_VERSION_CODE > 5
1687
1688 static int parse_xt_modules(int c, connman_bool_t invert,
1689                                 struct parse_context *ctx)
1690 {
1691         struct xtables_match *m;
1692         struct xtables_rule_match *rm;
1693
1694         DBG("xtables version code > 5");
1695
1696         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
1697                 if (rm->completed != 0)
1698                         continue;
1699
1700                 m = rm->match;
1701
1702                 if (m->x6_parse == NULL && m->parse == NULL)
1703                         continue;
1704
1705                 if (c < (int) m->option_offset ||
1706                                 c >= (int) m->option_offset
1707                                         + XT_OPTION_OFFSET_SCALE)
1708                         continue;
1709
1710                 xtables_option_mpcall(c, ctx->argv, invert, m, NULL);
1711         }
1712
1713         if (ctx->xt_t == NULL)
1714                 return 0;
1715
1716         if (ctx->xt_t->x6_parse == NULL && ctx->xt_t->parse == NULL)
1717                 return 0;
1718
1719         if (c < (int) ctx->xt_t->option_offset ||
1720                         c >= (int) ctx->xt_t->option_offset
1721                                         + XT_OPTION_OFFSET_SCALE)
1722                 return 0;
1723
1724         xtables_option_tpcall(c, ctx->argv, invert, ctx->xt_t, NULL);
1725
1726         return 0;
1727 }
1728
1729 static int final_check_xt_modules(struct parse_context *ctx)
1730 {
1731         struct xtables_rule_match *rm;
1732
1733         DBG("xtables version code > 5");
1734
1735         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
1736                 xtables_option_mfcall(rm->match);
1737
1738         if (ctx->xt_t != NULL)
1739                 xtables_option_tfcall(ctx->xt_t);
1740
1741         return 0;
1742 }
1743
1744 #else
1745
1746 static int parse_xt_modules(int c, connman_bool_t invert,
1747                                 struct parse_context *ctx)
1748 {
1749         struct xtables_match *m;
1750         struct xtables_rule_match *rm;
1751         int err;
1752
1753         DBG("xtables version code <= 5");
1754
1755         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
1756                 if (rm->completed == 1)
1757                         continue;
1758
1759                 m = rm->match;
1760
1761                 if (m->parse == NULL)
1762                         continue;
1763
1764                 err = m->parse(c - m->option_offset,
1765                                 argv, invert, &m->mflags,
1766                                 NULL, &m->m);
1767                 if (err > 0)
1768                         return -err;
1769         }
1770
1771         if (ctx->xt_t == NULL)
1772                 return 0;
1773
1774         if (ctx->xt_t->parse == NULL)
1775                 return 0;
1776
1777         err = ctx->xt_m->parse(c - ctx->xt_m->option_offset,
1778                                 ctx->argv, invert, &ctx->xt_m->mflags,
1779                                 NULL, &ctx->xt_m->m);
1780         return -err;
1781 }
1782
1783 static int final_check_xt_modules(struct parse_context *ctx)
1784 {
1785         struct xtables_rule_match *rm;
1786
1787         DBG("xtables version code <= 5");
1788
1789         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
1790                 if (rm->match->final_check != NULL)
1791                         rm->match->final_check(rm->match->mflags);
1792
1793         if (ctx->xt_t != NULL && ctx->xt_t->final_check != NULL)
1794                 ctx->xt_t->final_check(ctx->xt_t->tflags);
1795
1796         return 0;
1797 }
1798
1799 #endif
1800
1801 static int parse_rule_spec(struct connman_iptables *table,
1802                                 struct parse_context *ctx)
1803 {
1804         /*
1805          * How the parser works:
1806          *
1807          *  - If getopt finds 's', 'd', 'i', 'o'.
1808          *    just extract the information.
1809          *  - if '!' is found, set the invert flag to true and
1810          *    removes the '!' from the optarg string and jumps
1811          *    back to getopt to reparse the current optarg string.
1812          *    After reparsing the invert flag is reseted to false.
1813          *  - If 'm' or 'j' is found then call either
1814          *    prepare_matches() or prepare_target(). Those function
1815          *    will modify (extend) the longopts for getopt_long.
1816          *    That means getopt will change its matching context according
1817          *    the loaded target.
1818          *
1819          *    Here an example with iptables-test
1820          *
1821          *    argv[0] = ./tools/iptables-test
1822          *    argv[1] = -t
1823          *    argv[2] = filter
1824          *    argv[3] = -A
1825          *    argv[4] = INPUT
1826          *    argv[5] = -m
1827          *    argv[6] = mark
1828          *    argv[7] = --mark
1829          *    argv[8] = 999
1830          *    argv[9] = -j
1831          *    argv[10] = LOG
1832          *
1833          *    getopt found 'm' then the optarg is "mark" and optind 7
1834          *    The longopts array containts before hitting the `case 'm'`
1835          *
1836          *    val A has_arg 1 name append
1837          *    val C has_arg 1 name compare
1838          *    val D has_arg 1 name delete
1839          *    val F has_arg 1 name flush-chain
1840          *    val I has_arg 1 name insert
1841          *    val L has_arg 2 name list
1842          *    val N has_arg 1 name new-chain
1843          *    val P has_arg 1 name policy
1844          *    val X has_arg 1 name delete-chain
1845          *    val d has_arg 1 name destination
1846          *    val i has_arg 1 name in-interface
1847          *    val j has_arg 1 name jump
1848          *    val m has_arg 1 name match
1849          *    val o has_arg 1 name out-interface
1850          *    val s has_arg 1 name source
1851          *    val t has_arg 1 name table
1852          *
1853          *    After executing the `case 'm'` block longopts is
1854          *
1855          *    val A has_arg 1 name append
1856          *    val C has_arg 1 name compare
1857          *    val D has_arg 1 name delete
1858          *    val F has_arg 1 name flush-chain
1859          *    val I has_arg 1 name insert
1860          *    val L has_arg 2 name list
1861          *    val N has_arg 1 name new-chain
1862          *    val P has_arg 1 name policy
1863          *    val X has_arg 1 name delete-chain
1864          *    val d has_arg 1 name destination
1865          *    val i has_arg 1 name in-interface
1866          *    val j has_arg 1 name jump
1867          *    val m has_arg 1 name match
1868          *    val o has_arg 1 name out-interface
1869          *    val s has_arg 1 name source
1870          *    val t has_arg 1 name table
1871          *    val   has_arg 1 name mark
1872          *
1873          *    So the 'mark' matcher has added the 'mark' options
1874          *    and getopt will then return c '256' optarg "999" optind 9
1875          *    And we will hit the 'default' statement which then
1876          *    will call the matchers parser (xt_m->parser() or
1877          *    xtables_option_mpcall() depending on which version
1878          *    of libxtables is found.
1879          */
1880         connman_bool_t invert = FALSE;
1881         int len, c, err;
1882
1883         DBG("");
1884
1885         ctx->ip = g_try_new0(struct ipt_ip, 1);
1886         if (ctx->ip == NULL)
1887                 return -ENOMEM;
1888
1889         /*
1890          * As side effect parsing a rule sets some global flags
1891          * which will be evaluated/verified. Let's reset them
1892          * to ensure we can parse more than one rule.
1893          */
1894         clear_tables_flags();
1895
1896         /*
1897          * Tell getopt_long not to generate error messages for unknown
1898          * options and also reset optind back to 0.
1899          */
1900         opterr = 0;
1901         optind = 0;
1902
1903         while ((c = getopt_long(ctx->argc, ctx->argv,
1904                                         "-:d:i:o:s:m:j:",
1905                                         iptables_globals.opts, NULL)) != -1) {
1906                 switch (c) {
1907                 case 's':
1908                         /* Source specification */
1909                         if (!parse_ip_and_mask(optarg,
1910                                                 &ctx->ip->src,
1911                                                 &ctx->ip->smsk))
1912                                 break;
1913
1914                         if (invert)
1915                                 ctx->ip->invflags |= IPT_INV_SRCIP;
1916
1917                         break;
1918                 case 'd':
1919                         /* Destination specification */
1920                         if (!parse_ip_and_mask(optarg,
1921                                                 &ctx->ip->dst,
1922                                                 &ctx->ip->dmsk))
1923                                 break;
1924
1925                         if (invert)
1926                                 ctx->ip->invflags |= IPT_INV_DSTIP;
1927                         break;
1928                 case 'i':
1929                         /* In interface specification */
1930                         len = strlen(optarg);
1931
1932                         if (len + 1 > IFNAMSIZ)
1933                                 break;
1934
1935                         strcpy(ctx->ip->iniface, optarg);
1936                         memset(ctx->ip->iniface_mask, 0xff, len + 1);
1937
1938                         if (invert)
1939                                 ctx->ip->invflags |= IPT_INV_VIA_IN;
1940
1941                         break;
1942                 case 'o':
1943                         /* Out interface specification */
1944                         len = strlen(optarg);
1945
1946                         if (len + 1 > IFNAMSIZ)
1947                                 break;
1948
1949                         strcpy(ctx->ip->outiface, optarg);
1950                         memset(ctx->ip->outiface_mask, 0xff, len + 1);
1951
1952                         if (invert)
1953                                 ctx->ip->invflags |= IPT_INV_VIA_OUT;
1954
1955                         break;
1956                 case 'm':
1957                         /* Matches */
1958                         ctx->xt_m = prepare_matches(table, &ctx->xt_rm, optarg);
1959                         if (ctx->xt_m == NULL) {
1960                                 err = -EINVAL;
1961                                 goto out;
1962                         }
1963
1964                         break;
1965                 case 'j':
1966                         /* Target */
1967                         ctx->xt_t = prepare_target(table, optarg);
1968                         if (ctx->xt_t == NULL) {
1969                                 err = -EINVAL;
1970                                 goto out;
1971                         }
1972
1973                         break;
1974                 case 1:
1975                         if (optarg[0] == '!' && optarg[1] == '\0') {
1976                                 invert = TRUE;
1977
1978                                 /* Remove the '!' from the optarg */
1979                                 optarg[0] = '\0';
1980
1981                                 /*
1982                                  * And recall getopt_long without reseting
1983                                  * invert.
1984                                  */
1985                                 continue;
1986                         }
1987
1988                         break;
1989                 default:
1990                         err = parse_xt_modules(c, invert, ctx);
1991                         if (err == 1)
1992                                 continue;
1993
1994                         break;
1995                 }
1996
1997                 invert = FALSE;
1998         }
1999
2000         err = final_check_xt_modules(ctx);
2001
2002 out:
2003         return err;
2004 }
2005
2006 static void cleanup_parse_context(struct parse_context *ctx)
2007 {
2008         g_strfreev(ctx->argv);
2009         g_free(ctx->ip);
2010         if (ctx->xt_t != NULL)
2011                 g_free(ctx->xt_t->t);
2012         if (ctx->xt_m != NULL)
2013                 g_free(ctx->xt_m->m);
2014         g_free(ctx);
2015 }
2016
2017 int __connman_iptables_new_chain(const char *table_name,
2018                                         const char *chain)
2019 {
2020         struct connman_iptables *table;
2021
2022         DBG("-t %s -N %s", table_name, chain);
2023
2024         table = pre_load_table(table_name, NULL);
2025         if (table == NULL)
2026                 return -EINVAL;
2027
2028         return iptables_add_chain(table, chain);
2029 }
2030
2031 int __connman_iptables_delete_chain(const char *table_name,
2032                                         const char *chain)
2033 {
2034         struct connman_iptables *table;
2035
2036         DBG("-t %s -X %s", table_name, chain);
2037
2038         table = pre_load_table(table_name, NULL);
2039         if (table == NULL)
2040                 return -EINVAL;
2041
2042         return iptables_delete_chain(table, chain);
2043 }
2044
2045 int __connman_iptables_flush_chain(const char *table_name,
2046                                         const char *chain)
2047 {
2048         struct connman_iptables *table;
2049
2050         DBG("-t %s -F %s", table_name, chain);
2051
2052         table = pre_load_table(table_name, NULL);
2053         if (table == NULL)
2054                 return -EINVAL;
2055
2056         return iptables_flush_chain(table, chain);
2057 }
2058
2059 int __connman_iptables_change_policy(const char *table_name,
2060                                         const char *chain,
2061                                         const char *policy)
2062 {
2063         struct connman_iptables *table;
2064
2065         DBG("-t %s -F %s", table_name, chain);
2066
2067         table = pre_load_table(table_name, NULL);
2068         if (table == NULL)
2069                 return -EINVAL;
2070
2071         return iptables_change_policy(table, chain, policy);
2072 }
2073
2074 int __connman_iptables_append(const char *table_name,
2075                                 const char *chain,
2076                                 const char *rule_spec)
2077 {
2078         struct connman_iptables *table;
2079         struct parse_context *ctx;
2080         const char *target_name;
2081         int err;
2082
2083         ctx = g_try_new0(struct parse_context, 1);
2084         if (ctx == NULL)
2085                 return -ENOMEM;
2086
2087         DBG("-t %s -A %s %s", table_name, chain, rule_spec);
2088
2089         err = prepare_getopt_args(rule_spec, ctx);
2090         if (err < 0)
2091                 goto out;
2092
2093         table = pre_load_table(table_name, NULL);
2094         if (table == NULL) {
2095                 err = -EINVAL;
2096                 goto out;
2097         }
2098
2099         err = parse_rule_spec(table, ctx);
2100         if (err < 0)
2101                 goto out;
2102
2103         if (ctx->xt_t == NULL)
2104                 target_name = NULL;
2105         else
2106                 target_name = ctx->xt_t->name;
2107
2108         err = iptables_insert_rule(table, ctx->ip, chain,
2109                                 target_name, ctx->xt_t, ctx->xt_rm);
2110 out:
2111         cleanup_parse_context(ctx);
2112
2113         return err;
2114 }
2115
2116 int __connman_iptables_delete(const char *table_name,
2117                                 const char *chain,
2118                                 const char *rule_spec)
2119 {
2120         struct connman_iptables *table;
2121         struct parse_context *ctx;
2122         const char *target_name;
2123         int err;
2124
2125         ctx = g_try_new0(struct parse_context, 1);
2126         if (ctx == NULL)
2127                 return -ENOMEM;
2128
2129         DBG("-t %s -D %s %s", table_name, chain, rule_spec);
2130
2131         err = prepare_getopt_args(rule_spec, ctx);
2132         if (err < 0)
2133                 goto out;
2134
2135         table = pre_load_table(table_name, NULL);
2136         if (table == NULL) {
2137                 err = -EINVAL;
2138                 goto out;
2139         }
2140
2141         err = parse_rule_spec(table, ctx);
2142         if (err < 0)
2143                 goto out;
2144
2145         if (ctx->xt_t == NULL)
2146                 target_name = NULL;
2147         else
2148                 target_name = ctx->xt_t->name;
2149
2150         err = iptables_delete_rule(table, ctx->ip, chain,
2151                                 target_name, ctx->xt_t, ctx->xt_m,
2152                                 ctx->xt_rm);
2153 out:
2154         cleanup_parse_context(ctx);
2155
2156         return err;
2157 }
2158
2159 int __connman_iptables_commit(const char *table_name)
2160 {
2161         struct connman_iptables *table;
2162         struct ipt_replace *repl;
2163         int err;
2164
2165         DBG("%s", table_name);
2166
2167         table = g_hash_table_lookup(table_hash, table_name);
2168         if (table == NULL)
2169                 return -EINVAL;
2170
2171         repl = iptables_blob(table);
2172
2173         if (debug_enabled == TRUE)
2174                 dump_ipt_replace(repl);
2175
2176         err = iptables_replace(table, repl);
2177
2178         g_free(repl->counters);
2179         g_free(repl);
2180
2181         if (err < 0)
2182             return err;
2183
2184         g_hash_table_remove(table_hash, table_name);
2185
2186         return 0;
2187 }
2188
2189 static void remove_table(gpointer user_data)
2190 {
2191         struct connman_iptables *table = user_data;
2192
2193         table_cleanup(table);
2194 }
2195
2196 static int flush_table_cb(struct ipt_entry *entry, int builtin,
2197                                 unsigned int hook, size_t size,
2198                                 unsigned int offset, void *user_data)
2199 {
2200         GSList **chains = user_data;
2201         struct xt_entry_target *target;
2202         char *name;
2203
2204         if (offset + entry->next_offset == size)
2205                 return 0;
2206
2207         target = ipt_get_target(entry);
2208
2209         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
2210                 name = g_strdup((const char*)target->data);
2211         else if (builtin >= 0)
2212                   name = g_strdup(hooknames[builtin]);
2213         else
2214                 return 0;
2215
2216         *chains = g_slist_prepend(*chains, name);
2217
2218         return 0;
2219 }
2220
2221 static void flush_table(const char *name)
2222 {
2223         GSList *chains = NULL, *list;
2224         struct connman_iptables *table;
2225
2226         table = pre_load_table(name, NULL);
2227         if (table == NULL)
2228                 return;
2229
2230         iterate_entries(table->blob_entries->entrytable,
2231                         table->info->valid_hooks,
2232                         table->info->hook_entry,
2233                         table->blob_entries->size,
2234                         flush_table_cb, &chains);
2235
2236         for (list = chains; list != NULL; list = list->next) {
2237                 char *chain = list->data;
2238
2239                 DBG("chain %s", chain);
2240                 iptables_flush_chain(table, chain);
2241         }
2242
2243         __connman_iptables_commit(name);
2244         g_slist_free_full(chains, g_free);
2245 }
2246
2247 static void flush_all_chains(void)
2248 {
2249         flush_table("filter");
2250         flush_table("mangle");
2251         flush_table("nat");
2252 }
2253
2254 int __connman_iptables_init(void)
2255 {
2256         DBG("");
2257
2258         if (getenv("CONNMAN_IPTABLES_DEBUG"))
2259                 debug_enabled = TRUE;
2260
2261         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
2262                                                 g_free, remove_table);
2263
2264         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
2265
2266         flush_all_chains();
2267
2268         return 0;
2269 }
2270
2271 void __connman_iptables_cleanup(void)
2272 {
2273         DBG("");
2274
2275         g_hash_table_destroy(table_hash);
2276
2277         xtables_free_opts(1);
2278 }