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