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