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