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