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