9584e1264c790df6174f34d555c8a2640b11b965
[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                                 GList *matches,
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 && !matches)
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 (matches != 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 (matches != 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                                 GList *matches,
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
1037         DBG("table %s chain %s", table->name, chain_name);
1038
1039         removed = 0;
1040
1041         chain_head = find_chain_head(table, chain_name);
1042         if (chain_head == NULL)
1043                 return -EINVAL;
1044
1045         chain_tail = find_chain_tail(table, chain_name);
1046         if (chain_tail == NULL)
1047                 return -EINVAL;
1048
1049         list = find_existing_rule(table, ip, chain_name, target_name,
1050                                                         xt_t, matches, xt_rm);
1051         if (list == NULL)
1052                 return -EINVAL;
1053
1054         entry = chain_head->data;
1055         builtin = entry->builtin;
1056
1057         if (builtin >= 0 && list == chain_head) {
1058                 /*
1059                  * We are about to remove the first rule in the
1060                  * chain. In this case we need to store the builtin
1061                  * value to the new chain_head.
1062                  *
1063                  * Note, for builtin chains, chain_head->next is
1064                  * always valid. A builtin chain has always a policy
1065                  * rule at the end.
1066                  */
1067                 chain_head = chain_head->next;
1068
1069                 entry = chain_head->data;
1070                 entry->builtin = builtin;
1071         }
1072
1073         entry = list->data;
1074         if (entry == NULL)
1075                 return -EINVAL;
1076
1077         /* We have deleted a rule,
1078          * all references should be bumped accordingly */
1079         if (list->next != NULL)
1080                 update_targets_reference(table, list->next->data,
1081                                                 list->data, TRUE);
1082
1083         removed += remove_table_entry(table, entry);
1084
1085         if (builtin >= 0)
1086                 delete_update_hooks(table, builtin, chain_head, removed);
1087
1088         update_offsets(table);
1089
1090         return 0;
1091 }
1092
1093 static int iptables_change_policy(struct connman_iptables *table,
1094                                 const char *chain_name, const char *policy)
1095 {
1096         GList *chain_head, *chain_tail;
1097         struct connman_iptables_entry *entry;
1098         struct xt_entry_target *target;
1099         struct xt_standard_target *t;
1100         int verdict;
1101
1102         DBG("table %s chain %s policy %s", table->name, chain_name, policy);
1103
1104         verdict = target_to_verdict(policy);
1105         switch (verdict) {
1106         case -NF_ACCEPT - 1:
1107         case -NF_DROP - 1:
1108                 break;
1109         default:
1110                 return -EINVAL;
1111         }
1112
1113         chain_head = find_chain_head(table, chain_name);
1114         if (chain_head == NULL)
1115                 return -EINVAL;
1116
1117         entry = chain_head->data;
1118         if (entry->builtin < 0)
1119                 return -EINVAL;
1120
1121         chain_tail = find_chain_tail(table, chain_name);
1122         if (chain_tail == NULL)
1123                 return -EINVAL;
1124
1125         entry = chain_tail->prev->data;
1126         target = ipt_get_target(entry->entry);
1127
1128         t = (struct xt_standard_target *)target;
1129         t->verdict = verdict;
1130
1131         return 0;
1132 }
1133
1134 static struct ipt_replace *iptables_blob(struct connman_iptables *table)
1135 {
1136         struct ipt_replace *r;
1137         GList *list;
1138         struct connman_iptables_entry *e;
1139         unsigned char *entry_index;
1140
1141         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
1142         if (r == NULL)
1143                 return NULL;
1144
1145         memset(r, 0, sizeof(*r) + table->size);
1146
1147         r->counters = g_try_malloc0(sizeof(struct xt_counters)
1148                                 * table->old_entries);
1149         if (r->counters == NULL) {
1150                 g_free(r);
1151                 return NULL;
1152         }
1153
1154         g_stpcpy(r->name, table->info->name);
1155         r->num_entries = table->num_entries;
1156         r->size = table->size;
1157
1158         r->num_counters = table->old_entries;
1159         r->valid_hooks  = table->info->valid_hooks;
1160
1161         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
1162         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
1163
1164         entry_index = (unsigned char *)r->entries;
1165         for (list = table->entries; list; list = list->next) {
1166                 e = list->data;
1167
1168                 memcpy(entry_index, e->entry, e->entry->next_offset);
1169                 entry_index += e->entry->next_offset;
1170         }
1171
1172         return r;
1173 }
1174
1175 static void dump_ip(struct ipt_entry *entry)
1176 {
1177         struct ipt_ip *ip = &entry->ip;
1178         char ip_string[INET6_ADDRSTRLEN];
1179         char ip_mask[INET6_ADDRSTRLEN];
1180
1181         if (strlen(ip->iniface))
1182                 DBG("\tin %s", ip->iniface);
1183
1184         if (strlen(ip->outiface))
1185                 DBG("\tout %s", ip->outiface);
1186
1187         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
1188                         inet_ntop(AF_INET, &ip->smsk,
1189                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1190                 DBG("\tsrc %s/%s", ip_string, ip_mask);
1191
1192         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
1193                         inet_ntop(AF_INET, &ip->dmsk,
1194                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1195                 DBG("\tdst %s/%s", ip_string, ip_mask);
1196 }
1197
1198 static void dump_target(struct ipt_entry *entry)
1199
1200 {
1201         struct xtables_target *xt_t;
1202         struct xt_entry_target *target;
1203
1204         target = ipt_get_target(entry);
1205
1206         if (!g_strcmp0(target->u.user.name, IPT_STANDARD_TARGET)) {
1207                 struct xt_standard_target *t;
1208
1209                 t = (struct xt_standard_target *)target;
1210
1211                 switch (t->verdict) {
1212                 case XT_RETURN:
1213                         DBG("\ttarget RETURN");
1214                         break;
1215
1216                 case -NF_ACCEPT - 1:
1217                         DBG("\ttarget ACCEPT");
1218                         break;
1219
1220                 case -NF_DROP - 1:
1221                         DBG("\ttarget DROP");
1222                         break;
1223
1224                 case -NF_QUEUE - 1:
1225                         DBG("\ttarget QUEUE");
1226                         break;
1227
1228                 case -NF_STOP - 1:
1229                         DBG("\ttarget STOP");
1230                         break;
1231
1232                 default:
1233                         DBG("\tJUMP %u", t->verdict);
1234                         break;
1235                 }
1236
1237                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1238                                                 XTF_LOAD_MUST_SUCCEED);
1239
1240                 if(xt_t->print != NULL)
1241                         xt_t->print(NULL, target, 1);
1242         } else {
1243                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
1244                 if (xt_t == NULL) {
1245                         DBG("\ttarget %s", target->u.user.name);
1246                         return;
1247                 }
1248
1249                 if(xt_t->print != NULL) {
1250                         DBG("\ttarget ");
1251                         xt_t->print(NULL, target, 1);
1252                 }
1253         }
1254
1255         if (xt_t == xt_t->next)
1256                 free(xt_t);
1257 }
1258
1259 static void dump_match(struct ipt_entry *entry)
1260 {
1261         struct xtables_match *xt_m;
1262         struct xt_entry_match *match;
1263
1264         if (entry->elems == (unsigned char *)entry + entry->target_offset)
1265                 return;
1266
1267         match = (struct xt_entry_match *) entry->elems;
1268
1269         if (!strlen(match->u.user.name))
1270                 return;
1271
1272         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
1273         if (xt_m == NULL)
1274                 goto out;
1275
1276         if(xt_m->print != NULL) {
1277                 DBG("\tmatch ");
1278                 xt_m->print(NULL, match, 1);
1279
1280                 return;
1281         }
1282         if (xt_m == xt_m->next)
1283                 free(xt_m);
1284
1285 out:
1286         DBG("\tmatch %s", match->u.user.name);
1287
1288 }
1289
1290 static int dump_entry(struct ipt_entry *entry, int builtin,
1291                         unsigned int hook, size_t size, unsigned int offset,
1292                         void *user_data)
1293 {
1294         struct xt_entry_target *target;
1295
1296         target = ipt_get_target(entry);
1297
1298         if (offset + entry->next_offset == size) {
1299                 DBG("\tEnd of CHAIN");
1300                 return 0;
1301         }
1302
1303         if (!g_strcmp0(target->u.user.name, IPT_ERROR_TARGET)) {
1304                 DBG("\tUSER CHAIN (%s) match %p  target %p",
1305                         target->data, entry->elems,
1306                         (char *)entry + entry->target_offset);
1307
1308                 return 0;
1309         } else if (builtin >= 0) {
1310                 DBG("\tCHAIN (%s) match %p  target %p",
1311                         hooknames[builtin], entry->elems,
1312                         (char *)entry + entry->target_offset);
1313         } else {
1314                 DBG("\tRULE  match %p  target %p",
1315                         entry->elems,
1316                         (char *)entry + entry->target_offset);
1317         }
1318
1319         dump_match(entry);
1320         dump_target(entry);
1321         dump_ip(entry);
1322
1323         return 0;
1324 }
1325
1326 static void dump_table(struct connman_iptables *table)
1327 {
1328         DBG("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
1329                         table->info->name,
1330                         table->info->valid_hooks, table->info->num_entries,
1331                                 table->info->size);
1332
1333         DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
1334                 table->info->hook_entry[NF_IP_PRE_ROUTING],
1335                 table->info->hook_entry[NF_IP_LOCAL_IN],
1336                 table->info->hook_entry[NF_IP_FORWARD],
1337                 table->info->hook_entry[NF_IP_LOCAL_OUT],
1338                 table->info->hook_entry[NF_IP_POST_ROUTING]);
1339         DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
1340                 table->info->underflow[NF_IP_PRE_ROUTING],
1341                 table->info->underflow[NF_IP_LOCAL_IN],
1342                 table->info->underflow[NF_IP_FORWARD],
1343                 table->info->underflow[NF_IP_LOCAL_OUT],
1344                 table->info->underflow[NF_IP_POST_ROUTING]);
1345
1346         iterate_entries(table->blob_entries->entrytable,
1347                         table->info->valid_hooks,
1348                         table->info->hook_entry,
1349                         table->info->underflow,
1350                         table->blob_entries->size,
1351                         print_entry, dump_entry);
1352 }
1353
1354 static void dump_ipt_replace(struct ipt_replace *repl)
1355 {
1356         DBG("%s valid_hooks 0x%08x  num_entries %u  size %u",
1357                         repl->name, repl->valid_hooks, repl->num_entries,
1358                         repl->size);
1359
1360         DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
1361                 repl->hook_entry[NF_IP_PRE_ROUTING],
1362                 repl->hook_entry[NF_IP_LOCAL_IN],
1363                 repl->hook_entry[NF_IP_FORWARD],
1364                 repl->hook_entry[NF_IP_LOCAL_OUT],
1365                 repl->hook_entry[NF_IP_POST_ROUTING]);
1366         DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
1367                 repl->underflow[NF_IP_PRE_ROUTING],
1368                 repl->underflow[NF_IP_LOCAL_IN],
1369                 repl->underflow[NF_IP_FORWARD],
1370                 repl->underflow[NF_IP_LOCAL_OUT],
1371                 repl->underflow[NF_IP_POST_ROUTING]);
1372
1373         iterate_entries(repl->entries, repl->valid_hooks,
1374                         repl->hook_entry, repl->underflow,
1375                         repl->size, print_entry, dump_entry);
1376 }
1377
1378 static int iptables_get_entries(struct connman_iptables *table)
1379 {
1380         socklen_t entry_size;
1381
1382         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
1383
1384         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
1385                                 table->blob_entries, &entry_size);
1386 }
1387
1388 static int iptables_replace(struct connman_iptables *table,
1389                                         struct ipt_replace *r)
1390 {
1391         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
1392                          sizeof(*r) + r->size);
1393 }
1394
1395 static int add_entry(struct ipt_entry *entry, int builtin, unsigned int hook,
1396                         size_t size, unsigned offset, void *user_data)
1397 {
1398         struct connman_iptables *table = user_data;
1399         struct ipt_entry *new_entry;
1400
1401         new_entry = g_try_malloc0(entry->next_offset);
1402         if (new_entry == NULL)
1403                 return -ENOMEM;
1404
1405         memcpy(new_entry, entry, entry->next_offset);
1406
1407         return iptables_add_entry(table, new_entry, NULL, builtin);
1408 }
1409
1410 static void table_cleanup(struct connman_iptables *table)
1411 {
1412         GList *list;
1413         struct connman_iptables_entry *entry;
1414
1415         if (table == NULL)
1416                 return;
1417
1418         if (table->ipt_sock >= 0)
1419                 close(table->ipt_sock);
1420
1421         for (list = table->entries; list; list = list->next) {
1422                 entry = list->data;
1423
1424                 g_free(entry->entry);
1425                 g_free(entry);
1426         }
1427
1428         g_list_free(table->entries);
1429         g_free(table->name);
1430         g_free(table->info);
1431         g_free(table->blob_entries);
1432         g_free(table);
1433 }
1434
1435 static struct connman_iptables *iptables_init(const char *table_name)
1436 {
1437         struct connman_iptables *table = NULL;
1438         char *module = NULL;
1439         socklen_t s;
1440
1441         DBG("%s", table_name);
1442
1443         if (xtables_insmod("ip_tables", NULL, TRUE) != 0)
1444                 DBG("ip_tables module loading gives error but trying anyway");
1445
1446         module = g_strconcat("iptable_", table_name, NULL);
1447         if (module == NULL)
1448                 return NULL;
1449
1450         if (xtables_insmod(module, NULL, TRUE) != 0)
1451                 DBG("%s module loading gives error but trying anyway", module);
1452
1453         g_free(module);
1454
1455         table = g_try_new0(struct connman_iptables, 1);
1456         if (table == NULL)
1457                 return NULL;
1458
1459         table->info = g_try_new0(struct ipt_getinfo, 1);
1460         if (table->info == NULL)
1461                 goto err;
1462
1463         table->ipt_sock = socket(AF_INET, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_RAW);
1464         if (table->ipt_sock < 0)
1465                 goto err;
1466
1467         s = sizeof(*table->info);
1468         g_stpcpy(table->info->name, table_name);
1469         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
1470                                                 table->info, &s) < 0) {
1471                 connman_error("iptables support missing error %d (%s)", errno,
1472                         strerror(errno));
1473                 goto err;
1474         }
1475
1476         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
1477                                                 table->info->size);
1478         if (table->blob_entries == NULL)
1479                 goto err;
1480
1481         g_stpcpy(table->blob_entries->name, table_name);
1482         table->blob_entries->size = table->info->size;
1483
1484         if (iptables_get_entries(table) < 0)
1485                 goto err;
1486
1487         table->num_entries = 0;
1488         table->old_entries = table->info->num_entries;
1489         table->size = 0;
1490
1491         memcpy(table->underflow, table->info->underflow,
1492                                 sizeof(table->info->underflow));
1493         memcpy(table->hook_entry, table->info->hook_entry,
1494                                 sizeof(table->info->hook_entry));
1495
1496         iterate_entries(table->blob_entries->entrytable,
1497                         table->info->valid_hooks, table->info->hook_entry,
1498                         table->info->underflow, table->blob_entries->size,
1499                         add_entry, table);
1500
1501         if (debug_enabled == TRUE)
1502                 dump_table(table);
1503
1504         return table;
1505
1506 err:
1507         table_cleanup(table);
1508
1509         return NULL;
1510 }
1511
1512 static struct option iptables_opts[] = {
1513         {.name = "append",        .has_arg = 1, .val = 'A'},
1514         {.name = "compare",       .has_arg = 1, .val = 'C'},
1515         {.name = "delete",        .has_arg = 1, .val = 'D'},
1516         {.name = "flush-chain",   .has_arg = 1, .val = 'F'},
1517         {.name = "insert",        .has_arg = 1, .val = 'I'},
1518         {.name = "list",          .has_arg = 2, .val = 'L'},
1519         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
1520         {.name = "policy",        .has_arg = 1, .val = 'P'},
1521         {.name = "delete-chain",  .has_arg = 1, .val = 'X'},
1522         {.name = "destination",   .has_arg = 1, .val = 'd'},
1523         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
1524         {.name = "jump",          .has_arg = 1, .val = 'j'},
1525         {.name = "match",         .has_arg = 1, .val = 'm'},
1526         {.name = "out-interface", .has_arg = 1, .val = 'o'},
1527         {.name = "source",        .has_arg = 1, .val = 's'},
1528         {.name = "table",         .has_arg = 1, .val = 't'},
1529         {NULL},
1530 };
1531
1532 struct xtables_globals iptables_globals = {
1533         .option_offset = 0,
1534         .opts = iptables_opts,
1535         .orig_opts = iptables_opts,
1536 };
1537
1538 static struct xtables_target *prepare_target(struct connman_iptables *table,
1539                                                         const char *target_name)
1540 {
1541         struct xtables_target *xt_t = NULL;
1542         gboolean is_builtin, is_user_defined;
1543         GList *chain_head = NULL;
1544         size_t target_size;
1545
1546         is_builtin = FALSE;
1547         is_user_defined = FALSE;
1548
1549         if (is_builtin_target(target_name))
1550                 is_builtin = TRUE;
1551         else {
1552                 chain_head = find_chain_head(table, target_name);
1553                 if (chain_head != NULL && chain_head->next != NULL)
1554                         is_user_defined = TRUE;
1555         }
1556
1557         if (is_builtin || is_user_defined)
1558                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1559                                                 XTF_LOAD_MUST_SUCCEED);
1560         else
1561                 xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1562
1563         if (xt_t == NULL)
1564                 return NULL;
1565
1566         target_size = ALIGN(sizeof(struct ipt_entry_target)) + xt_t->size;
1567
1568         xt_t->t = g_try_malloc0(target_size);
1569         if (xt_t->t == NULL)
1570                 return NULL;
1571
1572         xt_t->t->u.target_size = target_size;
1573
1574         if (is_builtin || is_user_defined) {
1575                 struct xt_standard_target *target;
1576
1577                 target = (struct xt_standard_target *)(xt_t->t);
1578                 g_stpcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
1579
1580                 if (is_builtin == TRUE)
1581                         target->verdict = target_to_verdict(target_name);
1582                 else if (is_user_defined == TRUE) {
1583                         struct connman_iptables_entry *target_rule;
1584
1585                         if (chain_head == NULL) {
1586                                 g_free(xt_t->t);
1587                                 return NULL;
1588                         }
1589
1590                         target_rule = chain_head->next->data;
1591                         target->verdict = target_rule->offset;
1592                 }
1593         } else {
1594                 g_stpcpy(xt_t->t->u.user.name, target_name);
1595                 xt_t->t->u.user.revision = xt_t->revision;
1596                 if (xt_t->init != NULL)
1597                         xt_t->init(xt_t->t);
1598         }
1599
1600         if (xt_t->x6_options != NULL)
1601                 iptables_globals.opts =
1602                         xtables_options_xfrm(
1603                                 iptables_globals.orig_opts,
1604                                 iptables_globals.opts,
1605                                 xt_t->x6_options,
1606                                 &xt_t->option_offset);
1607         else
1608                 iptables_globals.opts =
1609                         xtables_merge_options(
1610                                 iptables_globals.orig_opts,
1611                                 iptables_globals.opts,
1612                                 xt_t->extra_opts,
1613                                 &xt_t->option_offset);
1614
1615         if (iptables_globals.opts == NULL) {
1616                 g_free(xt_t->t);
1617                 xt_t = NULL;
1618         }
1619
1620         return xt_t;
1621 }
1622
1623 static struct xtables_match *prepare_matches(struct connman_iptables *table,
1624                                         struct xtables_rule_match **xt_rm,
1625                                         const char *match_name)
1626 {
1627         struct xtables_match *xt_m;
1628         size_t match_size;
1629
1630         if (match_name == NULL)
1631                 return NULL;
1632
1633         xt_m = xtables_find_match(match_name, XTF_LOAD_MUST_SUCCEED, xt_rm);
1634         match_size = ALIGN(sizeof(struct ipt_entry_match)) + xt_m->size;
1635
1636         xt_m->m = g_try_malloc0(match_size);
1637         if (xt_m->m == NULL)
1638                 return NULL;
1639
1640         xt_m->m->u.match_size = match_size;
1641         g_stpcpy(xt_m->m->u.user.name, xt_m->name);
1642         xt_m->m->u.user.revision = xt_m->revision;
1643
1644         if (xt_m->init != NULL)
1645                 xt_m->init(xt_m->m);
1646
1647         if (xt_m->x6_options != NULL)
1648                 iptables_globals.opts =
1649                         xtables_options_xfrm(
1650                                 iptables_globals.orig_opts,
1651                                 iptables_globals.opts,
1652                                 xt_m->x6_options,
1653                                 &xt_m->option_offset);
1654         else
1655                         iptables_globals.opts =
1656                         xtables_merge_options(
1657                                 iptables_globals.orig_opts,
1658                                 iptables_globals.opts,
1659                                 xt_m->extra_opts,
1660                                 &xt_m->option_offset);
1661
1662         if (iptables_globals.opts == NULL) {
1663                 g_free(xt_m->m);
1664
1665                 if (xt_m == xt_m->next)
1666                         free(xt_m);
1667
1668                 xt_m = NULL;
1669         }
1670
1671         return xt_m;
1672 }
1673
1674 static int parse_ip_and_mask(const char *str, struct in_addr *ip, struct in_addr *mask)
1675 {
1676         char **tokens;
1677         uint32_t prefixlength;
1678         uint32_t tmp;
1679         int err;
1680
1681         tokens = g_strsplit(str, "/", 2);
1682         if (tokens == NULL)
1683                 return -1;
1684
1685         if (!inet_pton(AF_INET, tokens[0], ip)) {
1686                 err = -1;
1687                 goto out;
1688         }
1689
1690         if (tokens[1] != NULL) {
1691                 prefixlength = strtol(tokens[1], NULL, 10);
1692                 if (prefixlength > 31) {
1693                         err = -1;
1694                         goto out;
1695                 }
1696
1697                 tmp = ~(0xffffffff >> prefixlength);
1698         } else {
1699                 tmp = 0xffffffff;
1700         }
1701
1702         mask->s_addr = htonl(tmp);
1703         ip->s_addr = ip->s_addr & mask->s_addr;
1704         err = 0;
1705 out:
1706         g_strfreev(tokens);
1707
1708         return err;
1709 }
1710
1711 static struct connman_iptables *get_table(const char *table_name)
1712 {
1713         struct connman_iptables *table;
1714
1715         if (table_name == NULL)
1716                 table_name = "filter";
1717
1718         table = g_hash_table_lookup(table_hash, table_name);
1719         if (table != NULL)
1720                 return table;
1721
1722         table = iptables_init(table_name);
1723         if (table == NULL)
1724                 return NULL;
1725
1726         table->name = g_strdup(table_name);
1727         g_hash_table_replace(table_hash, table->name, table);
1728
1729         return table;
1730 }
1731
1732 struct parse_context {
1733         int argc;
1734         char **argv;
1735         struct ipt_ip *ip;
1736         struct xtables_target *xt_t;
1737         GList *xt_m;
1738         struct xtables_rule_match *xt_rm;
1739 };
1740
1741 static int prepare_getopt_args(const char *str, struct parse_context *ctx)
1742 {
1743         char **tokens;
1744         int i;
1745
1746         tokens = g_strsplit_set(str, " ", -1);
1747
1748         i = g_strv_length(tokens);
1749
1750         /* Add space for the argv[0] value */
1751         ctx->argc = i + 1;
1752
1753         /* Don't forget the last NULL entry */
1754         ctx->argv = g_try_malloc0((ctx->argc + 1) * sizeof(char *));
1755         if (ctx->argv == NULL) {
1756                 g_strfreev(tokens);
1757                 return -ENOMEM;
1758         }
1759
1760         /*
1761          * getopt_long() jumps over the first token; we need to add some
1762          * random argv[0] entry.
1763          */
1764         ctx->argv[0] = g_strdup("argh");
1765         for (i = 1; i < ctx->argc; i++)
1766                 ctx->argv[i] = tokens[i - 1];
1767
1768         g_free(tokens);
1769
1770         return 0;
1771 }
1772
1773 static int parse_xt_modules(int c, connman_bool_t invert,
1774                                 struct parse_context *ctx)
1775 {
1776         struct xtables_match *m;
1777         struct xtables_rule_match *rm;
1778
1779         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
1780                 if (rm->completed != 0)
1781                         continue;
1782
1783                 m = rm->match;
1784
1785                 if (m->x6_parse == NULL && m->parse == NULL)
1786                         continue;
1787
1788                 if (c < (int) m->option_offset ||
1789                                 c >= (int) m->option_offset
1790                                         + XT_OPTION_OFFSET_SCALE)
1791                         continue;
1792
1793                 xtables_option_mpcall(c, ctx->argv, invert, m, NULL);
1794         }
1795
1796         if (ctx->xt_t == NULL)
1797                 return 0;
1798
1799         if (ctx->xt_t->x6_parse == NULL && ctx->xt_t->parse == NULL)
1800                 return 0;
1801
1802         if (c < (int) ctx->xt_t->option_offset ||
1803                         c >= (int) ctx->xt_t->option_offset
1804                                         + XT_OPTION_OFFSET_SCALE)
1805                 return 0;
1806
1807         xtables_option_tpcall(c, ctx->argv, invert, ctx->xt_t, NULL);
1808
1809         return 0;
1810 }
1811
1812 static int final_check_xt_modules(struct parse_context *ctx)
1813 {
1814         struct xtables_rule_match *rm;
1815
1816         for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
1817                 xtables_option_mfcall(rm->match);
1818
1819         if (ctx->xt_t != NULL)
1820                 xtables_option_tfcall(ctx->xt_t);
1821
1822         return 0;
1823 }
1824
1825 static int parse_rule_spec(struct connman_iptables *table,
1826                                 struct parse_context *ctx)
1827 {
1828         /*
1829          * How the parser works:
1830          *
1831          *  - If getopt finds 's', 'd', 'i', 'o'.
1832          *    just extract the information.
1833          *  - if '!' is found, set the invert flag to true and
1834          *    removes the '!' from the optarg string and jumps
1835          *    back to getopt to reparse the current optarg string.
1836          *    After reparsing the invert flag is reseted to false.
1837          *  - If 'm' or 'j' is found then call either
1838          *    prepare_matches() or prepare_target(). Those function
1839          *    will modify (extend) the longopts for getopt_long.
1840          *    That means getopt will change its matching context according
1841          *    the loaded target.
1842          *
1843          *    Here an example with iptables-test
1844          *
1845          *    argv[0] = ./tools/iptables-test
1846          *    argv[1] = -t
1847          *    argv[2] = filter
1848          *    argv[3] = -A
1849          *    argv[4] = INPUT
1850          *    argv[5] = -m
1851          *    argv[6] = mark
1852          *    argv[7] = --mark
1853          *    argv[8] = 999
1854          *    argv[9] = -j
1855          *    argv[10] = LOG
1856          *
1857          *    getopt found 'm' then the optarg is "mark" and optind 7
1858          *    The longopts array containts before hitting the `case 'm'`
1859          *
1860          *    val A has_arg 1 name append
1861          *    val C has_arg 1 name compare
1862          *    val D has_arg 1 name delete
1863          *    val F has_arg 1 name flush-chain
1864          *    val I has_arg 1 name insert
1865          *    val L has_arg 2 name list
1866          *    val N has_arg 1 name new-chain
1867          *    val P has_arg 1 name policy
1868          *    val X has_arg 1 name delete-chain
1869          *    val d has_arg 1 name destination
1870          *    val i has_arg 1 name in-interface
1871          *    val j has_arg 1 name jump
1872          *    val m has_arg 1 name match
1873          *    val o has_arg 1 name out-interface
1874          *    val s has_arg 1 name source
1875          *    val t has_arg 1 name table
1876          *
1877          *    After executing the `case 'm'` block longopts is
1878          *
1879          *    val A has_arg 1 name append
1880          *    val C has_arg 1 name compare
1881          *    val D has_arg 1 name delete
1882          *    val F has_arg 1 name flush-chain
1883          *    val I has_arg 1 name insert
1884          *    val L has_arg 2 name list
1885          *    val N has_arg 1 name new-chain
1886          *    val P has_arg 1 name policy
1887          *    val X has_arg 1 name delete-chain
1888          *    val d has_arg 1 name destination
1889          *    val i has_arg 1 name in-interface
1890          *    val j has_arg 1 name jump
1891          *    val m has_arg 1 name match
1892          *    val o has_arg 1 name out-interface
1893          *    val s has_arg 1 name source
1894          *    val t has_arg 1 name table
1895          *    val   has_arg 1 name mark
1896          *
1897          *    So the 'mark' matcher has added the 'mark' options
1898          *    and getopt will then return c '256' optarg "999" optind 9
1899          *    And we will hit the 'default' statement which then
1900          *    will call the matchers parser (xt_m->parser() or
1901          *    xtables_option_mpcall() depending on which version
1902          *    of libxtables is found.
1903          */
1904         struct xtables_match *xt_m;
1905         connman_bool_t invert = FALSE;
1906         int len, c, err;
1907
1908         ctx->ip = g_try_new0(struct ipt_ip, 1);
1909         if (ctx->ip == NULL)
1910                 return -ENOMEM;
1911
1912         /*
1913          * Tell getopt_long not to generate error messages for unknown
1914          * options and also reset optind back to 0.
1915          */
1916         opterr = 0;
1917         optind = 0;
1918
1919         while ((c = getopt_long(ctx->argc, ctx->argv,
1920                                         "-:d:i:o:s:m:j:",
1921                                         iptables_globals.opts, NULL)) != -1) {
1922                 switch (c) {
1923                 case 's':
1924                         /* Source specification */
1925                         if (!parse_ip_and_mask(optarg,
1926                                                 &ctx->ip->src,
1927                                                 &ctx->ip->smsk))
1928                                 break;
1929
1930                         if (invert)
1931                                 ctx->ip->invflags |= IPT_INV_SRCIP;
1932
1933                         break;
1934                 case 'd':
1935                         /* Destination specification */
1936                         if (!parse_ip_and_mask(optarg,
1937                                                 &ctx->ip->dst,
1938                                                 &ctx->ip->dmsk))
1939                                 break;
1940
1941                         if (invert)
1942                                 ctx->ip->invflags |= IPT_INV_DSTIP;
1943                         break;
1944                 case 'i':
1945                         /* In interface specification */
1946                         len = strlen(optarg);
1947
1948                         if (len + 1 > IFNAMSIZ)
1949                                 break;
1950
1951                         g_stpcpy(ctx->ip->iniface, optarg);
1952                         memset(ctx->ip->iniface_mask, 0xff, len + 1);
1953
1954                         if (invert)
1955                                 ctx->ip->invflags |= IPT_INV_VIA_IN;
1956
1957                         break;
1958                 case 'o':
1959                         /* Out interface specification */
1960                         len = strlen(optarg);
1961
1962                         if (len + 1 > IFNAMSIZ)
1963                                 break;
1964
1965                         g_stpcpy(ctx->ip->outiface, optarg);
1966                         memset(ctx->ip->outiface_mask, 0xff, len + 1);
1967
1968                         if (invert)
1969                                 ctx->ip->invflags |= IPT_INV_VIA_OUT;
1970
1971                         break;
1972                 case 'm':
1973                         /* Matches */
1974                         xt_m = prepare_matches(table, &ctx->xt_rm, optarg);
1975                         if (xt_m == NULL) {
1976                                 err = -EINVAL;
1977                                 goto out;
1978                         }
1979                         ctx->xt_m = g_list_append(ctx->xt_m, xt_m);
1980
1981                         break;
1982                 case 'j':
1983                         /* Target */
1984                         ctx->xt_t = prepare_target(table, optarg);
1985                         if (ctx->xt_t == NULL) {
1986                                 err = -EINVAL;
1987                                 goto out;
1988                         }
1989
1990                         break;
1991                 case 1:
1992                         if (optarg[0] == '!' && optarg[1] == '\0') {
1993                                 invert = TRUE;
1994
1995                                 /* Remove the '!' from the optarg */
1996                                 optarg[0] = '\0';
1997
1998                                 /*
1999                                  * And recall getopt_long without reseting
2000                                  * invert.
2001                                  */
2002                                 continue;
2003                         }
2004
2005                         break;
2006                 default:
2007                         err = parse_xt_modules(c, invert, ctx);
2008                         if (err == 1)
2009                                 continue;
2010
2011                         break;
2012                 }
2013
2014                 invert = FALSE;
2015         }
2016
2017         err = final_check_xt_modules(ctx);
2018
2019 out:
2020         return err;
2021 }
2022
2023 static void reset_xtables(void)
2024 {
2025         struct xtables_match *xt_m;
2026         struct xtables_target *xt_t;
2027
2028         /*
2029          * As side effect parsing a rule sets some global flags
2030          * which will be evaluated/verified. Let's reset them
2031          * to ensure we can parse more than one rule.
2032          *
2033          * Clear all flags because the flags are only valid
2034          * for one rule.
2035          */
2036         for (xt_m = xtables_matches; xt_m != NULL; xt_m = xt_m->next)
2037                 xt_m->mflags = 0;
2038
2039         for (xt_t = xtables_targets; xt_t != NULL; xt_t = xt_t->next) {
2040                 xt_t->tflags = 0;
2041                 xt_t->used = 0;
2042         }
2043
2044         /*
2045          * We need also to free the memory implicitly allocated
2046          * during parsing (see xtables_options_xfrm()).
2047          * Note xt_params is actually iptables_globals.
2048          */
2049         if (xt_params->opts != xt_params->orig_opts) {
2050                 g_free(xt_params->opts);
2051                 xt_params->opts = xt_params->orig_opts;
2052         }
2053         xt_params->option_offset = 0;
2054 }
2055
2056 static void cleanup_parse_context(struct parse_context *ctx)
2057 {
2058         struct xtables_rule_match *rm, *tmp;
2059         GList *list;
2060
2061         g_strfreev(ctx->argv);
2062         g_free(ctx->ip);
2063         if (ctx->xt_t != NULL) {
2064                 g_free(ctx->xt_t->t);
2065                 ctx->xt_t->t = NULL;
2066         }
2067
2068         for (list = ctx->xt_m; list != NULL; list = list->next) {
2069                 struct xtables_match *xt_m = list->data;
2070
2071                 g_free(xt_m->m);
2072
2073                 if (xt_m != xt_m->next)
2074                         continue;
2075
2076                 g_free(xt_m);
2077         }
2078         g_list_free(ctx->xt_m);
2079
2080         for (tmp = NULL, rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
2081                 if (tmp != NULL)
2082                         g_free(tmp);
2083                 tmp = rm;
2084         }
2085         g_free(tmp);
2086
2087         g_free(ctx);
2088 }
2089
2090 int __connman_iptables_dump(const char *table_name)
2091 {
2092         struct connman_iptables *table;
2093
2094         DBG("-t %s -L", table_name);
2095
2096         table = get_table(table_name);
2097         if (table == NULL)
2098                 return -EINVAL;
2099
2100         dump_table(table);
2101
2102         return 0;
2103 }
2104
2105 int __connman_iptables_new_chain(const char *table_name,
2106                                         const char *chain)
2107 {
2108         struct connman_iptables *table;
2109
2110         DBG("-t %s -N %s", table_name, chain);
2111
2112         table = get_table(table_name);
2113         if (table == NULL)
2114                 return -EINVAL;
2115
2116         return iptables_add_chain(table, chain);
2117 }
2118
2119 int __connman_iptables_delete_chain(const char *table_name,
2120                                         const char *chain)
2121 {
2122         struct connman_iptables *table;
2123
2124         DBG("-t %s -X %s", table_name, chain);
2125
2126         table = get_table(table_name);
2127         if (table == NULL)
2128                 return -EINVAL;
2129
2130         return iptables_delete_chain(table, chain);
2131 }
2132
2133 int __connman_iptables_flush_chain(const char *table_name,
2134                                         const char *chain)
2135 {
2136         struct connman_iptables *table;
2137
2138         DBG("-t %s -F %s", table_name, chain);
2139
2140         table = get_table(table_name);
2141         if (table == NULL)
2142                 return -EINVAL;
2143
2144         return iptables_flush_chain(table, chain);
2145 }
2146
2147 int __connman_iptables_change_policy(const char *table_name,
2148                                         const char *chain,
2149                                         const char *policy)
2150 {
2151         struct connman_iptables *table;
2152
2153         DBG("-t %s -F %s", table_name, chain);
2154
2155         table = get_table(table_name);
2156         if (table == NULL)
2157                 return -EINVAL;
2158
2159         return iptables_change_policy(table, chain, policy);
2160 }
2161
2162 int __connman_iptables_append(const char *table_name,
2163                                 const char *chain,
2164                                 const char *rule_spec)
2165 {
2166         struct connman_iptables *table;
2167         struct parse_context *ctx;
2168         const char *target_name;
2169         int err;
2170
2171         ctx = g_try_new0(struct parse_context, 1);
2172         if (ctx == NULL)
2173                 return -ENOMEM;
2174
2175         DBG("-t %s -A %s %s", table_name, chain, rule_spec);
2176
2177         err = prepare_getopt_args(rule_spec, ctx);
2178         if (err < 0)
2179                 goto out;
2180
2181         table = get_table(table_name);
2182         if (table == NULL) {
2183                 err = -EINVAL;
2184                 goto out;
2185         }
2186
2187         err = parse_rule_spec(table, ctx);
2188         if (err < 0)
2189                 goto out;
2190
2191         if (ctx->xt_t == NULL)
2192                 target_name = NULL;
2193         else
2194                 target_name = ctx->xt_t->name;
2195
2196         err = iptables_append_rule(table, ctx->ip, chain,
2197                                 target_name, ctx->xt_t, ctx->xt_rm);
2198 out:
2199         cleanup_parse_context(ctx);
2200         reset_xtables();
2201
2202         return err;
2203 }
2204
2205 int __connman_iptables_insert(const char *table_name,
2206                                 const char *chain,
2207                                 const char *rule_spec)
2208 {
2209         struct connman_iptables *table;
2210         struct parse_context *ctx;
2211         const char *target_name;
2212         int err;
2213
2214         ctx = g_try_new0(struct parse_context, 1);
2215         if (ctx == NULL)
2216                 return -ENOMEM;
2217
2218         DBG("-t %s -I %s %s", table_name, chain, rule_spec);
2219
2220         err = prepare_getopt_args(rule_spec, ctx);
2221         if (err < 0)
2222                 goto out;
2223
2224         table = get_table(table_name);
2225         if (table == NULL) {
2226                 err = -EINVAL;
2227                 goto out;
2228         }
2229
2230         err = parse_rule_spec(table, ctx);
2231         if (err < 0)
2232                 goto out;
2233
2234         if (ctx->xt_t == NULL)
2235                 target_name = NULL;
2236         else
2237                 target_name = ctx->xt_t->name;
2238
2239         err = iptables_insert_rule(table, ctx->ip, chain,
2240                                 target_name, ctx->xt_t, ctx->xt_rm);
2241 out:
2242         cleanup_parse_context(ctx);
2243         reset_xtables();
2244
2245         return err;
2246 }
2247
2248 int __connman_iptables_delete(const char *table_name,
2249                                 const char *chain,
2250                                 const char *rule_spec)
2251 {
2252         struct connman_iptables *table;
2253         struct parse_context *ctx;
2254         const char *target_name;
2255         int err;
2256
2257         ctx = g_try_new0(struct parse_context, 1);
2258         if (ctx == NULL)
2259                 return -ENOMEM;
2260
2261         DBG("-t %s -D %s %s", table_name, chain, rule_spec);
2262
2263         err = prepare_getopt_args(rule_spec, ctx);
2264         if (err < 0)
2265                 goto out;
2266
2267         table = get_table(table_name);
2268         if (table == NULL) {
2269                 err = -EINVAL;
2270                 goto out;
2271         }
2272
2273         err = parse_rule_spec(table, ctx);
2274         if (err < 0)
2275                 goto out;
2276
2277         if (ctx->xt_t == NULL)
2278                 target_name = NULL;
2279         else
2280                 target_name = ctx->xt_t->name;
2281
2282         err = iptables_delete_rule(table, ctx->ip, chain,
2283                                 target_name, ctx->xt_t, ctx->xt_m,
2284                                 ctx->xt_rm);
2285 out:
2286         cleanup_parse_context(ctx);
2287         reset_xtables();
2288
2289         return err;
2290 }
2291
2292 int __connman_iptables_commit(const char *table_name)
2293 {
2294         struct connman_iptables *table;
2295         struct ipt_replace *repl;
2296         int err;
2297
2298         DBG("%s", table_name);
2299
2300         table = g_hash_table_lookup(table_hash, table_name);
2301         if (table == NULL)
2302                 return -EINVAL;
2303
2304         repl = iptables_blob(table);
2305
2306         if (debug_enabled == TRUE)
2307                 dump_ipt_replace(repl);
2308
2309         err = iptables_replace(table, repl);
2310
2311         g_free(repl->counters);
2312         g_free(repl);
2313
2314         if (err < 0)
2315             return err;
2316
2317         g_hash_table_remove(table_hash, table_name);
2318
2319         return 0;
2320 }
2321
2322 static void remove_table(gpointer user_data)
2323 {
2324         struct connman_iptables *table = user_data;
2325
2326         table_cleanup(table);
2327 }
2328
2329 static int iterate_chains_cb(struct ipt_entry *entry, int builtin,
2330                                 unsigned int hook, size_t size,
2331                                 unsigned int offset, void *user_data)
2332 {
2333         struct cb_data *cbd = user_data;
2334         connman_iptables_iterate_chains_cb_t cb = cbd->cb;
2335         struct xt_entry_target *target;
2336
2337         if (offset + entry->next_offset == size)
2338                 return 0;
2339
2340         target = ipt_get_target(entry);
2341
2342         if (!g_strcmp0(target->u.user.name, IPT_ERROR_TARGET))
2343                 (*cb)((const char*)target->data, cbd->user_data);
2344         else if (builtin >= 0)
2345                 (*cb)(hooknames[builtin], cbd->user_data);
2346
2347         return 0;
2348 }
2349
2350 int __connman_iptables_iterate_chains(const char *table_name,
2351                                 connman_iptables_iterate_chains_cb_t cb,
2352                                 void *user_data)
2353 {
2354         struct cb_data *cbd = cb_data_new(cb, user_data);
2355         struct connman_iptables *table;
2356
2357         table = get_table(table_name);
2358         if (table == NULL)
2359                 return -EINVAL;
2360
2361         iterate_entries(table->blob_entries->entrytable,
2362                         table->info->valid_hooks,
2363                         table->info->hook_entry,
2364                         table->info->underflow,
2365                         table->blob_entries->size,
2366                         iterate_chains_cb, cbd);
2367
2368         g_free(cbd);
2369
2370         return 0;
2371 }
2372
2373 int __connman_iptables_init(void)
2374 {
2375         DBG("");
2376
2377         if (getenv("CONNMAN_IPTABLES_DEBUG"))
2378                 debug_enabled = TRUE;
2379
2380         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
2381                                                 NULL, remove_table);
2382
2383         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
2384
2385         return 0;
2386 }
2387
2388 void __connman_iptables_cleanup(void)
2389 {
2390         DBG("");
2391
2392         g_hash_table_destroy(table_hash);
2393 }