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