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