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