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