iptables: Allocated memory blocks are already zerod out
[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         entry_head->target_offset = sizeof(struct ipt_entry);
617         entry_head->next_offset = entry_head_size;
618
619         error = (struct error_target *) entry_head->elems;
620         g_stpcpy(error->t.u.user.name, IPT_ERROR_TARGET);
621         error->t.u.user.target_size = ALIGN(sizeof(struct error_target));
622         g_stpcpy(error->error, name);
623
624         if (iptables_add_entry(table, entry_head, last, -1) < 0)
625                 goto err_head;
626
627         /* tail entry */
628         entry_return_size = sizeof(struct ipt_entry) +
629                                 sizeof(struct ipt_standard_target);
630         entry_return = g_try_malloc0(entry_return_size);
631         if (entry_return == NULL)
632                 goto err;
633
634         entry_return->target_offset = sizeof(struct ipt_entry);
635         entry_return->next_offset = entry_return_size;
636
637         standard = (struct ipt_standard_target *) entry_return->elems;
638         standard->target.u.user.target_size =
639                                 ALIGN(sizeof(struct ipt_standard_target));
640         standard->verdict = XT_RETURN;
641
642         if (iptables_add_entry(table, entry_return, last, -1) < 0)
643                 goto err;
644
645         return 0;
646
647 err:
648         g_free(entry_return);
649 err_head:
650         g_free(entry_head);
651
652         return -ENOMEM;
653 }
654
655 static int iptables_delete_chain(struct connman_iptables *table,
656                                         const char *name)
657 {
658         struct connman_iptables_entry *entry;
659         GList *chain_head, *chain_tail;
660
661         DBG("table %s chain %s", table->name, name);
662
663         chain_head = find_chain_head(table, name);
664         if (chain_head == NULL)
665                 return -EINVAL;
666
667         entry = chain_head->data;
668
669         /* We cannot remove builtin chain */
670         if (entry->builtin >= 0)
671                 return -EINVAL;
672
673         chain_tail = find_chain_tail(table, name);
674         if (chain_tail == NULL)
675                 return -EINVAL;
676
677         /* Chain must be flushed */
678         if (chain_head->next != chain_tail->prev)
679                 return -EINVAL;
680
681         remove_table_entry(table, entry);
682
683         entry = chain_tail->prev->data;
684         remove_table_entry(table, entry);
685
686         update_offsets(table);
687
688         return 0;
689 }
690
691 static struct ipt_entry *new_rule(struct ipt_ip *ip,
692                 const char *target_name, struct xtables_target *xt_t,
693                 struct xtables_rule_match *xt_rm)
694 {
695         struct xtables_rule_match *tmp_xt_rm;
696         struct ipt_entry *new_entry;
697         size_t match_size, target_size;
698
699         match_size = 0;
700         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL; tmp_xt_rm = tmp_xt_rm->next)
701                 match_size += tmp_xt_rm->match->m->u.match_size;
702
703         if (xt_t)
704                 target_size = ALIGN(xt_t->t->u.target_size);
705         else
706                 target_size = ALIGN(sizeof(struct xt_standard_target));
707
708         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
709                                                                 match_size);
710         if (new_entry == NULL)
711                 return NULL;
712
713         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
714
715         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
716         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
717                                                                 match_size;
718
719         match_size = 0;
720         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
721                                 tmp_xt_rm = tmp_xt_rm->next) {
722                 memcpy(new_entry->elems + match_size, tmp_xt_rm->match->m,
723                                         tmp_xt_rm->match->m->u.match_size);
724                 match_size += tmp_xt_rm->match->m->u.match_size;
725         }
726
727         if (xt_t) {
728                 struct xt_entry_target *entry_target;
729
730                 entry_target = ipt_get_target(new_entry);
731                 memcpy(entry_target, xt_t->t, target_size);
732         }
733
734         return new_entry;
735 }
736
737 static void update_hooks(struct connman_iptables *table, GList *chain_head,
738                                 struct ipt_entry *entry)
739 {
740         GList *list;
741         struct connman_iptables_entry *head, *e;
742         int builtin;
743
744         if (chain_head == NULL)
745                 return;
746
747         head = chain_head->data;
748
749         builtin = head->builtin;
750         if (builtin < 0)
751                 return;
752
753         table->underflow[builtin] += entry->next_offset;
754
755         for (list = chain_head->next; list; list = list->next) {
756                 e = list->data;
757
758                 builtin = e->builtin;
759                 if (builtin < 0)
760                         continue;
761
762                 table->hook_entry[builtin] += entry->next_offset;
763                 table->underflow[builtin] += entry->next_offset;
764         }
765 }
766
767 static struct ipt_entry *prepare_rule_inclusion(struct connman_iptables *table,
768                                 struct ipt_ip *ip, const char *chain_name,
769                                 const char *target_name,
770                                 struct xtables_target *xt_t,
771                                 int *builtin, struct xtables_rule_match *xt_rm)
772 {
773         GList *chain_tail, *chain_head;
774         struct ipt_entry *new_entry;
775         struct connman_iptables_entry *head;
776
777         chain_head = find_chain_head(table, chain_name);
778         if (chain_head == NULL)
779                 return NULL;
780
781         chain_tail = find_chain_tail(table, chain_name);
782         if (chain_tail == NULL)
783                 return NULL;
784
785         new_entry = new_rule(ip, target_name, xt_t, xt_rm);
786         if (new_entry == NULL)
787                 return NULL;
788
789         update_hooks(table, chain_head, new_entry);
790
791         /*
792          * If the chain is builtin, and does not have any rule,
793          * then the one that we're inserting is becoming the head
794          * and thus needs the builtin flag.
795          */
796         head = chain_head->data;
797         if (head->builtin < 0)
798                 *builtin = -1;
799         else if (chain_head == chain_tail->prev) {
800                 *builtin = head->builtin;
801                 head->builtin = -1;
802         }
803
804         return new_entry;
805 }
806
807 static int iptables_append_rule(struct connman_iptables *table,
808                                 struct ipt_ip *ip, const char *chain_name,
809                                 const char *target_name,
810                                 struct xtables_target *xt_t,
811                                 struct xtables_rule_match *xt_rm)
812 {
813         struct ipt_entry *new_entry;
814         int builtin = -1, ret;
815         GList *chain_tail;
816
817         DBG("table %s chain %s", table->name, chain_name);
818
819         chain_tail = find_chain_tail(table, chain_name);
820         if (chain_tail == NULL)
821                 return -EINVAL;
822
823         new_entry = prepare_rule_inclusion(table, ip, chain_name,
824                                         target_name, xt_t, &builtin, xt_rm);
825         if (new_entry == NULL)
826                 return -EINVAL;
827
828         ret = iptables_add_entry(table, new_entry, chain_tail->prev, builtin);
829         if (ret < 0)
830                 g_free(new_entry);
831
832         return ret;
833 }
834
835 static gboolean is_same_ipt_entry(struct ipt_entry *i_e1,
836                                         struct ipt_entry *i_e2)
837 {
838         if (memcmp(&i_e1->ip, &i_e2->ip, sizeof(struct ipt_ip)) != 0)
839                 return FALSE;
840
841         if (i_e1->target_offset != i_e2->target_offset)
842                 return FALSE;
843
844         if (i_e1->next_offset != i_e2->next_offset)
845                 return FALSE;
846
847         return TRUE;
848 }
849
850 static gboolean is_same_target(struct xt_entry_target *xt_e_t1,
851                                         struct xt_entry_target *xt_e_t2)
852 {
853         unsigned int i;
854
855         if (xt_e_t1 == NULL || xt_e_t2 == NULL)
856                 return FALSE;
857
858         if (g_strcmp0(xt_e_t1->u.user.name, "") == 0 &&
859                         g_strcmp0(xt_e_t2->u.user.name, "") == 0) {
860                 /* fallthrough */
861                 return TRUE;
862         } else if (g_strcmp0(xt_e_t1->u.user.name, IPT_STANDARD_TARGET) == 0) {
863                 struct xt_standard_target *xt_s_t1;
864                 struct xt_standard_target *xt_s_t2;
865
866                 xt_s_t1 = (struct xt_standard_target *) xt_e_t1;
867                 xt_s_t2 = (struct xt_standard_target *) xt_e_t2;
868
869                 if (xt_s_t1->verdict != xt_s_t2->verdict)
870                         return FALSE;
871         } else {
872                 if (xt_e_t1->u.target_size != xt_e_t2->u.target_size)
873                         return FALSE;
874
875                 if (g_strcmp0(xt_e_t1->u.user.name, xt_e_t2->u.user.name) != 0)
876                         return FALSE;
877
878                 for (i = 0; i < xt_e_t1->u.target_size -
879                                 sizeof(struct xt_standard_target); i++) {
880                         if ((xt_e_t1->data[i] ^ xt_e_t2->data[i]) != 0)
881                                 return FALSE;
882                 }
883         }
884
885         return TRUE;
886 }
887
888 static gboolean is_same_match(struct xt_entry_match *xt_e_m1,
889                                 struct xt_entry_match *xt_e_m2)
890 {
891         unsigned int i;
892
893         if (xt_e_m1 == NULL || xt_e_m2 == NULL)
894                 return FALSE;
895
896         if (xt_e_m1->u.match_size != xt_e_m2->u.match_size)
897                 return FALSE;
898
899         if (xt_e_m1->u.user.revision != xt_e_m2->u.user.revision)
900                 return FALSE;
901
902         if (g_strcmp0(xt_e_m1->u.user.name, xt_e_m2->u.user.name) != 0)
903                 return FALSE;
904
905         for (i = 0; i < xt_e_m1->u.match_size - sizeof(struct xt_entry_match);
906                         i++) {
907                 if ((xt_e_m1->data[i] ^ xt_e_m2->data[i]) != 0)
908                         return FALSE;
909         }
910
911         return TRUE;
912 }
913
914 static GList *find_existing_rule(struct connman_iptables *table,
915                                 struct ipt_ip *ip, const char *chain_name,
916                                 const char *target_name,
917                                 struct xtables_target *xt_t,
918                                 struct xtables_match *xt_m,
919                                 struct xtables_rule_match *xt_rm)
920 {
921         GList *chain_tail, *chain_head, *list;
922         struct xt_entry_target *xt_e_t = NULL;
923         struct xt_entry_match *xt_e_m = NULL;
924         struct connman_iptables_entry *entry;
925         struct ipt_entry *entry_test;
926         int builtin;
927
928         chain_head = find_chain_head(table, chain_name);
929         if (chain_head == NULL)
930                 return NULL;
931
932         chain_tail = find_chain_tail(table, chain_name);
933         if (chain_tail == NULL)
934                 return NULL;
935
936         if (!xt_t && !xt_m)
937                 return NULL;
938
939         entry_test = new_rule(ip, target_name, xt_t, xt_rm);
940         if (entry_test == NULL)
941                 return NULL;
942
943         if (xt_t != NULL)
944                 xt_e_t = ipt_get_target(entry_test);
945         if (xt_m != NULL)
946                 xt_e_m = (struct xt_entry_match *)entry_test->elems;
947
948         entry = chain_head->data;
949         builtin = entry->builtin;
950
951         if (builtin >= 0)
952                 list = chain_head;
953         else
954                 list = chain_head->next;
955
956         for (; list != chain_tail->prev; list = list->next) {
957                 struct connman_iptables_entry *tmp;
958                 struct ipt_entry *tmp_e;
959
960                 tmp = list->data;
961                 tmp_e = tmp->entry;
962
963                 if (is_same_ipt_entry(entry_test, tmp_e) == FALSE)
964                         continue;
965
966                 if (xt_t != NULL) {
967                         struct xt_entry_target *tmp_xt_e_t;
968
969                         tmp_xt_e_t = ipt_get_target(tmp_e);
970
971                         if (!is_same_target(tmp_xt_e_t, xt_e_t))
972                                 continue;
973                 }
974
975                 if (xt_m != NULL) {
976                         struct xt_entry_match *tmp_xt_e_m;
977
978                         tmp_xt_e_m = (struct xt_entry_match *)tmp_e->elems;
979
980                         if (!is_same_match(tmp_xt_e_m, xt_e_m))
981                                 continue;
982                 }
983
984                 break;
985         }
986
987         g_free(entry_test);
988
989         if (list != chain_tail->prev)
990                 return list;
991
992         return NULL;
993 }
994
995 static int iptables_delete_rule(struct connman_iptables *table,
996                                 struct ipt_ip *ip, const char *chain_name,
997                                 const char *target_name,
998                                 struct xtables_target *xt_t,
999                                 struct xtables_match *xt_m,
1000                                 struct xtables_rule_match *xt_rm)
1001 {
1002         struct connman_iptables_entry *entry;
1003         GList *chain_head, *chain_tail, *list;
1004         int builtin, removed;
1005
1006         DBG("table %s chain %s", table->name, chain_name);
1007
1008         removed = 0;
1009
1010         chain_head = find_chain_head(table, chain_name);
1011         if (chain_head == NULL)
1012                 return -EINVAL;
1013
1014         chain_tail = find_chain_tail(table, chain_name);
1015         if (chain_tail == NULL)
1016                 return -EINVAL;
1017
1018         list = find_existing_rule(table, ip, chain_name, target_name,
1019                                                         xt_t, xt_m, xt_rm);
1020         if (list == NULL)
1021                 return -EINVAL;
1022
1023         entry = chain_head->data;
1024         builtin = entry->builtin;
1025
1026         if (builtin >= 0 && list == chain_head) {
1027                 /*
1028                  * We are about to remove the first rule in the
1029                  * chain. In this case we need to store the builtin
1030                  * value to the new chain_head.
1031                  *
1032                  * Note, for builtin chains, chain_head->next is
1033                  * always valid. A builtin chain has always a policy
1034                  * rule at the end.
1035                  */
1036                 chain_head = chain_head->next;
1037
1038                 entry = chain_head->data;
1039                 entry->builtin = builtin;
1040         }
1041
1042         entry = list->data;
1043         if (entry == NULL)
1044                 return -EINVAL;
1045
1046         /* We have deleted a rule,
1047          * all references should be bumped accordingly */
1048         if (list->next != NULL)
1049                 update_targets_reference(table, list->next->data,
1050                                                 list->data, TRUE);
1051
1052         removed += remove_table_entry(table, entry);
1053
1054         if (builtin >= 0)
1055                 delete_update_hooks(table, builtin, chain_head, removed);
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 *get_table(const char *table_name)
1672 {
1673         struct connman_iptables *table;
1674
1675         if (table_name == NULL)
1676                 table_name = "filter";
1677
1678         table = g_hash_table_lookup(table_hash, table_name);
1679         if (table != NULL)
1680                 return table;
1681
1682         table = iptables_init(table_name);
1683         if (table == NULL)
1684                 return NULL;
1685
1686         table->name = g_strdup(table_name);
1687         g_hash_table_replace(table_hash, table->name, table);
1688
1689         return table;
1690 }
1691
1692 struct parse_context {
1693         int argc;
1694         char **argv;
1695         struct ipt_ip *ip;
1696         struct xtables_target *xt_t;
1697         struct xtables_match *xt_m;
1698         struct xtables_rule_match *xt_rm;
1699 };
1700
1701 static int prepare_getopt_args(const char *str, struct parse_context *ctx)
1702 {
1703         char **tokens;
1704         int i;
1705
1706         tokens = g_strsplit_set(str, " ", -1);
1707
1708         i = g_strv_length(tokens);
1709
1710         /* Add space for the argv[0] value */
1711         ctx->argc = i + 1;
1712
1713         /* Don't forget the last NULL entry */
1714         ctx->argv = g_try_malloc0((ctx->argc + 1) * sizeof(char *));
1715         if (ctx->argv == NULL) {
1716                 g_strfreev(tokens);
1717                 return -ENOMEM;
1718         }
1719
1720         /*
1721          * getopt_long() jumps over the first token; we need to add some
1722          * random argv[0] entry.
1723          */
1724         ctx->argv[0] = g_strdup("argh");
1725         for (i = 1; i < ctx->argc; i++)
1726                 ctx->argv[i] = tokens[i - 1];
1727
1728         g_free(tokens);
1729
1730         return 0;
1731 }
1732
1733 static int parse_xt_modules(int c, connman_bool_t invert,
1734                                 struct parse_context *ctx)
1735 {
1736         struct xtables_match *m;
1737         struct xtables_rule_match *rm;
1738
1739         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
1740                 if (rm->completed != 0)
1741                         continue;
1742
1743                 m = rm->match;
1744
1745                 if (m->x6_parse == NULL && m->parse == NULL)
1746                         continue;
1747
1748                 if (c < (int) m->option_offset ||
1749                                 c >= (int) m->option_offset
1750                                         + XT_OPTION_OFFSET_SCALE)
1751                         continue;
1752
1753                 xtables_option_mpcall(c, ctx->argv, invert, m, NULL);
1754         }
1755
1756         if (ctx->xt_t == NULL)
1757                 return 0;
1758
1759         if (ctx->xt_t->x6_parse == NULL && ctx->xt_t->parse == NULL)
1760                 return 0;
1761
1762         if (c < (int) ctx->xt_t->option_offset ||
1763                         c >= (int) ctx->xt_t->option_offset
1764                                         + XT_OPTION_OFFSET_SCALE)
1765                 return 0;
1766
1767         xtables_option_tpcall(c, ctx->argv, invert, ctx->xt_t, NULL);
1768
1769         return 0;
1770 }
1771
1772 static int final_check_xt_modules(struct parse_context *ctx)
1773 {
1774         struct xtables_rule_match *rm;
1775
1776         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
1777                 xtables_option_mfcall(rm->match);
1778
1779         if (ctx->xt_t != NULL)
1780                 xtables_option_tfcall(ctx->xt_t);
1781
1782         return 0;
1783 }
1784
1785 static int parse_rule_spec(struct connman_iptables *table,
1786                                 struct parse_context *ctx)
1787 {
1788         /*
1789          * How the parser works:
1790          *
1791          *  - If getopt finds 's', 'd', 'i', 'o'.
1792          *    just extract the information.
1793          *  - if '!' is found, set the invert flag to true and
1794          *    removes the '!' from the optarg string and jumps
1795          *    back to getopt to reparse the current optarg string.
1796          *    After reparsing the invert flag is reseted to false.
1797          *  - If 'm' or 'j' is found then call either
1798          *    prepare_matches() or prepare_target(). Those function
1799          *    will modify (extend) the longopts for getopt_long.
1800          *    That means getopt will change its matching context according
1801          *    the loaded target.
1802          *
1803          *    Here an example with iptables-test
1804          *
1805          *    argv[0] = ./tools/iptables-test
1806          *    argv[1] = -t
1807          *    argv[2] = filter
1808          *    argv[3] = -A
1809          *    argv[4] = INPUT
1810          *    argv[5] = -m
1811          *    argv[6] = mark
1812          *    argv[7] = --mark
1813          *    argv[8] = 999
1814          *    argv[9] = -j
1815          *    argv[10] = LOG
1816          *
1817          *    getopt found 'm' then the optarg is "mark" and optind 7
1818          *    The longopts array containts before hitting the `case 'm'`
1819          *
1820          *    val A has_arg 1 name append
1821          *    val C has_arg 1 name compare
1822          *    val D has_arg 1 name delete
1823          *    val F has_arg 1 name flush-chain
1824          *    val I has_arg 1 name insert
1825          *    val L has_arg 2 name list
1826          *    val N has_arg 1 name new-chain
1827          *    val P has_arg 1 name policy
1828          *    val X has_arg 1 name delete-chain
1829          *    val d has_arg 1 name destination
1830          *    val i has_arg 1 name in-interface
1831          *    val j has_arg 1 name jump
1832          *    val m has_arg 1 name match
1833          *    val o has_arg 1 name out-interface
1834          *    val s has_arg 1 name source
1835          *    val t has_arg 1 name table
1836          *
1837          *    After executing the `case 'm'` block longopts is
1838          *
1839          *    val A has_arg 1 name append
1840          *    val C has_arg 1 name compare
1841          *    val D has_arg 1 name delete
1842          *    val F has_arg 1 name flush-chain
1843          *    val I has_arg 1 name insert
1844          *    val L has_arg 2 name list
1845          *    val N has_arg 1 name new-chain
1846          *    val P has_arg 1 name policy
1847          *    val X has_arg 1 name delete-chain
1848          *    val d has_arg 1 name destination
1849          *    val i has_arg 1 name in-interface
1850          *    val j has_arg 1 name jump
1851          *    val m has_arg 1 name match
1852          *    val o has_arg 1 name out-interface
1853          *    val s has_arg 1 name source
1854          *    val t has_arg 1 name table
1855          *    val   has_arg 1 name mark
1856          *
1857          *    So the 'mark' matcher has added the 'mark' options
1858          *    and getopt will then return c '256' optarg "999" optind 9
1859          *    And we will hit the 'default' statement which then
1860          *    will call the matchers parser (xt_m->parser() or
1861          *    xtables_option_mpcall() depending on which version
1862          *    of libxtables is found.
1863          */
1864         connman_bool_t invert = FALSE;
1865         int len, c, err;
1866
1867         ctx->ip = g_try_new0(struct ipt_ip, 1);
1868         if (ctx->ip == NULL)
1869                 return -ENOMEM;
1870
1871         /*
1872          * Tell getopt_long not to generate error messages for unknown
1873          * options and also reset optind back to 0.
1874          */
1875         opterr = 0;
1876         optind = 0;
1877
1878         while ((c = getopt_long(ctx->argc, ctx->argv,
1879                                         "-:d:i:o:s:m:j:",
1880                                         iptables_globals.opts, NULL)) != -1) {
1881                 switch (c) {
1882                 case 's':
1883                         /* Source specification */
1884                         if (!parse_ip_and_mask(optarg,
1885                                                 &ctx->ip->src,
1886                                                 &ctx->ip->smsk))
1887                                 break;
1888
1889                         if (invert)
1890                                 ctx->ip->invflags |= IPT_INV_SRCIP;
1891
1892                         break;
1893                 case 'd':
1894                         /* Destination specification */
1895                         if (!parse_ip_and_mask(optarg,
1896                                                 &ctx->ip->dst,
1897                                                 &ctx->ip->dmsk))
1898                                 break;
1899
1900                         if (invert)
1901                                 ctx->ip->invflags |= IPT_INV_DSTIP;
1902                         break;
1903                 case 'i':
1904                         /* In interface specification */
1905                         len = strlen(optarg);
1906
1907                         if (len + 1 > IFNAMSIZ)
1908                                 break;
1909
1910                         g_stpcpy(ctx->ip->iniface, optarg);
1911                         memset(ctx->ip->iniface_mask, 0xff, len + 1);
1912
1913                         if (invert)
1914                                 ctx->ip->invflags |= IPT_INV_VIA_IN;
1915
1916                         break;
1917                 case 'o':
1918                         /* Out interface specification */
1919                         len = strlen(optarg);
1920
1921                         if (len + 1 > IFNAMSIZ)
1922                                 break;
1923
1924                         g_stpcpy(ctx->ip->outiface, optarg);
1925                         memset(ctx->ip->outiface_mask, 0xff, len + 1);
1926
1927                         if (invert)
1928                                 ctx->ip->invflags |= IPT_INV_VIA_OUT;
1929
1930                         break;
1931                 case 'm':
1932                         /* Matches */
1933                         ctx->xt_m = prepare_matches(table, &ctx->xt_rm, optarg);
1934                         if (ctx->xt_m == NULL) {
1935                                 err = -EINVAL;
1936                                 goto out;
1937                         }
1938
1939                         break;
1940                 case 'j':
1941                         /* Target */
1942                         ctx->xt_t = prepare_target(table, optarg);
1943                         if (ctx->xt_t == NULL) {
1944                                 err = -EINVAL;
1945                                 goto out;
1946                         }
1947
1948                         break;
1949                 case 1:
1950                         if (optarg[0] == '!' && optarg[1] == '\0') {
1951                                 invert = TRUE;
1952
1953                                 /* Remove the '!' from the optarg */
1954                                 optarg[0] = '\0';
1955
1956                                 /*
1957                                  * And recall getopt_long without reseting
1958                                  * invert.
1959                                  */
1960                                 continue;
1961                         }
1962
1963                         break;
1964                 default:
1965                         err = parse_xt_modules(c, invert, ctx);
1966                         if (err == 1)
1967                                 continue;
1968
1969                         break;
1970                 }
1971
1972                 invert = FALSE;
1973         }
1974
1975         err = final_check_xt_modules(ctx);
1976
1977 out:
1978         return err;
1979 }
1980
1981 static void reset_xtables(void)
1982 {
1983         struct xtables_match *xt_m;
1984         struct xtables_target *xt_t;
1985
1986         /*
1987          * As side effect parsing a rule sets some global flags
1988          * which will be evaluated/verified. Let's reset them
1989          * to ensure we can parse more than one rule.
1990          *
1991          * Clear all flags because the flags are only valid
1992          * for one rule.
1993          */
1994         for (xt_m = xtables_matches; xt_m != NULL; xt_m = xt_m->next)
1995                 xt_m->mflags = 0;
1996
1997         for (xt_t = xtables_targets; xt_t != NULL; xt_t = xt_t->next) {
1998                 xt_t->tflags = 0;
1999                 xt_t->used = 0;
2000         }
2001
2002         /*
2003          * We need also to free the memory implicitly allocated
2004          * during parsing (see xtables_options_xfrm()).
2005          * Note xt_params is actually iptables_globals.
2006          */
2007         if (xt_params->opts != xt_params->orig_opts) {
2008                 g_free(xt_params->opts);
2009                 xt_params->opts = xt_params->orig_opts;
2010         }
2011         xt_params->option_offset = 0;
2012 }
2013
2014 static void cleanup_parse_context(struct parse_context *ctx)
2015 {
2016         struct xtables_rule_match *rm, *tmp;
2017
2018         g_strfreev(ctx->argv);
2019         g_free(ctx->ip);
2020         if (ctx->xt_t != NULL) {
2021                 g_free(ctx->xt_t->t);
2022                 ctx->xt_t->t = NULL;
2023         }
2024         if (ctx->xt_m != NULL) {
2025                 g_free(ctx->xt_m->m);
2026                 ctx->xt_m->m = NULL;
2027         }
2028         for (tmp = NULL, rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
2029                 if (tmp != NULL)
2030                         g_free(tmp);
2031                 tmp = rm;
2032         }
2033         g_free(tmp);
2034
2035         g_free(ctx);
2036 }
2037
2038 int __connman_iptables_dump(const char *table_name)
2039 {
2040         struct connman_iptables *table;
2041
2042         DBG("-t %s -L", table_name);
2043
2044         table = get_table(table_name);
2045         if (table == NULL)
2046                 return -EINVAL;
2047
2048         dump_table(table);
2049
2050         return 0;
2051 }
2052
2053 int __connman_iptables_new_chain(const char *table_name,
2054                                         const char *chain)
2055 {
2056         struct connman_iptables *table;
2057
2058         DBG("-t %s -N %s", table_name, chain);
2059
2060         table = get_table(table_name);
2061         if (table == NULL)
2062                 return -EINVAL;
2063
2064         return iptables_add_chain(table, chain);
2065 }
2066
2067 int __connman_iptables_delete_chain(const char *table_name,
2068                                         const char *chain)
2069 {
2070         struct connman_iptables *table;
2071
2072         DBG("-t %s -X %s", table_name, chain);
2073
2074         table = get_table(table_name);
2075         if (table == NULL)
2076                 return -EINVAL;
2077
2078         return iptables_delete_chain(table, chain);
2079 }
2080
2081 int __connman_iptables_flush_chain(const char *table_name,
2082                                         const char *chain)
2083 {
2084         struct connman_iptables *table;
2085
2086         DBG("-t %s -F %s", table_name, chain);
2087
2088         table = get_table(table_name);
2089         if (table == NULL)
2090                 return -EINVAL;
2091
2092         return iptables_flush_chain(table, chain);
2093 }
2094
2095 int __connman_iptables_change_policy(const char *table_name,
2096                                         const char *chain,
2097                                         const char *policy)
2098 {
2099         struct connman_iptables *table;
2100
2101         DBG("-t %s -F %s", table_name, chain);
2102
2103         table = get_table(table_name);
2104         if (table == NULL)
2105                 return -EINVAL;
2106
2107         return iptables_change_policy(table, chain, policy);
2108 }
2109
2110 int __connman_iptables_append(const char *table_name,
2111                                 const char *chain,
2112                                 const char *rule_spec)
2113 {
2114         struct connman_iptables *table;
2115         struct parse_context *ctx;
2116         const char *target_name;
2117         int err;
2118
2119         ctx = g_try_new0(struct parse_context, 1);
2120         if (ctx == NULL)
2121                 return -ENOMEM;
2122
2123         DBG("-t %s -A %s %s", table_name, chain, rule_spec);
2124
2125         err = prepare_getopt_args(rule_spec, ctx);
2126         if (err < 0)
2127                 goto out;
2128
2129         table = get_table(table_name);
2130         if (table == NULL) {
2131                 err = -EINVAL;
2132                 goto out;
2133         }
2134
2135         err = parse_rule_spec(table, ctx);
2136         if (err < 0)
2137                 goto out;
2138
2139         if (ctx->xt_t == NULL)
2140                 target_name = NULL;
2141         else
2142                 target_name = ctx->xt_t->name;
2143
2144         err = iptables_append_rule(table, ctx->ip, chain,
2145                                 target_name, ctx->xt_t, ctx->xt_rm);
2146 out:
2147         cleanup_parse_context(ctx);
2148         reset_xtables();
2149
2150         return err;
2151 }
2152
2153 int __connman_iptables_delete(const char *table_name,
2154                                 const char *chain,
2155                                 const char *rule_spec)
2156 {
2157         struct connman_iptables *table;
2158         struct parse_context *ctx;
2159         const char *target_name;
2160         int err;
2161
2162         ctx = g_try_new0(struct parse_context, 1);
2163         if (ctx == NULL)
2164                 return -ENOMEM;
2165
2166         DBG("-t %s -D %s %s", table_name, chain, rule_spec);
2167
2168         err = prepare_getopt_args(rule_spec, ctx);
2169         if (err < 0)
2170                 goto out;
2171
2172         table = get_table(table_name);
2173         if (table == NULL) {
2174                 err = -EINVAL;
2175                 goto out;
2176         }
2177
2178         err = parse_rule_spec(table, ctx);
2179         if (err < 0)
2180                 goto out;
2181
2182         if (ctx->xt_t == NULL)
2183                 target_name = NULL;
2184         else
2185                 target_name = ctx->xt_t->name;
2186
2187         err = iptables_delete_rule(table, ctx->ip, chain,
2188                                 target_name, ctx->xt_t, ctx->xt_m,
2189                                 ctx->xt_rm);
2190 out:
2191         cleanup_parse_context(ctx);
2192         reset_xtables();
2193
2194         return err;
2195 }
2196
2197 int __connman_iptables_commit(const char *table_name)
2198 {
2199         struct connman_iptables *table;
2200         struct ipt_replace *repl;
2201         int err;
2202
2203         DBG("%s", table_name);
2204
2205         table = g_hash_table_lookup(table_hash, table_name);
2206         if (table == NULL)
2207                 return -EINVAL;
2208
2209         repl = iptables_blob(table);
2210
2211         if (debug_enabled == TRUE)
2212                 dump_ipt_replace(repl);
2213
2214         err = iptables_replace(table, repl);
2215
2216         g_free(repl->counters);
2217         g_free(repl);
2218
2219         if (err < 0)
2220             return err;
2221
2222         g_hash_table_remove(table_hash, table_name);
2223
2224         return 0;
2225 }
2226
2227 static void remove_table(gpointer user_data)
2228 {
2229         struct connman_iptables *table = user_data;
2230
2231         table_cleanup(table);
2232 }
2233
2234 static int flush_table_cb(struct ipt_entry *entry, int builtin,
2235                                 unsigned int hook, size_t size,
2236                                 unsigned int offset, void *user_data)
2237 {
2238         GSList **chains = user_data;
2239         struct xt_entry_target *target;
2240         char *name;
2241
2242         if (offset + entry->next_offset == size)
2243                 return 0;
2244
2245         target = ipt_get_target(entry);
2246
2247         if (!g_strcmp0(target->u.user.name, IPT_ERROR_TARGET))
2248                 name = g_strdup((const char*)target->data);
2249         else if (builtin >= 0)
2250                   name = g_strdup(hooknames[builtin]);
2251         else
2252                 return 0;
2253
2254         *chains = g_slist_prepend(*chains, name);
2255
2256         return 0;
2257 }
2258
2259 void flush_table(const char *name)
2260 {
2261         GSList *chains = NULL, *list;
2262         struct connman_iptables *table;
2263
2264         table = get_table(name);
2265         if (table == NULL)
2266                 return;
2267
2268         iterate_entries(table->blob_entries->entrytable,
2269                         table->info->valid_hooks,
2270                         table->info->hook_entry,
2271                         table->info->underflow,
2272                         table->blob_entries->size,
2273                         flush_table_cb, &chains);
2274
2275
2276         /*
2277          * The offset update code is fragile and it works
2278          * only safe if we remove elements and move forwards
2279          * in the table.
2280          */
2281         chains = g_slist_reverse(chains);
2282
2283         for (list = chains; list != NULL; list = list->next) {
2284                 char *chain = list->data;
2285
2286                 DBG("chain %s", chain);
2287                 iptables_flush_chain(table, chain);
2288         }
2289
2290         __connman_iptables_commit(name);
2291         g_slist_free_full(chains, g_free);
2292 }
2293
2294 int __connman_iptables_init(void)
2295 {
2296         DBG("");
2297
2298         if (getenv("CONNMAN_IPTABLES_DEBUG"))
2299                 debug_enabled = TRUE;
2300
2301         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
2302                                                 NULL, remove_table);
2303
2304         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
2305
2306         return 0;
2307 }
2308
2309 void __connman_iptables_cleanup(void)
2310 {
2311         DBG("");
2312
2313         g_hash_table_destroy(table_hash);
2314 }