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