iptables: Fixing target reference update
[platform/upstream/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 appended/insterted a new entry. All references
319          * should be bumped accordingly.
320          */
321         for (list = table->entries; list; 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 int iptables_delete_chain(struct connman_iptables *table, char *name)
487 {
488         struct connman_iptables_entry *entry;
489         GList *chain_head, *chain_tail;
490
491         chain_head = find_chain_head(table, name);
492         if (chain_head == NULL)
493                 return -EINVAL;
494
495         entry = chain_head->data;
496
497         /* We cannot remove builtin chain */
498         if (entry->builtin >= 0)
499                 return -EINVAL;
500
501         chain_tail = find_chain_tail(table, name);
502         if (chain_tail == NULL)
503                 return -EINVAL;
504
505         /* Chain must be flushed */
506         if (chain_head->next != chain_tail->prev)
507                 return -EINVAL;
508
509         remove_table_entry(table, entry);
510
511         entry = chain_tail->prev->data;
512         remove_table_entry(table, entry);
513
514         update_offsets(table);
515
516         return 0;
517 }
518
519 static struct ipt_entry *
520 new_rule(struct connman_iptables *table, struct ipt_ip *ip,
521                 char *target_name, struct xtables_target *xt_t,
522                 char *match_name, struct xtables_match *xt_m)
523 {
524         struct ipt_entry *new_entry;
525         size_t match_size, target_size;
526         int is_builtin = is_builtin_target(target_name);
527
528         if (xt_m)
529                 match_size = xt_m->m->u.match_size;
530         else
531                 match_size = 0;
532
533         if (xt_t)
534                 target_size = ALIGN(xt_t->t->u.target_size);
535         else
536                 target_size = ALIGN(sizeof(struct xt_standard_target));
537
538         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
539                                                                 match_size);
540         if (new_entry == NULL)
541                 return NULL;
542
543         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
544
545         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
546         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
547                                                                 match_size;
548         if (xt_m) {
549                 struct xt_entry_match *entry_match;
550
551                 entry_match = (struct xt_entry_match *)new_entry->elems;
552                 memcpy(entry_match, xt_m->m, match_size);
553         }
554
555         if (xt_t) {
556                 struct xt_entry_target *entry_target;
557
558                 if (is_builtin) {
559                         struct xt_standard_target *target;
560
561                         target = (struct xt_standard_target *)(xt_t->t);
562                         strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
563                         target->verdict = target_to_verdict(target_name);
564                 }
565
566                 entry_target = ipt_get_target(new_entry);
567                 memcpy(entry_target, xt_t->t, target_size);
568         } else {
569                 struct connman_iptables_entry *target_rule;
570                 struct xt_standard_target *target;
571                 GList *chain_head;
572
573                 /*
574                  * This is a user defined target, i.e. a chain jump.
575                  * We search for the chain head, and the target verdict
576                  * is the first rule's offset on this chain.
577                  * The offset is from the beginning of the table.
578                  */
579
580                 chain_head = find_chain_head(table, target_name);
581                 if (chain_head == NULL || chain_head->next == NULL) {
582                         g_free(new_entry);
583                         return NULL;
584                 }
585
586                 target_rule = chain_head->next->data;
587
588                 target = (struct xt_standard_target *)ipt_get_target(new_entry);
589                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
590                 target->target.u.user.target_size = target_size;
591                 target->verdict = target_rule->offset;
592         }
593
594         return new_entry;
595 }
596
597 static void update_hooks(struct connman_iptables *table, GList *chain_head,
598                                 struct ipt_entry *entry)
599 {
600         GList *list;
601         struct connman_iptables_entry *head, *e;
602         int builtin;
603
604         if (chain_head == NULL)
605                 return;
606
607         head = chain_head->data;
608
609         builtin = head->builtin;
610         if (builtin < 0)
611                 return;
612
613         table->underflow[builtin] += entry->next_offset;
614
615         for (list = chain_head->next; list; list = list->next) {
616                 e = list->data;
617
618                 builtin = e->builtin;
619                 if (builtin < 0)
620                         continue;
621
622                 table->hook_entry[builtin] += entry->next_offset;
623                 table->underflow[builtin] += entry->next_offset;
624         }
625 }
626
627 static struct ipt_entry *prepare_rule_inclusion(struct connman_iptables *table,
628                                 struct ipt_ip *ip, char *chain_name,
629                                 char *target_name, struct xtables_target *xt_t,
630                                 char *match_name, struct xtables_match *xt_m,
631                                 int *builtin)
632 {
633         GList *chain_tail, *chain_head;
634         struct ipt_entry *new_entry;
635         struct connman_iptables_entry *head;
636
637         chain_head = find_chain_head(table, chain_name);
638         if (chain_head == NULL)
639                 return NULL;
640
641         chain_tail = find_chain_tail(table, chain_name);
642         if (chain_tail == NULL)
643                 return NULL;
644
645         new_entry = new_rule(table, ip, target_name, xt_t, match_name, xt_m);
646         if (new_entry == NULL)
647                 return NULL;
648
649         update_hooks(table, chain_head, new_entry);
650
651         /*
652          * If the chain is builtin, and does not have any rule,
653          * then the one that we're inserting is becoming the head
654          * and thus needs the builtin flag.
655          */
656         head = chain_head->data;
657         if (head->builtin < 0)
658                 *builtin = -1;
659         else if (chain_head == chain_tail->prev) {
660                 *builtin = head->builtin;
661                 head->builtin = -1;
662         }
663
664         return new_entry;
665 }
666
667 static int iptables_append_rule(struct connman_iptables *table,
668                                 struct ipt_ip *ip, char *chain_name,
669                                 char *target_name, struct xtables_target *xt_t,
670                                 char *match_name, struct xtables_match *xt_m)
671 {
672         GList *chain_tail;
673         struct ipt_entry *new_entry;
674         int builtin = -1, ret;
675
676         DBG("");
677
678         chain_tail = find_chain_tail(table, chain_name);
679         if (chain_tail == NULL)
680                 return -EINVAL;
681
682         new_entry = prepare_rule_inclusion(table, ip, chain_name,
683                         target_name, xt_t, match_name, xt_m, &builtin);
684         if (new_entry == NULL)
685                 return -EINVAL;
686
687         ret = iptables_add_entry(table, new_entry, chain_tail->prev, builtin);
688         if (ret < 0)
689                 g_free(new_entry);
690
691         return ret;
692 }
693
694 static int iptables_insert_rule(struct connman_iptables *table,
695                                 struct ipt_ip *ip, char *chain_name,
696                                 char *target_name, struct xtables_target *xt_t,
697                                 char *match_name, struct xtables_match *xt_m)
698 {
699         struct ipt_entry *new_entry;
700         int builtin = -1, ret;
701         GList *chain_head;
702
703         chain_head = find_chain_head(table, chain_name);
704         if (chain_head == NULL)
705                 return -EINVAL;
706
707         new_entry = prepare_rule_inclusion(table, ip, chain_name,
708                         target_name, xt_t, match_name, xt_m, &builtin);
709         if (new_entry == NULL)
710                 return -EINVAL;
711
712         ret = iptables_add_entry(table, new_entry, chain_head->next, builtin);
713         if (ret < 0)
714                 g_free(new_entry);
715
716         return ret;
717 }
718
719 static struct ipt_replace *
720 iptables_blob(struct connman_iptables *table)
721 {
722         struct ipt_replace *r;
723         GList *list;
724         struct connman_iptables_entry *e;
725         unsigned char *entry_index;
726
727         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
728         if (r == NULL)
729                 return NULL;
730
731         memset(r, 0, sizeof(*r) + table->size);
732
733         r->counters = g_try_malloc0(sizeof(struct xt_counters)
734                                 * table->old_entries);
735         if (r->counters == NULL) {
736                 g_free(r);
737                 return NULL;
738         }
739
740         strcpy(r->name, table->info->name);
741         r->num_entries = table->num_entries;
742         r->size = table->size;
743
744         r->num_counters = table->old_entries;
745         r->valid_hooks  = table->info->valid_hooks;
746
747         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
748         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
749
750         entry_index = (unsigned char *)r->entries;
751         for (list = table->entries; list; list = list->next) {
752                 e = list->data;
753
754                 memcpy(entry_index, e->entry, e->entry->next_offset);
755                 entry_index += e->entry->next_offset;
756         }
757
758         return r;
759 }
760
761 static void dump_ip(struct ipt_entry *entry)
762 {
763         struct ipt_ip *ip = &entry->ip;
764         char ip_string[INET6_ADDRSTRLEN];
765         char ip_mask[INET6_ADDRSTRLEN];
766
767         if (strlen(ip->iniface))
768                 connman_info("\tin %s", ip->iniface);
769
770         if (strlen(ip->outiface))
771                 connman_info("\tout %s", ip->outiface);
772
773         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
774                         inet_ntop(AF_INET, &ip->smsk,
775                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
776                 connman_info("\tsrc %s/%s", ip_string, ip_mask);
777
778         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
779                         inet_ntop(AF_INET, &ip->dmsk,
780                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
781                 connman_info("\tdst %s/%s", ip_string, ip_mask);
782 }
783
784 static void dump_target(struct connman_iptables *table,
785                                 struct ipt_entry *entry)
786
787 {
788         struct xtables_target *xt_t;
789         struct xt_entry_target *target;
790
791         target = ipt_get_target(entry);
792
793         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
794                 struct xt_standard_target *t;
795
796                 t = (struct xt_standard_target *)target;
797
798                 switch (t->verdict) {
799                 case XT_RETURN:
800                         connman_info("\ttarget RETURN");
801                         break;
802
803                 case -NF_ACCEPT - 1:
804                         connman_info("\ttarget ACCEPT");
805                         break;
806
807                 case -NF_DROP - 1:
808                         connman_info("\ttarget DROP");
809                         break;
810
811                 case -NF_QUEUE - 1:
812                         connman_info("\ttarget QUEUE");
813                         break;
814
815                 case -NF_STOP - 1:
816                         connman_info("\ttarget STOP");
817                         break;
818
819                 default:
820                         connman_info("\tJUMP @%p (0x%x)",
821                                 (char*)table->blob_entries->entrytable +
822                                 t->verdict, t->verdict);
823                         break;
824                 }
825
826                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
827                                                 XTF_LOAD_MUST_SUCCEED);
828
829                 if(xt_t->print != NULL)
830                         xt_t->print(NULL, target, 1);
831         } else {
832                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
833                 if (xt_t == NULL) {
834                         connman_info("\ttarget %s", target->u.user.name);
835                         return;
836                 }
837
838                 if(xt_t->print != NULL) {
839                         connman_info("\ttarget ");
840                         xt_t->print(NULL, target, 1);
841                 }
842         }
843 }
844
845 static void dump_match(struct connman_iptables *table, struct ipt_entry *entry)
846 {
847         struct xtables_match *xt_m;
848         struct xt_entry_match *match;
849
850         if (entry->elems == (unsigned char *)entry + entry->target_offset)
851                 return;
852
853         match = (struct xt_entry_match *) entry->elems;
854
855         if (!strlen(match->u.user.name))
856                 return;
857
858         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
859         if (xt_m == NULL)
860                 goto out;
861
862         if(xt_m->print != NULL) {
863                 connman_info("\tmatch ");
864                 xt_m->print(NULL, match, 1);
865
866                 return;
867         }
868
869 out:
870         connman_info("\tmatch %s", match->u.user.name);
871
872 }
873
874 static int dump_entry(struct ipt_entry *entry,
875                                 struct connman_iptables *table)
876 {
877         struct xt_entry_target *target;
878         unsigned int offset;
879         int builtin;
880
881         offset = (char *)entry - (char *)table->blob_entries->entrytable;
882         target = ipt_get_target(entry);
883         builtin = is_hook_entry(table, entry);
884
885         if (entry_to_offset(table, entry) + entry->next_offset ==
886                                         table->blob_entries->size) {
887                 connman_info("End of CHAIN 0x%x", offset);
888                 return 0;
889         }
890
891         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
892                 connman_info("USER CHAIN (%s) %p  match %p  target %p  size %d",
893                         target->data, entry, entry->elems,
894                         (char *)entry + entry->target_offset,
895                                 entry->next_offset);
896
897                 return 0;
898         } else if (builtin >= 0) {
899                 connman_info("CHAIN (%s) %p  match %p  target %p  size %d",
900                         hooknames[builtin], entry, entry->elems,
901                         (char *)entry + entry->target_offset,
902                                 entry->next_offset);
903         } else {
904                 connman_info("RULE %p  match %p  target %p  size %d", entry,
905                         entry->elems,
906                         (char *)entry + entry->target_offset,
907                                 entry->next_offset);
908         }
909
910         dump_match(table, entry);
911         dump_target(table, entry);
912         dump_ip(entry);
913
914         return 0;
915 }
916
917 static void iptables_dump(struct connman_iptables *table)
918 {
919         connman_info("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
920                         table->info->name,
921                         table->info->valid_hooks, table->info->num_entries,
922                                 table->info->size);
923
924         ENTRY_ITERATE(table->blob_entries->entrytable,
925                         table->blob_entries->size,
926                         dump_entry, table);
927
928 }
929
930 static int iptables_get_entries(struct connman_iptables *table)
931 {
932         socklen_t entry_size;
933
934         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
935
936         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
937                                 table->blob_entries, &entry_size);
938 }
939
940 static int iptables_replace(struct connman_iptables *table,
941                                         struct ipt_replace *r)
942 {
943         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
944                          sizeof(*r) + r->size);
945 }
946
947 static int add_entry(struct ipt_entry *entry, struct connman_iptables *table)
948 {
949         struct ipt_entry *new_entry;
950         int builtin;
951
952         new_entry = g_try_malloc0(entry->next_offset);
953         if (new_entry == NULL)
954                 return -ENOMEM;
955
956         memcpy(new_entry, entry, entry->next_offset);
957
958         builtin = is_hook_entry(table, entry);
959
960         return iptables_add_entry(table, new_entry, NULL, builtin);
961 }
962
963 static void table_cleanup(struct connman_iptables *table)
964 {
965         GList *list;
966         struct connman_iptables_entry *entry;
967
968         close(table->ipt_sock);
969
970         for (list = table->entries; list; list = list->next) {
971                 entry = list->data;
972
973                 g_free(entry->entry);
974                 g_free(entry);
975         }
976
977         g_list_free(table->entries);
978         g_free(table->info);
979         g_free(table->blob_entries);
980         g_free(table);
981 }
982
983 static struct connman_iptables *iptables_init(char *table_name)
984 {
985         struct connman_iptables *table;
986         socklen_t s;
987
988         DBG("%s", table_name);
989
990         table = g_hash_table_lookup(table_hash, table_name);
991         if (table != NULL)
992                 return table;
993
994         table = g_try_new0(struct connman_iptables, 1);
995         if (table == NULL)
996                 return NULL;
997
998         table->info = g_try_new0(struct ipt_getinfo, 1);
999         if (table->info == NULL)
1000                 goto err;
1001
1002         table->ipt_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
1003         if (table->ipt_sock < 0)
1004                 goto err;
1005
1006         s = sizeof(*table->info);
1007         strcpy(table->info->name, table_name);
1008         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
1009                                                 table->info, &s) < 0)
1010                 goto err;
1011
1012         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
1013                                                 table->info->size);
1014         if (table->blob_entries == NULL)
1015                 goto err;
1016
1017         strcpy(table->blob_entries->name, table_name);
1018         table->blob_entries->size = table->info->size;
1019
1020         if (iptables_get_entries(table) < 0)
1021                 goto err;
1022
1023         table->num_entries = 0;
1024         table->old_entries = table->info->num_entries;
1025         table->size = 0;
1026
1027         memcpy(table->underflow, table->info->underflow,
1028                                 sizeof(table->info->underflow));
1029         memcpy(table->hook_entry, table->info->hook_entry,
1030                                 sizeof(table->info->hook_entry));
1031
1032         ENTRY_ITERATE(table->blob_entries->entrytable,
1033                         table->blob_entries->size,
1034                                 add_entry, table);
1035
1036         g_hash_table_insert(table_hash, g_strdup(table_name), table);
1037
1038         return table;
1039
1040 err:
1041
1042         table_cleanup(table);
1043
1044         return NULL;
1045 }
1046
1047 static struct option iptables_opts[] = {
1048         {.name = "append",        .has_arg = 1, .val = 'A'},
1049         {.name = "flush-chain",   .has_arg = 1, .val = 'F'},
1050         {.name = "insert",        .has_arg = 1, .val = 'I'},
1051         {.name = "list",          .has_arg = 2, .val = 'L'},
1052         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
1053         {.name = "delete-chain",  .has_arg = 1, .val = 'X'},
1054         {.name = "destination",   .has_arg = 1, .val = 'd'},
1055         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
1056         {.name = "jump",          .has_arg = 1, .val = 'j'},
1057         {.name = "match",         .has_arg = 1, .val = 'm'},
1058         {.name = "out-interface", .has_arg = 1, .val = 'o'},
1059         {.name = "source",        .has_arg = 1, .val = 's'},
1060         {.name = "table",         .has_arg = 1, .val = 't'},
1061         {NULL},
1062 };
1063
1064 struct xtables_globals iptables_globals = {
1065         .option_offset = 0,
1066         .opts = iptables_opts,
1067         .orig_opts = iptables_opts,
1068 };
1069
1070 static int iptables_command(int argc, char *argv[])
1071 {
1072         struct connman_iptables *table;
1073         struct xtables_match *xt_m;
1074         struct xtables_target *xt_t;
1075         struct ipt_ip ip;
1076         char *table_name, *chain, *new_chain, *match_name, *target_name;
1077         char *flush_chain, *delete_chain;
1078         int c, ret, in_len, out_len;
1079         size_t size;
1080         gboolean dump, invert, insert;
1081         struct in_addr src, dst;
1082
1083         if (argc == 0)
1084                 return -EINVAL;
1085
1086         dump = FALSE;
1087         invert = FALSE;
1088         insert = FALSE;
1089         table_name = chain = new_chain = match_name = target_name = NULL;
1090         flush_chain = delete_chain = NULL;
1091         memset(&ip, 0, sizeof(struct ipt_ip));
1092         table = NULL;
1093         xt_m = NULL;
1094         xt_t = NULL;
1095         ret = 0;
1096
1097         optind = 0;
1098
1099         while ((c = getopt_long(argc, argv, "-A:F:I:L::N:X:d:j:i:m:o:s:t:",
1100                                         iptables_globals.opts, NULL)) != -1) {
1101                 switch (c) {
1102                 case 'A':
1103                         /* It is either -A, -D or -I at once */
1104                         if (chain)
1105                                 goto out;
1106
1107                         chain = optarg;
1108                         break;
1109
1110                 case 'F':
1111                         flush_chain = optarg;
1112                         break;
1113
1114                 case 'I':
1115                         /* It is either -A, -D or -I at once */
1116                         if (chain)
1117                                 goto out;
1118
1119                         chain = optarg;
1120                         insert = TRUE;
1121                         break;
1122
1123                 case 'L':
1124                         dump = TRUE;
1125                         break;
1126
1127                 case 'N':
1128                         new_chain = optarg;
1129                         break;
1130
1131                 case 'X':
1132                         delete_chain = optarg;
1133                         break;
1134
1135                 case 'd':
1136                         if (!inet_pton(AF_INET, optarg, &dst))
1137                                 break;
1138
1139                         ip.dst = dst;
1140                         inet_pton(AF_INET, "255.255.255.255", &ip.dmsk);
1141
1142                         if (invert)
1143                                 ip.invflags |= IPT_INV_DSTIP;
1144
1145                         break;
1146
1147                 case 'i':
1148                         in_len = strlen(optarg);
1149
1150                         if (in_len + 1 > IFNAMSIZ)
1151                                 break;
1152
1153                         strcpy(ip.iniface, optarg);
1154                         memset(ip.iniface_mask, 0xff, in_len + 1);
1155
1156                         if (invert)
1157                                 ip.invflags |= IPT_INV_VIA_IN;
1158
1159                         break;
1160
1161                 case 'j':
1162                         target_name = optarg;
1163                         xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1164
1165                         if (xt_t == NULL)
1166                                 break;
1167
1168                         size = ALIGN(sizeof(struct ipt_entry_target)) +
1169                                                                 xt_t->size;
1170
1171                         xt_t->t = g_try_malloc0(size);
1172                         if (xt_t->t == NULL)
1173                                 goto out;
1174                         xt_t->t->u.target_size = size;
1175                         strcpy(xt_t->t->u.user.name, target_name);
1176                         xt_t->t->u.user.revision = xt_t->revision;
1177                         if (xt_t->init != NULL)
1178                                 xt_t->init(xt_t->t);
1179                         iptables_globals.opts =
1180                                 xtables_merge_options(
1181 #if XTABLES_VERSION_CODE > 5
1182                                                      iptables_globals.orig_opts,
1183 #endif
1184                                                      iptables_globals.opts,
1185                                                      xt_t->extra_opts,
1186                                                      &xt_t->option_offset);
1187                         if (iptables_globals.opts == NULL)
1188                                 goto out;
1189
1190                         break;
1191
1192                 case 'm':
1193                         match_name = optarg;
1194
1195                         xt_m = xtables_find_match(optarg, XTF_LOAD_MUST_SUCCEED, NULL);
1196                         size = ALIGN(sizeof(struct ipt_entry_match)) +
1197                                                                 xt_m->size;
1198                         xt_m->m = g_try_malloc0(size);
1199                         if (xt_m == NULL)
1200                                 goto out;
1201                         xt_m->m->u.match_size = size;
1202                         strcpy(xt_m->m->u.user.name, xt_m->name);
1203                         xt_m->m->u.user.revision = xt_m->revision;
1204                         if (xt_m->init != NULL)
1205                                 xt_m->init(xt_m->m);
1206                         if (xt_m != xt_m->next) {
1207                                 iptables_globals.opts =
1208                                 xtables_merge_options(
1209 #if XTABLES_VERSION_CODE > 5
1210                                                 iptables_globals.orig_opts,
1211 #endif
1212                                                 iptables_globals.opts,
1213                                                 xt_m->extra_opts,
1214                                                 &xt_m->option_offset);
1215                                 if (iptables_globals.opts == NULL)
1216                                         goto out;
1217                         }
1218
1219                         break;
1220
1221                 case 'o':
1222                         out_len = strlen(optarg);
1223
1224                         if (out_len + 1 > IFNAMSIZ)
1225                                 break;
1226
1227                         strcpy(ip.outiface, optarg);
1228                         memset(ip.outiface_mask, 0xff, out_len + 1);
1229
1230                         if (invert)
1231                                 ip.invflags |= IPT_INV_VIA_OUT;
1232
1233                         break;
1234
1235                 case 's':
1236                         if (!inet_pton(AF_INET, optarg, &src))
1237                                 break;
1238
1239                         ip.src = src;
1240                         inet_pton(AF_INET, "255.255.255.255", &ip.smsk);
1241
1242                         if (invert)
1243                                 ip.invflags |= IPT_INV_SRCIP;
1244
1245                         break;
1246
1247                 case 't':
1248                         table_name = optarg;
1249                         break;
1250
1251                 case 1:
1252                         if (optarg[0] == '!' && optarg[1] == '\0') {
1253                                 invert = TRUE;
1254                                 optarg[0] = '\0';
1255                                 continue;
1256                         }
1257
1258                         connman_error("Invalid option");
1259
1260                         ret = -EINVAL;
1261                         goto out;
1262
1263                 default:
1264                         if (xt_t == NULL || xt_t->parse == NULL ||
1265                             !xt_t->parse(c - xt_t->option_offset, argv, invert,
1266                                         &xt_t->tflags, NULL, &xt_t->t)) {
1267                                 if (xt_m == NULL || xt_m->parse == NULL)
1268                                         break;
1269
1270                                 xt_m->parse(c - xt_m->option_offset, argv,
1271                                         invert, &xt_m->mflags, NULL, &xt_m->m);
1272                         }
1273
1274                         break;
1275                 }
1276
1277                 invert = FALSE;
1278         }
1279
1280         if (table_name == NULL)
1281                 table_name = "filter";
1282
1283         table = iptables_init(table_name);
1284         if (table == NULL) {
1285                 ret = -EINVAL;
1286                 goto out;
1287         }
1288
1289         if (delete_chain != NULL) {
1290                 printf("Delete chain %s\n", delete_chain);
1291
1292                 iptables_delete_chain(table, delete_chain);
1293
1294                 goto out;
1295         }
1296
1297         if (dump) {
1298                 iptables_dump(table);
1299
1300                 ret = 0;
1301                 goto out;
1302         }
1303
1304         if (flush_chain) {
1305                 DBG("Flush chain %s", flush_chain);
1306
1307                 iptables_flush_chain(table, flush_chain);
1308
1309                 goto out;
1310         }
1311
1312         if (chain && new_chain) {
1313                 ret = -EINVAL;
1314                 goto out;
1315         }
1316
1317         if (new_chain) {
1318                 DBG("New chain %s", new_chain);
1319
1320                 ret = iptables_add_chain(table, new_chain);
1321                 goto out;
1322         }
1323
1324         if (chain) {
1325                 if (target_name == NULL)
1326                         return -1;
1327
1328                 if (insert == TRUE) {
1329                         DBG("Inserting %s to %s (match %s)",
1330                                         target_name, chain, match_name);
1331
1332                         ret = iptables_insert_rule(table, &ip, chain,
1333                                         target_name, xt_t, match_name, xt_m);
1334
1335                         goto out;
1336                 } else {
1337                         DBG("Adding %s to %s (match %s)",
1338                                         target_name, chain, match_name);
1339
1340                         ret = iptables_append_rule(table, &ip, chain,
1341                                         target_name, xt_t, match_name, xt_m);
1342
1343                         goto out;
1344                 }
1345         }
1346
1347 out:
1348         if (xt_t)
1349                 g_free(xt_t->t);
1350
1351         if (xt_m)
1352                 g_free(xt_m->m);
1353
1354         return ret;
1355 }
1356
1357 int __connman_iptables_command(const char *format, ...)
1358 {
1359         char **argv, **arguments, *command;
1360         int argc, i, ret;
1361         va_list args;
1362
1363         if (format == NULL)
1364                 return -EINVAL;
1365
1366         va_start(args, format);
1367
1368         command = g_strdup_vprintf(format, args);
1369
1370         va_end(args);
1371
1372         if (command == NULL)
1373                 return -ENOMEM;
1374
1375         arguments = g_strsplit_set(command, " ", -1);
1376
1377         for (argc = 0; arguments[argc]; argc++);
1378         ++argc;
1379
1380         DBG("command %s argc %d", command, argc);
1381
1382         argv = g_try_malloc0(argc * sizeof(char *));
1383         if (argv == NULL) {
1384                 g_free(command);
1385                 g_strfreev(arguments);
1386                 return -ENOMEM;
1387         }
1388
1389         argv[0] = "iptables";
1390         for (i = 1; i < argc; i++)
1391                 argv[i] = arguments[i - 1];
1392
1393         ret = iptables_command(argc, argv);
1394
1395         g_free(command);
1396         g_strfreev(arguments);
1397         g_free(argv);
1398
1399         return ret;
1400 }
1401
1402
1403 int __connman_iptables_commit(const char *table_name)
1404 {
1405         struct connman_iptables *table;
1406         struct ipt_replace *repl;
1407         int err;
1408
1409         DBG("%s", table_name);
1410
1411         table = g_hash_table_lookup(table_hash, table_name);
1412         if (table == NULL)
1413                 return -EINVAL;
1414
1415         repl = iptables_blob(table);
1416
1417         err = iptables_replace(table, repl);
1418
1419         g_free(repl->counters);
1420         g_free(repl);
1421
1422         if (err < 0)
1423             return err;
1424
1425         g_hash_table_remove(table_hash, table_name);
1426
1427         return 0;
1428 }
1429
1430 static void remove_table(gpointer user_data)
1431 {
1432         struct connman_iptables *table = user_data;
1433
1434         table_cleanup(table);
1435 }
1436
1437 int __connman_iptables_init(void)
1438 {
1439         DBG("");
1440
1441         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
1442                                                 g_free, remove_table);
1443
1444         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
1445
1446         return 0;
1447
1448 }
1449
1450 void __connman_iptables_cleanup(void)
1451 {
1452         DBG("");
1453
1454         g_hash_table_destroy(table_hash);
1455
1456         xtables_free_opts(1);
1457 }