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