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