iptables: Duplicate table name when inserting it
[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 ipt_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         GList *chain_head, *list;
246         struct connman_iptables_entry *head, *tail;
247         struct ipt_entry *entry;
248         struct xt_entry_target *target;
249         int builtin;
250
251         /* First we look for the head */
252         for (list = table->entries; list; list = list->next) {
253                 head = list->data;
254                 entry = head->entry;
255
256                 /* Buit-in chain */
257                 builtin = head->builtin;
258                 if (builtin >= 0 && !strcmp(hooknames[builtin], chain_name))
259                         break;
260
261                 /* User defined chain */
262                 target = ipt_get_target(entry);
263                 if (!strcmp(target->u.user.name, IPT_ERROR_TARGET) &&
264                     !strcmp((char *)target->data, chain_name))
265                         break;
266         }
267
268         if (list == NULL)
269                 return NULL;
270
271         chain_head = list;
272
273         /* Then we look for the next chain */
274         for (list = chain_head->next; list; list = list->next) {
275                 tail = list->data;
276                 entry = tail->entry;
277
278                 if (is_chain(table, tail))
279                         return list;
280         }
281
282         /* Nothing found, we return the table end */
283         return g_list_last(table->entries);
284 }
285
286
287 static void update_offsets(struct connman_iptables *table)
288 {
289         GList *list, *prev;
290         struct connman_iptables_entry *entry, *prev_entry;
291
292         for (list = table->entries; list; list = list->next) {
293                 entry = list->data;
294
295                 if (list == table->entries) {
296                         entry->offset = 0;
297
298                         continue;
299                 }
300
301                 prev = list->prev;
302                 prev_entry = prev->data;
303
304                 entry->offset = prev_entry->offset +
305                                         prev_entry->entry->next_offset;
306         }
307 }
308
309 static int iptables_add_entry(struct connman_iptables *table,
310                                 struct ipt_entry *entry, GList *before,
311                                         int builtin)
312 {
313         GList *list;
314         struct connman_iptables_entry *e, *tmp, *entry_before;
315         struct xt_standard_target *t;
316
317         if (table == NULL)
318                 return -1;
319
320         e = g_try_malloc0(sizeof(struct connman_iptables_entry));
321         if (e == NULL)
322                 return -1;
323
324         e->entry = entry;
325         e->builtin = builtin;
326
327         table->entries = g_list_insert_before(table->entries, before, e);
328         table->num_entries++;
329         table->size += entry->next_offset;
330
331         if (before == NULL) {
332                 e->offset = table->size - entry->next_offset;
333
334                 return 0;
335         }
336
337         entry_before = before->data;
338
339         /*
340          * We've just insterted a new entry. All references before it
341          * should be bumped accordingly.
342          */
343         for (list = table->entries; list != before; list = list->next) {
344                 tmp = list->data;
345
346                 if (!is_jump(tmp))
347                         continue;
348
349                 t = (struct xt_standard_target *)ipt_get_target(tmp->entry);
350
351                 if (t->verdict >= entry_before->offset)
352                         t->verdict += entry->next_offset;
353         }
354
355         update_offsets(table);
356
357         return 0;
358 }
359
360 static int iptables_add_chain(struct connman_iptables *table,
361                                         char *name)
362 {
363         GList *last;
364         struct ipt_entry *entry_head;
365         struct ipt_entry *entry_return;
366         struct ipt_error_target *error;
367         struct ipt_standard_target *standard;
368         u_int16_t entry_head_size, entry_return_size;
369
370         last = g_list_last(table->entries);
371
372         /*
373          * An empty chain is composed of:
374          * - A head entry, with no match and an error target.
375          *   The error target data is the chain name.
376          * - A tail entry, with no match and a standard target.
377          *   The standard target verdict is XT_RETURN (return to the
378          *   caller).
379          */
380
381         /* head entry */
382         entry_head_size = sizeof(struct ipt_entry) +
383                                 sizeof(struct ipt_error_target);
384         entry_head = g_try_malloc0(entry_head_size);
385         if (entry_head == NULL)
386                 goto err;
387
388         memset(entry_head, 0, entry_head_size);
389
390         entry_head->target_offset = sizeof(struct ipt_entry);
391         entry_head->next_offset = entry_head_size;
392
393         error = (struct ipt_error_target *) entry_head->elems;
394         strcpy(error->t.u.user.name, IPT_ERROR_TARGET);
395         error->t.u.user.target_size = ALIGN(sizeof(struct ipt_error_target));
396         strcpy(error->error, name);
397
398         if (iptables_add_entry(table, entry_head, last, -1) < 0)
399                 goto err;
400
401         /* tail entry */
402         entry_return_size = sizeof(struct ipt_entry) +
403                                 sizeof(struct ipt_standard_target);
404         entry_return = g_try_malloc0(entry_return_size);
405         if (entry_return == NULL)
406                 goto err;
407
408         memset(entry_return, 0, entry_return_size);
409
410         entry_return->target_offset = sizeof(struct ipt_entry);
411         entry_return->next_offset = entry_return_size;
412
413         standard = (struct ipt_standard_target *) entry_return->elems;
414         standard->target.u.user.target_size =
415                                 ALIGN(sizeof(struct ipt_standard_target));
416         standard->verdict = XT_RETURN;
417
418         if (iptables_add_entry(table, entry_return, last, -1) < 0)
419                 goto err;
420
421         return 0;
422
423 err:
424         g_free(entry_head);
425         g_free(entry_return);
426
427         return -ENOMEM;
428 }
429
430 static struct ipt_entry *
431 new_rule(struct connman_iptables *table, struct ipt_ip *ip,
432                 char *target_name, struct xtables_target *xt_t,
433                 char *match_name, struct xtables_match *xt_m)
434 {
435         struct ipt_entry *new_entry;
436         size_t match_size, target_size;
437         int is_builtin = is_builtin_target(target_name);
438
439         if (xt_m)
440                 match_size = xt_m->m->u.match_size;
441         else
442                 match_size = 0;
443
444         if (xt_t)
445                 target_size = ALIGN(xt_t->t->u.target_size);
446         else
447                 target_size = ALIGN(sizeof(struct xt_standard_target));
448
449         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
450                                                                 match_size);
451         if (new_entry == NULL)
452                 return NULL;
453
454         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
455
456         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
457         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
458                                                                 match_size;
459         if (xt_m) {
460                 struct xt_entry_match *entry_match;
461
462                 entry_match = (struct xt_entry_match *)new_entry->elems;
463                 memcpy(entry_match, xt_m->m, match_size);
464         }
465
466         if (xt_t) {
467                 struct xt_entry_target *entry_target;
468
469                 if (is_builtin) {
470                         struct xt_standard_target *target;
471
472                         target = (struct xt_standard_target *)(xt_t->t);
473                         strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
474                         target->verdict = target_to_verdict(target_name);
475                 }
476
477                 entry_target = ipt_get_target(new_entry);
478                 memcpy(entry_target, xt_t->t, target_size);
479         } else {
480                 struct connman_iptables_entry *target_rule;
481                 struct xt_standard_target *target;
482                 GList *chain_head;
483
484                 /*
485                  * This is a user defined target, i.e. a chain jump.
486                  * We search for the chain head, and the target verdict
487                  * is the first rule's offset on this chain.
488                  * The offset is from the beginning of the table.
489                  */
490
491                 chain_head = find_chain_head(table, target_name);
492                 if (chain_head == NULL || chain_head->next == NULL) {
493                         g_free(new_entry);
494                         return NULL;
495                 }
496
497                 target_rule = chain_head->next->data;
498
499                 target = (struct xt_standard_target *)ipt_get_target(new_entry);
500                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
501                 target->target.u.user.target_size = target_size;
502                 target->verdict = target_rule->offset;
503         }
504
505         return new_entry;
506 }
507
508 static void update_hooks(struct connman_iptables *table, GList *chain_head,
509                                 struct ipt_entry *entry)
510 {
511         GList *list;
512         struct connman_iptables_entry *head, *e;
513         int builtin;
514
515         if (chain_head == NULL)
516                 return;
517
518         head = chain_head->data;
519
520         builtin = head->builtin;
521         if (builtin < 0)
522                 return;
523
524         table->underflow[builtin] += entry->next_offset;
525
526         for (list = chain_head->next; list; list = list->next) {
527                 e = list->data;
528
529                 builtin = e->builtin;
530                 if (builtin < 0)
531                         continue;
532
533                 table->hook_entry[builtin] += entry->next_offset;
534                 table->underflow[builtin] += entry->next_offset;
535         }
536 }
537
538 static int
539 iptables_add_rule(struct connman_iptables *table,
540                                 struct ipt_ip *ip, char *chain_name,
541                                 char *target_name, struct xtables_target *xt_t,
542                                 char *match_name, struct xtables_match *xt_m)
543 {
544         GList *chain_tail, *chain_head;
545         struct ipt_entry *new_entry;
546         struct connman_iptables_entry *head;
547         int builtin = -1;
548
549         DBG("");
550
551         chain_head = find_chain_head(table, chain_name);
552         if (chain_head == NULL)
553                 return -EINVAL;
554
555         chain_tail = find_chain_tail(table, chain_name);
556         if (chain_tail == NULL)
557                 return -EINVAL;
558
559         new_entry = new_rule(table, ip,
560                                 target_name, xt_t,
561                                 match_name, xt_m);
562         if (new_entry == NULL)
563                 return -EINVAL;
564
565         update_hooks(table, chain_head, new_entry);
566
567         /*
568          * If the chain is builtin, and does not have any rule,
569          * then the one that we're inserting is becoming the head
570          * and thus needs the builtin flag.
571          */
572         head = chain_head->data;
573         if (head->builtin < 0)
574                 builtin = -1;
575         else if (chain_head == chain_tail->prev) {
576                 head->builtin = -1;
577                 builtin = head->builtin;
578         }
579
580         return iptables_add_entry(table, new_entry, chain_tail->prev, builtin);
581 }
582
583 static struct ipt_replace *
584 iptables_blob(struct connman_iptables *table)
585 {
586         struct ipt_replace *r;
587         GList *list;
588         struct connman_iptables_entry *e;
589         unsigned char *entry_index;
590
591         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
592         if (r == NULL)
593                 return NULL;
594
595         memset(r, 0, sizeof(*r) + table->size);
596
597         r->counters = g_try_malloc0(sizeof(struct xt_counters)
598                                 * table->num_entries);
599         if (r->counters == NULL) {
600                 g_free(r);
601                 return NULL;
602         }
603
604         strcpy(r->name, table->info->name);
605         r->num_entries = table->num_entries;
606         r->size = table->size;
607
608         r->num_counters = table->old_entries;
609         r->valid_hooks  = table->info->valid_hooks;
610
611         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
612         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
613
614         entry_index = (unsigned char *)r->entries;
615         for (list = table->entries; list; list = list->next) {
616                 e = list->data;
617
618                 memcpy(entry_index, e->entry, e->entry->next_offset);
619                 entry_index += e->entry->next_offset;
620         }
621
622         return r;
623 }
624
625 static void dump_ip(struct ipt_entry *entry)
626 {
627         struct ipt_ip *ip = &entry->ip;
628         char ip_string[INET6_ADDRSTRLEN];
629         char ip_mask[INET6_ADDRSTRLEN];
630
631         if (strlen(ip->iniface))
632                 connman_info("\tin %s", ip->iniface);
633
634         if (strlen(ip->outiface))
635                 connman_info("\tout %s", ip->outiface);
636
637         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
638                         inet_ntop(AF_INET, &ip->smsk,
639                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
640                 connman_info("\tsrc %s/%s", ip_string, ip_mask);
641
642         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
643                         inet_ntop(AF_INET, &ip->dmsk,
644                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
645                 connman_info("\tdst %s/%s", ip_string, ip_mask);
646 }
647
648 static void dump_target(struct connman_iptables *table,
649                                 struct ipt_entry *entry)
650
651 {
652         struct xtables_target *xt_t;
653         struct xt_entry_target *target;
654
655         target = ipt_get_target(entry);
656
657         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
658                 struct xt_standard_target *t;
659
660                 t = (struct xt_standard_target *)target;
661
662                 switch (t->verdict) {
663                 case XT_RETURN:
664                         connman_info("\ttarget RETURN");
665                         break;
666
667                 case -NF_ACCEPT - 1:
668                         connman_info("\ttarget ACCEPT");
669                         break;
670
671                 case -NF_DROP - 1:
672                         connman_info("\ttarget DROP");
673                         break;
674
675                 case -NF_QUEUE - 1:
676                         connman_info("\ttarget QUEUE");
677                         break;
678
679                 case -NF_STOP - 1:
680                         connman_info("\ttarget STOP");
681                         break;
682
683                 default:
684                         connman_info("\tJUMP @%p (0x%x)",
685                                 (char*)table->blob_entries->entrytable +
686                                 t->verdict, t->verdict);
687                         break;
688                 }
689
690                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
691                                                 XTF_LOAD_MUST_SUCCEED);
692
693                 if(xt_t->print != NULL)
694                         xt_t->print(NULL, target, 1);
695         } else {
696                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
697                 if (xt_t == NULL) {
698                         connman_info("\ttarget %s", target->u.user.name);
699                         return;
700                 }
701
702                 if(xt_t->print != NULL) {
703                         connman_info("\ttarget ");
704                         xt_t->print(NULL, target, 1);
705                 }
706         }
707 }
708
709 static void dump_match(struct connman_iptables *table, struct ipt_entry *entry)
710 {
711         struct xtables_match *xt_m;
712         struct xt_entry_match *match;
713
714         if (entry->elems == (unsigned char *)entry + entry->target_offset)
715                 return;
716
717         match = (struct xt_entry_match *) entry->elems;
718
719         if (!strlen(match->u.user.name))
720                 return;
721
722         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
723         if (xt_m == NULL)
724                 goto out;
725
726         if(xt_m->print != NULL) {
727                 connman_info("\tmatch ");
728                 xt_m->print(NULL, match, 1);
729
730                 return;
731         }
732
733 out:
734         connman_info("\tmatch %s", match->u.user.name);
735
736 }
737
738 static int dump_entry(struct ipt_entry *entry,
739                                 struct connman_iptables *table)
740 {
741         struct xt_entry_target *target;
742         unsigned int offset;
743         int builtin;
744
745         offset = (char *)entry - (char *)table->blob_entries->entrytable;
746         target = ipt_get_target(entry);
747         builtin = is_hook_entry(table, entry);
748
749         if (entry_to_offset(table, entry) + entry->next_offset ==
750                                         table->blob_entries->size) {
751                 connman_info("End of CHAIN 0x%x", offset);
752                 return 0;
753         }
754
755         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
756                 connman_info("USER CHAIN (%s) %p  match %p  target %p  size %d",
757                         target->data, entry, entry->elems,
758                         (char *)entry + entry->target_offset,
759                                 entry->next_offset);
760
761                 return 0;
762         } else if (builtin >= 0) {
763                 connman_info("CHAIN (%s) %p  match %p  target %p  size %d",
764                         hooknames[builtin], entry, entry->elems,
765                         (char *)entry + entry->target_offset,
766                                 entry->next_offset);
767         } else {
768                 connman_info("RULE %p  match %p  target %p  size %d", entry,
769                         entry->elems,
770                         (char *)entry + entry->target_offset,
771                                 entry->next_offset);
772         }
773
774         dump_match(table, entry);
775         dump_target(table, entry);
776         dump_ip(entry);
777
778         return 0;
779 }
780
781 static void iptables_dump(struct connman_iptables *table)
782 {
783         connman_info("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
784                         table->info->name,
785                         table->info->valid_hooks, table->info->num_entries,
786                                 table->info->size);
787
788         ENTRY_ITERATE(table->blob_entries->entrytable,
789                         table->blob_entries->size,
790                         dump_entry, table);
791
792 }
793
794 static int iptables_get_entries(struct connman_iptables *table)
795 {
796         socklen_t entry_size;
797
798         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
799
800         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
801                                 table->blob_entries, &entry_size);
802 }
803
804 static int iptables_replace(struct connman_iptables *table,
805                                         struct ipt_replace *r)
806 {
807         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
808                          sizeof(*r) + r->size);
809 }
810
811 static int add_entry(struct ipt_entry *entry, struct connman_iptables *table)
812 {
813         struct ipt_entry *new_entry;
814         int builtin;
815
816         new_entry = g_try_malloc0(entry->next_offset);
817         if (new_entry == NULL)
818                 return -ENOMEM;
819
820         memcpy(new_entry, entry, entry->next_offset);
821
822         builtin = is_hook_entry(table, entry);
823
824         return iptables_add_entry(table, new_entry, NULL, builtin);
825 }
826
827 static void table_cleanup(struct connman_iptables *table)
828 {
829         GList *list;
830         struct connman_iptables_entry *entry;
831
832         close(table->ipt_sock);
833
834         for (list = table->entries; list; list = list->next) {
835                 entry = list->data;
836
837                 g_free(entry->entry);
838         }
839
840         g_list_free(table->entries);
841         g_free(table->info);
842         g_free(table->blob_entries);
843         g_free(table);
844 }
845
846 static struct connman_iptables *iptables_init(char *table_name)
847 {
848         struct connman_iptables *table;
849         socklen_t s;
850
851         DBG("%s", table_name);
852
853         table = g_hash_table_lookup(table_hash, table_name);
854         if (table != NULL)
855                 return table;
856
857         table = g_try_new0(struct connman_iptables, 1);
858         if (table == NULL)
859                 return NULL;
860
861         table->info = g_try_new0(struct ipt_getinfo, 1);
862         if (table->info == NULL)
863                 goto err;
864
865         table->ipt_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
866         if (table->ipt_sock < 0)
867                 goto err;
868
869         s = sizeof(*table->info);
870         strcpy(table->info->name, table_name);
871         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
872                                                 table->info, &s) < 0)
873                 goto err;
874
875         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
876                                                 table->info->size);
877         if (table->blob_entries == NULL)
878                 goto err;
879
880         strcpy(table->blob_entries->name, table_name);
881         table->blob_entries->size = table->info->size;
882
883         if (iptables_get_entries(table) < 0)
884                 goto err;
885
886         table->num_entries = 0;
887         table->old_entries = table->info->num_entries;
888         table->size = 0;
889
890         memcpy(table->underflow, table->info->underflow,
891                                 sizeof(table->info->underflow));
892         memcpy(table->hook_entry, table->info->hook_entry,
893                                 sizeof(table->info->hook_entry));
894
895         ENTRY_ITERATE(table->blob_entries->entrytable,
896                         table->blob_entries->size,
897                                 add_entry, table);
898
899         g_hash_table_insert(table_hash, g_strdup(table_name), table);
900
901         return table;
902
903 err:
904
905         table_cleanup(table);
906
907         return NULL;
908 }
909
910 static struct option iptables_opts[] = {
911         {.name = "append",        .has_arg = 1, .val = 'A'},
912         {.name = "list",          .has_arg = 2, .val = 'L'},
913         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
914         {.name = "destination",   .has_arg = 1, .val = 'd'},
915         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
916         {.name = "jump",          .has_arg = 1, .val = 'j'},
917         {.name = "match",         .has_arg = 1, .val = 'm'},
918         {.name = "out-interface", .has_arg = 1, .val = 'o'},
919         {.name = "source",        .has_arg = 1, .val = 's'},
920         {.name = "table",         .has_arg = 1, .val = 't'},
921         {NULL},
922 };
923
924 struct xtables_globals iptables_globals = {
925         .option_offset = 0,
926         .opts = iptables_opts,
927         .orig_opts = iptables_opts,
928 };
929
930 static int iptables_command(int argc, char *argv[])
931 {
932         struct connman_iptables *table;
933         struct xtables_match *xt_m;
934         struct xtables_target *xt_t;
935         struct ipt_ip ip;
936         char *table_name, *chain, *new_chain, *match_name, *target_name;
937         int c, ret, in_len, out_len;
938         size_t size;
939         gboolean dump, invert;
940         struct in_addr src, dst;
941
942         if (argc == 0)
943                 return -EINVAL;
944
945         dump = FALSE;
946         invert = FALSE;
947         table_name = chain = new_chain = match_name = target_name = NULL;
948         memset(&ip, 0, sizeof(struct ipt_ip));
949         table = NULL;
950         xt_m = NULL;
951         xt_t = NULL;
952         ret = 0;
953
954         optind = 0;
955
956         while ((c = getopt_long(argc, argv,
957            "-A:L::N:d:j:i:m:o:s:t:", iptables_globals.opts, NULL)) != -1) {
958                 switch (c) {
959                 case 'A':
960                         chain = optarg;
961                         break;
962
963                 case 'L':
964                         dump = TRUE;
965                         break;
966
967                 case 'N':
968                         new_chain = optarg;
969                         break;
970
971                 case 'd':
972                         if (!inet_pton(AF_INET, optarg, &dst))
973                                 break;
974
975                         ip.dst = dst;
976                         inet_pton(AF_INET, "255.255.255.255", &ip.dmsk);
977
978                         if (invert)
979                                 ip.invflags |= IPT_INV_DSTIP;
980
981                         break;
982
983                 case 'i':
984                         in_len = strlen(optarg);
985
986                         if (in_len + 1 > IFNAMSIZ)
987                                 break;
988
989                         strcpy(ip.iniface, optarg);
990                         memset(ip.iniface_mask, 0xff, in_len + 1);
991
992                         if (invert)
993                                 ip.invflags |= IPT_INV_VIA_IN;
994
995                         break;
996
997                 case 'j':
998                         target_name = optarg;
999                         xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1000
1001                         if (xt_t == NULL)
1002                                 break;
1003
1004                         size = ALIGN(sizeof(struct ipt_entry_target)) +
1005                                                                 xt_t->size;
1006
1007                         xt_t->t = g_try_malloc0(size);
1008                         if (xt_t->t == NULL)
1009                                 goto out;
1010                         xt_t->t->u.target_size = size;
1011                         strcpy(xt_t->t->u.user.name, target_name);
1012                         xt_t->t->u.user.revision = xt_t->revision;
1013                         if (xt_t->init != NULL)
1014                                 xt_t->init(xt_t->t);
1015                         iptables_globals.opts =
1016                                 xtables_merge_options(iptables_globals.opts,
1017                                                      xt_t->extra_opts,
1018                                                      &xt_t->option_offset);
1019                         if (iptables_globals.opts == NULL)
1020                                 goto out;
1021
1022                         break;
1023
1024                 case 'm':
1025                         match_name = optarg;
1026
1027                         xt_m = xtables_find_match(optarg, XTF_LOAD_MUST_SUCCEED, NULL);
1028                         size = ALIGN(sizeof(struct ipt_entry_match)) +
1029                                                                 xt_m->size;
1030                         xt_m->m = g_try_malloc0(size);
1031                         if (xt_m == NULL)
1032                                 goto out;
1033                         xt_m->m->u.match_size = size;
1034                         strcpy(xt_m->m->u.user.name, xt_m->name);
1035                         xt_m->m->u.user.revision = xt_m->revision;
1036                         if (xt_m->init != NULL)
1037                                 xt_m->init(xt_m->m);
1038                         if (xt_m != xt_m->next) {
1039                                 iptables_globals.opts =
1040                                 xtables_merge_options(iptables_globals.opts,
1041                                                 xt_m->extra_opts,
1042                                                 &xt_m->option_offset);
1043                                 if (iptables_globals.opts == NULL)
1044                                         goto out;
1045                         }
1046
1047                         break;
1048
1049                 case 'o':
1050                         out_len = strlen(optarg);
1051
1052                         if (out_len + 1 > IFNAMSIZ)
1053                                 break;
1054
1055                         strcpy(ip.outiface, optarg);
1056                         memset(ip.outiface_mask, 0xff, out_len + 1);
1057
1058                         if (invert)
1059                                 ip.invflags |= IPT_INV_VIA_OUT;
1060
1061                         break;
1062
1063                 case 's':
1064                         if (!inet_pton(AF_INET, optarg, &src))
1065                                 break;
1066
1067                         ip.src = src;
1068                         inet_pton(AF_INET, "255.255.255.255", &ip.smsk);
1069
1070                         if (invert)
1071                                 ip.invflags |= IPT_INV_SRCIP;
1072
1073                         break;
1074
1075                 case 't':
1076                         table_name = optarg;
1077                         break;
1078
1079                 case 1:
1080                         if (optarg[0] == '!' && optarg[1] == '\0') {
1081                                 invert = TRUE;
1082                                 optarg[0] = '\0';
1083                                 continue;
1084                         }
1085
1086                         connman_error("Invalid option");
1087
1088                         ret = -EINVAL;
1089                         goto out;
1090
1091                 default:
1092                         if (xt_t == NULL || xt_t->parse == NULL ||
1093                             !xt_t->parse(c - xt_t->option_offset, argv, invert,
1094                                         &xt_t->tflags, NULL, &xt_t->t)) {
1095                                 if (xt_m == NULL || xt_m->parse == NULL)
1096                                         break;
1097
1098                                 xt_m->parse(c - xt_m->option_offset, argv,
1099                                         invert, &xt_m->mflags, NULL, &xt_m->m);
1100                         }
1101
1102                         break;
1103                 }
1104
1105                 invert = FALSE;
1106         }
1107
1108         if (table_name == NULL)
1109                 table_name = "filter";
1110
1111         table = iptables_init(table_name);
1112         if (table == NULL) {
1113                 ret = -EINVAL;
1114                 goto out;
1115         }
1116
1117         if (dump) {
1118                 iptables_dump(table);
1119
1120                 ret = 0;
1121                 goto out;
1122         }
1123
1124         if (chain && new_chain) {
1125                 ret = -EINVAL;
1126                 goto out;
1127         }
1128
1129         if (new_chain) {
1130                 DBG("New chain %s", new_chain);
1131
1132                 ret = iptables_add_chain(table, new_chain);
1133                 goto out;
1134         }
1135
1136         if (chain) {
1137                 if (target_name == NULL)
1138                         return -1;
1139
1140                 DBG("Adding %s to %s (match %s)",
1141                                 target_name, chain, match_name);
1142
1143                 ret = iptables_add_rule(table, &ip, chain, target_name, xt_t,
1144                                         match_name, xt_m);
1145
1146                 goto out;
1147         }
1148
1149 out:
1150         if (xt_t)
1151                 g_free(xt_t->t);
1152
1153         if (xt_m)
1154                 g_free(xt_m->m);
1155
1156         return ret;
1157 }
1158
1159 int __connman_iptables_command(const char *format, ...)
1160 {
1161         char **argv, **arguments, *command;
1162         int argc, i, ret;
1163         va_list args;
1164
1165         if (format == NULL)
1166                 return -EINVAL;
1167
1168         va_start(args, format);
1169
1170         command = g_strdup_vprintf(format, args);
1171
1172         va_end(args);
1173
1174         if (command == NULL)
1175                 return -ENOMEM;
1176
1177         arguments = g_strsplit_set(command, " ", -1);
1178
1179         for (argc = 0; arguments[argc]; argc++);
1180
1181         DBG("command %s argc %d", command, ++argc);
1182
1183         argv = g_try_malloc0(argc * sizeof(char *));
1184         if (argv == NULL) {
1185                 g_free(command);
1186                 g_strfreev(arguments);
1187                 return -ENOMEM;
1188         }
1189
1190         argv[0] = "iptables";
1191         for (i = 1; i < argc; i++)
1192                 argv[i] = arguments[i - 1];
1193
1194         ret = iptables_command(argc, argv);
1195
1196         g_free(command);
1197         g_strfreev(arguments);
1198         g_free(argv);
1199
1200         return ret;
1201 }
1202
1203
1204 int __connman_iptables_commit(const char *table_name)
1205 {
1206         struct connman_iptables *table;
1207         struct ipt_replace *repl;
1208
1209         DBG("%s", table_name);
1210
1211         table = g_hash_table_lookup(table_hash, table_name);
1212         if (table == NULL)
1213                 return -EINVAL;
1214
1215         repl = iptables_blob(table);
1216
1217         return iptables_replace(table, repl);
1218 }
1219
1220 static void remove_table(gpointer user_data)
1221 {
1222         struct connman_iptables *table = user_data;
1223
1224         table_cleanup(table);
1225 }
1226
1227 int __connman_iptables_init(void)
1228 {
1229         DBG("");
1230
1231         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
1232                                                 g_free, remove_table);
1233
1234         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
1235
1236         return 0;
1237
1238 }
1239
1240 void __connman_iptables_cleanup(void)
1241 {
1242         g_hash_table_destroy(table_hash);
1243
1244         xtables_free_opts(1);
1245 }