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