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