iptables: Factorization of target reference update
[framework/connectivity/connman.git] / src / iptables.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  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 static const char *hooknames[] = {
41         [NF_IP_PRE_ROUTING]     = "PREROUTING",
42         [NF_IP_LOCAL_IN]        = "INPUT",
43         [NF_IP_FORWARD]         = "FORWARD",
44         [NF_IP_LOCAL_OUT]       = "OUTPUT",
45         [NF_IP_POST_ROUTING]    = "POSTROUTING",
46 };
47
48 #define LABEL_ACCEPT  "ACCEPT"
49 #define LABEL_DROP    "DROP"
50 #define LABEL_QUEUE   "QUEUE"
51 #define LABEL_RETURN  "RETURN"
52
53 /* fn returns 0 to continue iteration */
54 #define _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, n, fn, args...) \
55 ({                                                              \
56         unsigned int __i;                                       \
57         int __n;                                                \
58         int __ret = 0;                                          \
59         type *__entry;                                          \
60                                                                 \
61         for (__i = 0, __n = 0; __i < (size);                    \
62              __i += __entry->next_offset, __n++) {              \
63                 __entry = (void *)(entries) + __i;              \
64                 if (__n < n)                                    \
65                         continue;                               \
66                                                                 \
67                 __ret = fn(__entry,  ## args);                  \
68                 if (__ret != 0)                                 \
69                         break;                                  \
70         }                                                       \
71         __ret;                                                  \
72 })
73
74 /* fn returns 0 to continue iteration */
75 #define _XT_ENTRY_ITERATE(type, entries, size, fn, args...) \
76         _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, 0, fn, args)
77
78 #define ENTRY_ITERATE(entries, size, fn, args...) \
79         _XT_ENTRY_ITERATE(struct ipt_entry, entries, size, fn, ## args)
80
81 #define MIN_ALIGN (__alignof__(struct ipt_entry))
82
83 #define ALIGN(s) (((s) + ((MIN_ALIGN)-1)) & ~((MIN_ALIGN)-1))
84
85 struct error_target {
86         struct xt_entry_target t;
87         char error[IPT_TABLE_MAXNAMELEN];
88 };
89
90 struct connman_iptables_entry {
91         int offset;
92         int builtin;
93
94         struct ipt_entry *entry;
95 };
96
97 struct connman_iptables {
98         int ipt_sock;
99
100         struct ipt_getinfo *info;
101         struct ipt_get_entries *blob_entries;
102
103         unsigned int num_entries;
104         unsigned int old_entries;
105         unsigned int size;
106
107         unsigned int underflow[NF_INET_NUMHOOKS];
108         unsigned int hook_entry[NF_INET_NUMHOOKS];
109
110         GList *entries;
111 };
112
113 static GHashTable *table_hash = NULL;
114
115 static struct ipt_entry *get_entry(struct connman_iptables *table,
116                                         unsigned int offset)
117 {
118         return (struct ipt_entry *)((char *)table->blob_entries->entrytable +
119                                                                         offset);
120 }
121
122 static int is_hook_entry(struct connman_iptables *table,
123                                 struct ipt_entry *entry)
124 {
125         unsigned int i;
126
127         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
128                 if ((table->info->valid_hooks & (1 << i))
129                 && get_entry(table, table->info->hook_entry[i]) == entry)
130                         return i;
131         }
132
133         return -1;
134 }
135
136 static unsigned long entry_to_offset(struct connman_iptables *table,
137                                         struct ipt_entry *entry)
138 {
139         return (void *)entry - (void *)table->blob_entries->entrytable;
140 }
141
142 static int target_to_verdict(char *target_name)
143 {
144         if (!strcmp(target_name, LABEL_ACCEPT))
145                 return -NF_ACCEPT - 1;
146
147         if (!strcmp(target_name, LABEL_DROP))
148                 return -NF_DROP - 1;
149
150         if (!strcmp(target_name, LABEL_QUEUE))
151                 return -NF_QUEUE - 1;
152
153         if (!strcmp(target_name, LABEL_RETURN))
154                 return XT_RETURN;
155
156         return 0;
157 }
158
159 static gboolean is_builtin_target(char *target_name)
160 {
161         if (!strcmp(target_name, LABEL_ACCEPT) ||
162                 !strcmp(target_name, LABEL_DROP) ||
163                 !strcmp(target_name, LABEL_QUEUE) ||
164                 !strcmp(target_name, LABEL_RETURN))
165                 return TRUE;
166
167         return FALSE;
168 }
169
170 static gboolean is_jump(struct connman_iptables_entry *e)
171 {
172         struct xt_entry_target *target;
173
174         target = ipt_get_target(e->entry);
175
176         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
177                 struct xt_standard_target *t;
178
179                 t = (struct xt_standard_target *)target;
180
181                 switch (t->verdict) {
182                 case XT_RETURN:
183                 case -NF_ACCEPT - 1:
184                 case -NF_DROP - 1:
185                 case -NF_QUEUE - 1:
186                 case -NF_STOP - 1:
187                         return false;
188
189                 default:
190                         return true;
191                 }
192         }
193
194         return false;
195 }
196
197 static gboolean is_chain(struct connman_iptables *table,
198                                 struct connman_iptables_entry *e)
199 {
200         struct ipt_entry *entry;
201         struct xt_entry_target *target;
202
203         entry = e->entry;
204         if (e->builtin >= 0)
205                 return TRUE;
206
207         target = ipt_get_target(entry);
208         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
209                 return TRUE;
210
211         return FALSE;
212 }
213
214 static GList *find_chain_head(struct connman_iptables *table,
215                                 char *chain_name)
216 {
217         GList *list;
218         struct connman_iptables_entry *head;
219         struct ipt_entry *entry;
220         struct xt_entry_target *target;
221         int builtin;
222
223         for (list = table->entries; list; list = list->next) {
224                 head = list->data;
225                 entry = head->entry;
226
227                 /* Buit-in chain */
228                 builtin = head->builtin;
229                 if (builtin >= 0 && !strcmp(hooknames[builtin], chain_name))
230                         break;
231
232                 /* User defined chain */
233                 target = ipt_get_target(entry);
234                 if (!strcmp(target->u.user.name, IPT_ERROR_TARGET) &&
235                     !strcmp((char *)target->data, chain_name))
236                         break;
237         }
238
239         return list;
240 }
241
242 static GList *find_chain_tail(struct connman_iptables *table,
243                                 char *chain_name)
244 {
245         struct connman_iptables_entry *tail;
246         GList *chain_head, *list;
247
248         chain_head = find_chain_head(table, chain_name);
249         if (chain_head == NULL)
250                 return NULL;
251
252         /* Then we look for the next chain */
253         for (list = chain_head->next; list; list = list->next) {
254                 tail = list->data;
255
256                 if (is_chain(table, tail))
257                         return list;
258         }
259
260         /* Nothing found, we return the table end */
261         return g_list_last(table->entries);
262 }
263
264
265 static void update_offsets(struct connman_iptables *table)
266 {
267         GList *list, *prev;
268         struct connman_iptables_entry *entry, *prev_entry;
269
270         for (list = table->entries; list; list = list->next) {
271                 entry = list->data;
272
273                 if (list == table->entries) {
274                         entry->offset = 0;
275
276                         continue;
277                 }
278
279                 prev = list->prev;
280                 prev_entry = prev->data;
281
282                 entry->offset = prev_entry->offset +
283                                         prev_entry->entry->next_offset;
284         }
285 }
286
287 static void update_targets_reference(struct connman_iptables *table,
288                                 struct connman_iptables_entry *entry_before,
289                                 struct connman_iptables_entry *modified_entry)
290 {
291         struct connman_iptables_entry *tmp;
292         struct xt_standard_target *t;
293         GList *list;
294
295         for (list = table->entries; list; list = list->next) {
296                 tmp = list->data;
297
298                 if (!is_jump(tmp))
299                         continue;
300
301                 t = (struct xt_standard_target *)ipt_get_target(tmp->entry);
302
303                 if (t->verdict > entry_before->offset)
304                         t->verdict += modified_entry->entry->next_offset;
305         }
306 }
307
308 static int iptables_add_entry(struct connman_iptables *table,
309                                 struct ipt_entry *entry, GList *before,
310                                         int builtin)
311 {
312         struct connman_iptables_entry *e, *entry_before;
313
314         if (table == NULL)
315                 return -1;
316
317         e = g_try_malloc0(sizeof(struct connman_iptables_entry));
318         if (e == NULL)
319                 return -1;
320
321         e->entry = entry;
322         e->builtin = builtin;
323
324         table->entries = g_list_insert_before(table->entries, before, e);
325         table->num_entries++;
326         table->size += entry->next_offset;
327
328         if (before == NULL) {
329                 e->offset = table->size - entry->next_offset;
330
331                 return 0;
332         }
333
334         entry_before = before->data;
335
336         /*
337          * We've just appended/insterted a new entry. All references
338          * should be bumped accordingly.
339          */
340         update_targets_reference(table, entry_before, e);
341
342         update_offsets(table);
343
344         return 0;
345 }
346
347 static int remove_table_entry(struct connman_iptables *table,
348                                 struct connman_iptables_entry *entry)
349 {
350         int removed = 0;
351
352         table->num_entries--;
353         table->size -= entry->entry->next_offset;
354         removed = entry->entry->next_offset;
355
356         g_free(entry->entry);
357
358         table->entries = g_list_remove(table->entries, entry);
359
360         return removed;
361 }
362
363 static int iptables_flush_chain(struct connman_iptables *table,
364                                                 char *name)
365 {
366         GList *chain_head, *chain_tail, *list, *next;
367         struct connman_iptables_entry *entry;
368         int builtin, removed = 0;
369
370         chain_head = find_chain_head(table, name);
371         if (chain_head == NULL)
372                 return -EINVAL;
373
374         chain_tail = find_chain_tail(table, name);
375         if (chain_tail == NULL)
376                 return -EINVAL;
377
378         entry = chain_head->data;
379         builtin = entry->builtin;
380
381         if (builtin >= 0)
382                 list = chain_head;
383         else
384                 list = chain_head->next;
385
386         if (list == chain_tail->prev)
387                 return 0;
388
389         while (list != chain_tail->prev) {
390                 entry = list->data;
391                 next = g_list_next(list);
392
393                 removed += remove_table_entry(table, entry);
394
395                 list = next;
396         }
397
398         if (builtin >= 0) {
399                 struct connman_iptables_entry *e;
400
401                 entry = list->data;
402
403                 entry->builtin = builtin;
404
405                 table->underflow[builtin] -= removed;
406
407                 for (list = chain_tail; list; list = list->next) {
408                         e = list->data;
409
410                         builtin = e->builtin;
411                         if (builtin < 0)
412                                 continue;
413
414                         table->hook_entry[builtin] -= removed;
415                         table->underflow[builtin] -= removed;
416                 }
417         }
418
419         update_offsets(table);
420
421         return 0;
422 }
423
424 static int iptables_add_chain(struct connman_iptables *table,
425                                         char *name)
426 {
427         GList *last;
428         struct ipt_entry *entry_head;
429         struct ipt_entry *entry_return;
430         struct error_target *error;
431         struct ipt_standard_target *standard;
432         u_int16_t entry_head_size, entry_return_size;
433
434         last = g_list_last(table->entries);
435
436         /*
437          * An empty chain is composed of:
438          * - A head entry, with no match and an error target.
439          *   The error target data is the chain name.
440          * - A tail entry, with no match and a standard target.
441          *   The standard target verdict is XT_RETURN (return to the
442          *   caller).
443          */
444
445         /* head entry */
446         entry_head_size = sizeof(struct ipt_entry) +
447                                 sizeof(struct error_target);
448         entry_head = g_try_malloc0(entry_head_size);
449         if (entry_head == NULL)
450                 goto err_head;
451
452         memset(entry_head, 0, entry_head_size);
453
454         entry_head->target_offset = sizeof(struct ipt_entry);
455         entry_head->next_offset = entry_head_size;
456
457         error = (struct error_target *) entry_head->elems;
458         strcpy(error->t.u.user.name, IPT_ERROR_TARGET);
459         error->t.u.user.target_size = ALIGN(sizeof(struct error_target));
460         strcpy(error->error, name);
461
462         if (iptables_add_entry(table, entry_head, last, -1) < 0)
463                 goto err_head;
464
465         /* tail entry */
466         entry_return_size = sizeof(struct ipt_entry) +
467                                 sizeof(struct ipt_standard_target);
468         entry_return = g_try_malloc0(entry_return_size);
469         if (entry_return == NULL)
470                 goto err;
471
472         memset(entry_return, 0, entry_return_size);
473
474         entry_return->target_offset = sizeof(struct ipt_entry);
475         entry_return->next_offset = entry_return_size;
476
477         standard = (struct ipt_standard_target *) entry_return->elems;
478         standard->target.u.user.target_size =
479                                 ALIGN(sizeof(struct ipt_standard_target));
480         standard->verdict = XT_RETURN;
481
482         if (iptables_add_entry(table, entry_return, last, -1) < 0)
483                 goto err;
484
485         return 0;
486
487 err:
488         g_free(entry_return);
489 err_head:
490         g_free(entry_head);
491
492         return -ENOMEM;
493 }
494
495 static int iptables_delete_chain(struct connman_iptables *table, char *name)
496 {
497         struct connman_iptables_entry *entry;
498         GList *chain_head, *chain_tail;
499
500         chain_head = find_chain_head(table, name);
501         if (chain_head == NULL)
502                 return -EINVAL;
503
504         entry = chain_head->data;
505
506         /* We cannot remove builtin chain */
507         if (entry->builtin >= 0)
508                 return -EINVAL;
509
510         chain_tail = find_chain_tail(table, name);
511         if (chain_tail == NULL)
512                 return -EINVAL;
513
514         /* Chain must be flushed */
515         if (chain_head->next != chain_tail->prev)
516                 return -EINVAL;
517
518         remove_table_entry(table, entry);
519
520         entry = chain_tail->prev->data;
521         remove_table_entry(table, entry);
522
523         update_offsets(table);
524
525         return 0;
526 }
527
528 static struct ipt_entry *
529 new_rule(struct ipt_ip *ip, char *target_name,
530                 struct xtables_target *xt_t,
531                 char *match_name, struct xtables_match *xt_m)
532 {
533         struct ipt_entry *new_entry;
534         size_t match_size, target_size;
535
536         if (xt_m)
537                 match_size = xt_m->m->u.match_size;
538         else
539                 match_size = 0;
540
541         if (xt_t)
542                 target_size = ALIGN(xt_t->t->u.target_size);
543         else
544                 target_size = ALIGN(sizeof(struct xt_standard_target));
545
546         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
547                                                                 match_size);
548         if (new_entry == NULL)
549                 return NULL;
550
551         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
552
553         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
554         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
555                                                                 match_size;
556         if (xt_m) {
557                 struct xt_entry_match *entry_match;
558
559                 entry_match = (struct xt_entry_match *)new_entry->elems;
560                 memcpy(entry_match, xt_m->m, match_size);
561         }
562
563         if (xt_t) {
564                 struct xt_entry_target *entry_target;
565
566                 entry_target = ipt_get_target(new_entry);
567                 memcpy(entry_target, xt_t->t, target_size);
568         }
569
570         return new_entry;
571 }
572
573 static void update_hooks(struct connman_iptables *table, GList *chain_head,
574                                 struct ipt_entry *entry)
575 {
576         GList *list;
577         struct connman_iptables_entry *head, *e;
578         int builtin;
579
580         if (chain_head == NULL)
581                 return;
582
583         head = chain_head->data;
584
585         builtin = head->builtin;
586         if (builtin < 0)
587                 return;
588
589         table->underflow[builtin] += entry->next_offset;
590
591         for (list = chain_head->next; list; list = list->next) {
592                 e = list->data;
593
594                 builtin = e->builtin;
595                 if (builtin < 0)
596                         continue;
597
598                 table->hook_entry[builtin] += entry->next_offset;
599                 table->underflow[builtin] += entry->next_offset;
600         }
601 }
602
603 static struct ipt_entry *prepare_rule_inclusion(struct connman_iptables *table,
604                                 struct ipt_ip *ip, char *chain_name,
605                                 char *target_name, struct xtables_target *xt_t,
606                                 char *match_name, struct xtables_match *xt_m,
607                                 int *builtin)
608 {
609         GList *chain_tail, *chain_head;
610         struct ipt_entry *new_entry;
611         struct connman_iptables_entry *head;
612
613         chain_head = find_chain_head(table, chain_name);
614         if (chain_head == NULL)
615                 return NULL;
616
617         chain_tail = find_chain_tail(table, chain_name);
618         if (chain_tail == NULL)
619                 return NULL;
620
621         new_entry = new_rule(ip, target_name, xt_t, match_name, xt_m);
622         if (new_entry == NULL)
623                 return NULL;
624
625         update_hooks(table, chain_head, new_entry);
626
627         /*
628          * If the chain is builtin, and does not have any rule,
629          * then the one that we're inserting is becoming the head
630          * and thus needs the builtin flag.
631          */
632         head = chain_head->data;
633         if (head->builtin < 0)
634                 *builtin = -1;
635         else if (chain_head == chain_tail->prev) {
636                 *builtin = head->builtin;
637                 head->builtin = -1;
638         }
639
640         return new_entry;
641 }
642
643 static int iptables_append_rule(struct connman_iptables *table,
644                                 struct ipt_ip *ip, char *chain_name,
645                                 char *target_name, struct xtables_target *xt_t,
646                                 char *match_name, struct xtables_match *xt_m)
647 {
648         GList *chain_tail;
649         struct ipt_entry *new_entry;
650         int builtin = -1, ret;
651
652         DBG("");
653
654         chain_tail = find_chain_tail(table, chain_name);
655         if (chain_tail == NULL)
656                 return -EINVAL;
657
658         new_entry = prepare_rule_inclusion(table, ip, chain_name,
659                         target_name, xt_t, match_name, xt_m, &builtin);
660         if (new_entry == NULL)
661                 return -EINVAL;
662
663         ret = iptables_add_entry(table, new_entry, chain_tail->prev, builtin);
664         if (ret < 0)
665                 g_free(new_entry);
666
667         return ret;
668 }
669
670 static int iptables_insert_rule(struct connman_iptables *table,
671                                 struct ipt_ip *ip, char *chain_name,
672                                 char *target_name, struct xtables_target *xt_t,
673                                 char *match_name, struct xtables_match *xt_m)
674 {
675         struct ipt_entry *new_entry;
676         int builtin = -1, ret;
677         GList *chain_head;
678
679         chain_head = find_chain_head(table, chain_name);
680         if (chain_head == NULL)
681                 return -EINVAL;
682
683         new_entry = prepare_rule_inclusion(table, ip, chain_name,
684                         target_name, xt_t, match_name, xt_m, &builtin);
685         if (new_entry == NULL)
686                 return -EINVAL;
687
688         ret = iptables_add_entry(table, new_entry, chain_head->next, builtin);
689         if (ret < 0)
690                 g_free(new_entry);
691
692         return ret;
693 }
694
695 static struct ipt_replace *
696 iptables_blob(struct connman_iptables *table)
697 {
698         struct ipt_replace *r;
699         GList *list;
700         struct connman_iptables_entry *e;
701         unsigned char *entry_index;
702
703         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
704         if (r == NULL)
705                 return NULL;
706
707         memset(r, 0, sizeof(*r) + table->size);
708
709         r->counters = g_try_malloc0(sizeof(struct xt_counters)
710                                 * table->old_entries);
711         if (r->counters == NULL) {
712                 g_free(r);
713                 return NULL;
714         }
715
716         strcpy(r->name, table->info->name);
717         r->num_entries = table->num_entries;
718         r->size = table->size;
719
720         r->num_counters = table->old_entries;
721         r->valid_hooks  = table->info->valid_hooks;
722
723         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
724         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
725
726         entry_index = (unsigned char *)r->entries;
727         for (list = table->entries; list; list = list->next) {
728                 e = list->data;
729
730                 memcpy(entry_index, e->entry, e->entry->next_offset);
731                 entry_index += e->entry->next_offset;
732         }
733
734         return r;
735 }
736
737 static void dump_ip(struct ipt_entry *entry)
738 {
739         struct ipt_ip *ip = &entry->ip;
740         char ip_string[INET6_ADDRSTRLEN];
741         char ip_mask[INET6_ADDRSTRLEN];
742
743         if (strlen(ip->iniface))
744                 connman_info("\tin %s", ip->iniface);
745
746         if (strlen(ip->outiface))
747                 connman_info("\tout %s", ip->outiface);
748
749         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
750                         inet_ntop(AF_INET, &ip->smsk,
751                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
752                 connman_info("\tsrc %s/%s", ip_string, ip_mask);
753
754         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
755                         inet_ntop(AF_INET, &ip->dmsk,
756                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
757                 connman_info("\tdst %s/%s", ip_string, ip_mask);
758 }
759
760 static void dump_target(struct connman_iptables *table,
761                                 struct ipt_entry *entry)
762
763 {
764         struct xtables_target *xt_t;
765         struct xt_entry_target *target;
766
767         target = ipt_get_target(entry);
768
769         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
770                 struct xt_standard_target *t;
771
772                 t = (struct xt_standard_target *)target;
773
774                 switch (t->verdict) {
775                 case XT_RETURN:
776                         connman_info("\ttarget RETURN");
777                         break;
778
779                 case -NF_ACCEPT - 1:
780                         connman_info("\ttarget ACCEPT");
781                         break;
782
783                 case -NF_DROP - 1:
784                         connman_info("\ttarget DROP");
785                         break;
786
787                 case -NF_QUEUE - 1:
788                         connman_info("\ttarget QUEUE");
789                         break;
790
791                 case -NF_STOP - 1:
792                         connman_info("\ttarget STOP");
793                         break;
794
795                 default:
796                         connman_info("\tJUMP @%p (0x%x)",
797                                 (char*)table->blob_entries->entrytable +
798                                 t->verdict, t->verdict);
799                         break;
800                 }
801
802                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
803                                                 XTF_LOAD_MUST_SUCCEED);
804
805                 if(xt_t->print != NULL)
806                         xt_t->print(NULL, target, 1);
807         } else {
808                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
809                 if (xt_t == NULL) {
810                         connman_info("\ttarget %s", target->u.user.name);
811                         return;
812                 }
813
814                 if(xt_t->print != NULL) {
815                         connman_info("\ttarget ");
816                         xt_t->print(NULL, target, 1);
817                 }
818         }
819 }
820
821 static void dump_match(struct connman_iptables *table, struct ipt_entry *entry)
822 {
823         struct xtables_match *xt_m;
824         struct xt_entry_match *match;
825
826         if (entry->elems == (unsigned char *)entry + entry->target_offset)
827                 return;
828
829         match = (struct xt_entry_match *) entry->elems;
830
831         if (!strlen(match->u.user.name))
832                 return;
833
834         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
835         if (xt_m == NULL)
836                 goto out;
837
838         if(xt_m->print != NULL) {
839                 connman_info("\tmatch ");
840                 xt_m->print(NULL, match, 1);
841
842                 return;
843         }
844
845 out:
846         connman_info("\tmatch %s", match->u.user.name);
847
848 }
849
850 static int dump_entry(struct ipt_entry *entry,
851                                 struct connman_iptables *table)
852 {
853         struct xt_entry_target *target;
854         unsigned int offset;
855         int builtin;
856
857         offset = (char *)entry - (char *)table->blob_entries->entrytable;
858         target = ipt_get_target(entry);
859         builtin = is_hook_entry(table, entry);
860
861         if (entry_to_offset(table, entry) + entry->next_offset ==
862                                         table->blob_entries->size) {
863                 connman_info("End of CHAIN 0x%x", offset);
864                 return 0;
865         }
866
867         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
868                 connman_info("USER CHAIN (%s) %p  match %p  target %p  size %d",
869                         target->data, entry, entry->elems,
870                         (char *)entry + entry->target_offset,
871                                 entry->next_offset);
872
873                 return 0;
874         } else if (builtin >= 0) {
875                 connman_info("CHAIN (%s) %p  match %p  target %p  size %d",
876                         hooknames[builtin], entry, entry->elems,
877                         (char *)entry + entry->target_offset,
878                                 entry->next_offset);
879         } else {
880                 connman_info("RULE %p  match %p  target %p  size %d", entry,
881                         entry->elems,
882                         (char *)entry + entry->target_offset,
883                                 entry->next_offset);
884         }
885
886         dump_match(table, entry);
887         dump_target(table, entry);
888         dump_ip(entry);
889
890         return 0;
891 }
892
893 static void iptables_dump(struct connman_iptables *table)
894 {
895         connman_info("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
896                         table->info->name,
897                         table->info->valid_hooks, table->info->num_entries,
898                                 table->info->size);
899
900         ENTRY_ITERATE(table->blob_entries->entrytable,
901                         table->blob_entries->size,
902                         dump_entry, table);
903
904 }
905
906 static int iptables_get_entries(struct connman_iptables *table)
907 {
908         socklen_t entry_size;
909
910         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
911
912         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
913                                 table->blob_entries, &entry_size);
914 }
915
916 static int iptables_replace(struct connman_iptables *table,
917                                         struct ipt_replace *r)
918 {
919         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
920                          sizeof(*r) + r->size);
921 }
922
923 static int add_entry(struct ipt_entry *entry, struct connman_iptables *table)
924 {
925         struct ipt_entry *new_entry;
926         int builtin;
927
928         new_entry = g_try_malloc0(entry->next_offset);
929         if (new_entry == NULL)
930                 return -ENOMEM;
931
932         memcpy(new_entry, entry, entry->next_offset);
933
934         builtin = is_hook_entry(table, entry);
935
936         return iptables_add_entry(table, new_entry, NULL, builtin);
937 }
938
939 static void table_cleanup(struct connman_iptables *table)
940 {
941         GList *list;
942         struct connman_iptables_entry *entry;
943
944         close(table->ipt_sock);
945
946         for (list = table->entries; list; list = list->next) {
947                 entry = list->data;
948
949                 g_free(entry->entry);
950                 g_free(entry);
951         }
952
953         g_list_free(table->entries);
954         g_free(table->info);
955         g_free(table->blob_entries);
956         g_free(table);
957 }
958
959 static struct connman_iptables *iptables_init(char *table_name)
960 {
961         struct connman_iptables *table;
962         socklen_t s;
963
964         DBG("%s", table_name);
965
966         table = g_hash_table_lookup(table_hash, table_name);
967         if (table != NULL)
968                 return table;
969
970         table = g_try_new0(struct connman_iptables, 1);
971         if (table == NULL)
972                 return NULL;
973
974         table->info = g_try_new0(struct ipt_getinfo, 1);
975         if (table->info == NULL)
976                 goto err;
977
978         table->ipt_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
979         if (table->ipt_sock < 0)
980                 goto err;
981
982         s = sizeof(*table->info);
983         strcpy(table->info->name, table_name);
984         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
985                                                 table->info, &s) < 0)
986                 goto err;
987
988         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
989                                                 table->info->size);
990         if (table->blob_entries == NULL)
991                 goto err;
992
993         strcpy(table->blob_entries->name, table_name);
994         table->blob_entries->size = table->info->size;
995
996         if (iptables_get_entries(table) < 0)
997                 goto err;
998
999         table->num_entries = 0;
1000         table->old_entries = table->info->num_entries;
1001         table->size = 0;
1002
1003         memcpy(table->underflow, table->info->underflow,
1004                                 sizeof(table->info->underflow));
1005         memcpy(table->hook_entry, table->info->hook_entry,
1006                                 sizeof(table->info->hook_entry));
1007
1008         ENTRY_ITERATE(table->blob_entries->entrytable,
1009                         table->blob_entries->size,
1010                                 add_entry, table);
1011
1012         g_hash_table_insert(table_hash, g_strdup(table_name), table);
1013
1014         return table;
1015
1016 err:
1017
1018         table_cleanup(table);
1019
1020         return NULL;
1021 }
1022
1023 static struct xtables_target *prepare_target(struct connman_iptables *table,
1024                                                         char *target_name)
1025 {
1026         struct xtables_target *xt_t = NULL;
1027         gboolean is_builtin, is_user_defined;
1028         GList *chain_head = NULL;
1029         size_t target_size;
1030
1031         is_builtin = FALSE;
1032         is_user_defined = FALSE;
1033
1034         if (is_builtin_target(target_name))
1035                 is_builtin = TRUE;
1036         else {
1037                 chain_head = find_chain_head(table, target_name);
1038                 if (chain_head != NULL && chain_head->next != NULL)
1039                         is_user_defined = TRUE;
1040         }
1041
1042         if (is_builtin || is_user_defined)
1043                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1044                                                 XTF_LOAD_MUST_SUCCEED);
1045         else
1046                 xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1047
1048         if (xt_t == NULL)
1049                 return NULL;
1050
1051         target_size = ALIGN(sizeof(struct ipt_entry_target)) + xt_t->size;
1052
1053         xt_t->t = g_try_malloc0(target_size);
1054         if (xt_t->t == NULL)
1055                 return NULL;
1056
1057         xt_t->t->u.target_size = target_size;
1058
1059         if (is_builtin || is_user_defined) {
1060                 struct xt_standard_target *target;
1061
1062                 target = (struct xt_standard_target *)(xt_t->t);
1063                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
1064
1065                 if (is_builtin == TRUE)
1066                         target->verdict = target_to_verdict(target_name);
1067                 else if (is_user_defined == TRUE) {
1068                         struct connman_iptables_entry *target_rule;
1069
1070                         if (chain_head == NULL) {
1071                                 g_free(xt_t->t);
1072                                 return NULL;
1073                         }
1074
1075                         target_rule = chain_head->next->data;
1076                         target->verdict = target_rule->offset;
1077                 }
1078         } else {
1079                 strcpy(xt_t->t->u.user.name, target_name);
1080                 xt_t->t->u.user.revision = xt_t->revision;
1081                 if (xt_t->init != NULL)
1082                         xt_t->init(xt_t->t);
1083         }
1084
1085         return xt_t;
1086 }
1087
1088 static struct option iptables_opts[] = {
1089         {.name = "append",        .has_arg = 1, .val = 'A'},
1090         {.name = "flush-chain",   .has_arg = 1, .val = 'F'},
1091         {.name = "insert",        .has_arg = 1, .val = 'I'},
1092         {.name = "list",          .has_arg = 2, .val = 'L'},
1093         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
1094         {.name = "delete-chain",  .has_arg = 1, .val = 'X'},
1095         {.name = "destination",   .has_arg = 1, .val = 'd'},
1096         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
1097         {.name = "jump",          .has_arg = 1, .val = 'j'},
1098         {.name = "match",         .has_arg = 1, .val = 'm'},
1099         {.name = "out-interface", .has_arg = 1, .val = 'o'},
1100         {.name = "source",        .has_arg = 1, .val = 's'},
1101         {.name = "table",         .has_arg = 1, .val = 't'},
1102         {NULL},
1103 };
1104
1105 struct xtables_globals iptables_globals = {
1106         .option_offset = 0,
1107         .opts = iptables_opts,
1108         .orig_opts = iptables_opts,
1109 };
1110
1111 static int iptables_command(int argc, char *argv[])
1112 {
1113         struct connman_iptables *table;
1114         struct xtables_match *xt_m;
1115         struct xtables_target *xt_t;
1116         struct ipt_ip ip;
1117         char *table_name, *chain, *new_chain, *match_name, *target_name;
1118         char *flush_chain, *delete_chain;
1119         int c, ret, in_len, out_len;
1120         size_t size;
1121         gboolean dump, invert, insert;
1122         struct in_addr src, dst;
1123
1124         if (argc == 0)
1125                 return -EINVAL;
1126
1127         dump = FALSE;
1128         invert = FALSE;
1129         insert = FALSE;
1130         table_name = chain = new_chain = match_name = target_name = NULL;
1131         flush_chain = delete_chain = NULL;
1132         memset(&ip, 0, sizeof(struct ipt_ip));
1133         table = NULL;
1134         xt_m = NULL;
1135         xt_t = NULL;
1136         ret = 0;
1137
1138         optind = 0;
1139
1140         while ((c = getopt_long(argc, argv, "-A:F:I:L::N:X:d:j:i:m:o:s:t:",
1141                                         iptables_globals.opts, NULL)) != -1) {
1142                 switch (c) {
1143                 case 'A':
1144                         /* It is either -A, -D or -I at once */
1145                         if (chain)
1146                                 goto out;
1147
1148                         chain = optarg;
1149                         break;
1150
1151                 case 'F':
1152                         flush_chain = optarg;
1153                         break;
1154
1155                 case 'I':
1156                         /* It is either -A, -D or -I at once */
1157                         if (chain)
1158                                 goto out;
1159
1160                         chain = optarg;
1161                         insert = TRUE;
1162                         break;
1163
1164                 case 'L':
1165                         dump = TRUE;
1166                         break;
1167
1168                 case 'N':
1169                         new_chain = optarg;
1170                         break;
1171
1172                 case 'X':
1173                         delete_chain = optarg;
1174                         break;
1175
1176                 case 'd':
1177                         if (!inet_pton(AF_INET, optarg, &dst))
1178                                 break;
1179
1180                         ip.dst = dst;
1181                         inet_pton(AF_INET, "255.255.255.255", &ip.dmsk);
1182
1183                         if (invert)
1184                                 ip.invflags |= IPT_INV_DSTIP;
1185
1186                         break;
1187
1188                 case 'i':
1189                         in_len = strlen(optarg);
1190
1191                         if (in_len + 1 > IFNAMSIZ)
1192                                 break;
1193
1194                         strcpy(ip.iniface, optarg);
1195                         memset(ip.iniface_mask, 0xff, in_len + 1);
1196
1197                         if (invert)
1198                                 ip.invflags |= IPT_INV_VIA_IN;
1199
1200                         break;
1201
1202                 case 'j':
1203                         target_name = optarg;
1204                         break;
1205
1206                 case 'm':
1207                         match_name = optarg;
1208
1209                         xt_m = xtables_find_match(optarg, XTF_LOAD_MUST_SUCCEED, NULL);
1210                         size = ALIGN(sizeof(struct ipt_entry_match)) +
1211                                                                 xt_m->size;
1212                         xt_m->m = g_try_malloc0(size);
1213                         if (xt_m == NULL)
1214                                 goto out;
1215                         xt_m->m->u.match_size = size;
1216                         strcpy(xt_m->m->u.user.name, xt_m->name);
1217                         xt_m->m->u.user.revision = xt_m->revision;
1218                         if (xt_m->init != NULL)
1219                                 xt_m->init(xt_m->m);
1220                         if (xt_m != xt_m->next) {
1221                                 iptables_globals.opts =
1222                                 xtables_merge_options(
1223 #if XTABLES_VERSION_CODE > 5
1224                                                 iptables_globals.orig_opts,
1225 #endif
1226                                                 iptables_globals.opts,
1227                                                 xt_m->extra_opts,
1228                                                 &xt_m->option_offset);
1229                                 if (iptables_globals.opts == NULL)
1230                                         goto out;
1231                         }
1232
1233                         break;
1234
1235                 case 'o':
1236                         out_len = strlen(optarg);
1237
1238                         if (out_len + 1 > IFNAMSIZ)
1239                                 break;
1240
1241                         strcpy(ip.outiface, optarg);
1242                         memset(ip.outiface_mask, 0xff, out_len + 1);
1243
1244                         if (invert)
1245                                 ip.invflags |= IPT_INV_VIA_OUT;
1246
1247                         break;
1248
1249                 case 's':
1250                         if (!inet_pton(AF_INET, optarg, &src))
1251                                 break;
1252
1253                         ip.src = src;
1254                         inet_pton(AF_INET, "255.255.255.255", &ip.smsk);
1255
1256                         if (invert)
1257                                 ip.invflags |= IPT_INV_SRCIP;
1258
1259                         break;
1260
1261                 case 't':
1262                         table_name = optarg;
1263                         break;
1264
1265                 case 1:
1266                         if (optarg[0] == '!' && optarg[1] == '\0') {
1267                                 invert = TRUE;
1268                                 optarg[0] = '\0';
1269                                 continue;
1270                         }
1271
1272                         connman_error("Invalid option");
1273
1274                         ret = -EINVAL;
1275                         goto out;
1276
1277                 default:
1278                         if (xt_t == NULL || xt_t->parse == NULL ||
1279                             !xt_t->parse(c - xt_t->option_offset, argv, invert,
1280                                         &xt_t->tflags, NULL, &xt_t->t)) {
1281                                 if (xt_m == NULL || xt_m->parse == NULL)
1282                                         break;
1283
1284                                 xt_m->parse(c - xt_m->option_offset, argv,
1285                                         invert, &xt_m->mflags, NULL, &xt_m->m);
1286                         }
1287
1288                         break;
1289                 }
1290
1291                 invert = FALSE;
1292         }
1293
1294         if (table_name == NULL)
1295                 table_name = "filter";
1296
1297         table = iptables_init(table_name);
1298         if (table == NULL) {
1299                 ret = -EINVAL;
1300                 goto out;
1301         }
1302
1303         if (delete_chain != NULL) {
1304                 printf("Delete chain %s\n", delete_chain);
1305
1306                 iptables_delete_chain(table, delete_chain);
1307
1308                 goto out;
1309         }
1310
1311         if (dump) {
1312                 iptables_dump(table);
1313
1314                 ret = 0;
1315                 goto out;
1316         }
1317
1318         if (flush_chain) {
1319                 DBG("Flush chain %s", flush_chain);
1320
1321                 iptables_flush_chain(table, flush_chain);
1322
1323                 goto out;
1324         }
1325
1326         if (chain && new_chain) {
1327                 ret = -EINVAL;
1328                 goto out;
1329         }
1330
1331         if (new_chain) {
1332                 DBG("New chain %s", new_chain);
1333
1334                 ret = iptables_add_chain(table, new_chain);
1335                 goto out;
1336         }
1337
1338         if (chain) {
1339                 xt_t = prepare_target(table, target_name);
1340                 if (xt_t == NULL)
1341                         goto out;
1342
1343                 iptables_globals.opts =
1344                         xtables_merge_options(
1345 #if XTABLES_VERSION_CODE > 5
1346                                         iptables_globals.orig_opts,
1347 #endif
1348                                         iptables_globals.opts,
1349                                         xt_t->extra_opts,
1350                                         &xt_t->option_offset);
1351                 if (iptables_globals.opts == NULL)
1352                         goto out;
1353
1354                 if (insert == TRUE) {
1355                         DBG("Inserting %s to %s (match %s)",
1356                                         target_name, chain, match_name);
1357
1358                         ret = iptables_insert_rule(table, &ip, chain,
1359                                         target_name, xt_t, match_name, xt_m);
1360
1361                         goto out;
1362                 } else {
1363                         DBG("Adding %s to %s (match %s)",
1364                                         target_name, chain, match_name);
1365
1366                         ret = iptables_append_rule(table, &ip, chain,
1367                                         target_name, xt_t, match_name, xt_m);
1368
1369                         goto out;
1370                 }
1371         }
1372
1373 out:
1374         if (xt_t)
1375                 g_free(xt_t->t);
1376
1377         if (xt_m)
1378                 g_free(xt_m->m);
1379
1380         return ret;
1381 }
1382
1383 int __connman_iptables_command(const char *format, ...)
1384 {
1385         char **argv, **arguments, *command;
1386         int argc, i, ret;
1387         va_list args;
1388
1389         if (format == NULL)
1390                 return -EINVAL;
1391
1392         va_start(args, format);
1393
1394         command = g_strdup_vprintf(format, args);
1395
1396         va_end(args);
1397
1398         if (command == NULL)
1399                 return -ENOMEM;
1400
1401         arguments = g_strsplit_set(command, " ", -1);
1402
1403         for (argc = 0; arguments[argc]; argc++);
1404         ++argc;
1405
1406         DBG("command %s argc %d", command, argc);
1407
1408         argv = g_try_malloc0(argc * sizeof(char *));
1409         if (argv == NULL) {
1410                 g_free(command);
1411                 g_strfreev(arguments);
1412                 return -ENOMEM;
1413         }
1414
1415         argv[0] = "iptables";
1416         for (i = 1; i < argc; i++)
1417                 argv[i] = arguments[i - 1];
1418
1419         ret = iptables_command(argc, argv);
1420
1421         g_free(command);
1422         g_strfreev(arguments);
1423         g_free(argv);
1424
1425         return ret;
1426 }
1427
1428
1429 int __connman_iptables_commit(const char *table_name)
1430 {
1431         struct connman_iptables *table;
1432         struct ipt_replace *repl;
1433         int err;
1434
1435         DBG("%s", table_name);
1436
1437         table = g_hash_table_lookup(table_hash, table_name);
1438         if (table == NULL)
1439                 return -EINVAL;
1440
1441         repl = iptables_blob(table);
1442
1443         err = iptables_replace(table, repl);
1444
1445         g_free(repl->counters);
1446         g_free(repl);
1447
1448         if (err < 0)
1449             return err;
1450
1451         g_hash_table_remove(table_hash, table_name);
1452
1453         return 0;
1454 }
1455
1456 static void remove_table(gpointer user_data)
1457 {
1458         struct connman_iptables *table = user_data;
1459
1460         table_cleanup(table);
1461 }
1462
1463 int __connman_iptables_init(void)
1464 {
1465         DBG("");
1466
1467         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
1468                                                 g_free, remove_table);
1469
1470         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
1471
1472         return 0;
1473
1474 }
1475
1476 void __connman_iptables_cleanup(void)
1477 {
1478         DBG("");
1479
1480         g_hash_table_destroy(table_hash);
1481
1482         xtables_free_opts(1);
1483 }