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