iptables: Add support for interface and IP option inversion
[framework/connectivity/connman.git] / src / iptables.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <getopt.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/errno.h>
32 #include <sys/socket.h>
33 #include <xtables.h>
34
35 #include <linux/netfilter_ipv4/ip_tables.h>
36
37 #include "connman.h"
38
39
40 static const char *hooknames[] = {
41         [NF_IP_PRE_ROUTING]     = "PREROUTING",
42         [NF_IP_LOCAL_IN]        = "INPUT",
43         [NF_IP_FORWARD]         = "FORWARD",
44         [NF_IP_LOCAL_OUT]       = "OUTPUT",
45         [NF_IP_POST_ROUTING]    = "POSTROUTING",
46 };
47
48 #define LABEL_ACCEPT  "ACCEPT"
49 #define LABEL_DROP    "DROP"
50 #define LABEL_QUEUE   "QUEUE"
51 #define LABEL_RETURN  "RETURN"
52
53 /* fn returns 0 to continue iteration */
54 #define _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, n, fn, args...) \
55 ({                                                              \
56         unsigned int __i;                                       \
57         int __n;                                                \
58         int __ret = 0;                                          \
59         type *__entry;                                          \
60                                                                 \
61         for (__i = 0, __n = 0; __i < (size);                    \
62              __i += __entry->next_offset, __n++) {              \
63                 __entry = (void *)(entries) + __i;              \
64                 if (__n < n)                                    \
65                         continue;                               \
66                                                                 \
67                 __ret = fn(__entry,  ## args);                  \
68                 if (__ret != 0)                                 \
69                         break;                                  \
70         }                                                       \
71         __ret;                                                  \
72 })
73
74 /* fn returns 0 to continue iteration */
75 #define _XT_ENTRY_ITERATE(type, entries, size, fn, args...) \
76         _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, 0, fn, args)
77
78 #define ENTRY_ITERATE(entries, size, fn, args...) \
79         _XT_ENTRY_ITERATE(struct ipt_entry, entries, size, fn, ## args)
80
81 #define MIN_ALIGN (__alignof__(struct ipt_entry))
82
83 #define ALIGN(s) (((s) + ((MIN_ALIGN)-1)) & ~((MIN_ALIGN)-1))
84
85 struct ipt_error_target {
86         struct xt_entry_target t;
87         char error[IPT_TABLE_MAXNAMELEN];
88 };
89
90 struct connman_iptables_entry {
91         int offset;
92
93         struct ipt_entry *entry;
94 };
95
96 struct connman_iptables {
97         int ipt_sock;
98
99         struct ipt_getinfo *info;
100         struct ipt_get_entries *blob_entries;
101
102         unsigned int num_entries;
103         unsigned int old_entries;
104         unsigned int size;
105
106         GList *entries;
107 };
108
109 static GHashTable *table_hash = NULL;
110
111 static struct ipt_entry *get_entry(struct connman_iptables *table,
112                                         unsigned int offset)
113 {
114         return (struct ipt_entry *)((char *)table->blob_entries->entrytable +
115                                                                         offset);
116 }
117
118 static int is_hook_entry(struct connman_iptables *table,
119                                 struct ipt_entry *entry)
120 {
121         unsigned int i;
122
123         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
124                 if ((table->info->valid_hooks & (1 << i))
125                 && get_entry(table, table->info->hook_entry[i]) == entry)
126                         return i;
127         }
128
129         return -1;
130 }
131
132 static unsigned long entry_to_offset(struct connman_iptables *table,
133                                         struct ipt_entry *entry)
134 {
135         return (void *)entry - (void *)table->blob_entries->entrytable;
136 }
137
138 static int target_to_verdict(char *target_name)
139 {
140         if (!strcmp(target_name, LABEL_ACCEPT))
141                 return -NF_ACCEPT - 1;
142
143         if (!strcmp(target_name, LABEL_DROP))
144                 return -NF_DROP - 1;
145
146         if (!strcmp(target_name, LABEL_QUEUE))
147                 return -NF_QUEUE - 1;
148
149         if (!strcmp(target_name, LABEL_RETURN))
150                 return XT_RETURN;
151
152         return 0;
153 }
154
155 static gboolean is_builtin_target(char *target_name)
156 {
157         if (!strcmp(target_name, LABEL_ACCEPT) ||
158                 !strcmp(target_name, LABEL_DROP) ||
159                 !strcmp(target_name, LABEL_QUEUE) ||
160                 !strcmp(target_name, LABEL_RETURN))
161                 return TRUE;
162
163         return FALSE;
164 }
165
166 static gboolean is_jump(struct connman_iptables_entry *e)
167 {
168         struct xt_entry_target *target;
169
170         target = ipt_get_target(e->entry);
171
172         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
173                 struct xt_standard_target *t;
174
175                 t = (struct xt_standard_target *)target;
176
177                 switch (t->verdict) {
178                 case XT_RETURN:
179                 case -NF_ACCEPT - 1:
180                 case -NF_DROP - 1:
181                 case -NF_QUEUE - 1:
182                 case -NF_STOP - 1:
183                         return false;
184
185                 default:
186                         return true;
187                 }
188         }
189
190         return false;
191 }
192
193 static gboolean is_chain(struct connman_iptables *table,
194                                 struct connman_iptables_entry *e)
195 {
196         int builtin;
197         struct ipt_entry *entry;
198         struct xt_entry_target *target;
199
200         entry = e->entry;
201         builtin = is_hook_entry(table, entry);
202         if (builtin >= 0)
203                 return TRUE;
204
205         target = ipt_get_target(entry);
206         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
207                 return TRUE;
208
209         return FALSE;
210 }
211
212 static GList *find_chain_head(struct connman_iptables *table,
213                                 char *chain_name)
214 {
215         GList *list;
216         struct connman_iptables_entry *head;
217         struct ipt_entry *entry;
218         struct xt_entry_target *target;
219         int builtin;
220
221         for (list = table->entries; list; list = list->next) {
222                 head = list->data;
223                 entry = head->entry;
224
225                 /* Buit-in chain */
226                 builtin = is_hook_entry(table, entry);
227                 if (builtin >= 0 && !strcmp(hooknames[builtin], chain_name))
228                         break;
229
230                 /* User defined chain */
231                 target = ipt_get_target(entry);
232                 if (!strcmp(target->u.user.name, IPT_ERROR_TARGET) &&
233                     !strcmp((char *)target->data, chain_name))
234                         break;
235         }
236
237         return list;
238 }
239
240 static GList *find_chain_tail(struct connman_iptables *table,
241                                 char *chain_name)
242 {
243         GList *chain_head, *list;
244         struct connman_iptables_entry *head, *tail;
245         struct ipt_entry *entry;
246         struct xt_entry_target *target;
247         int builtin;
248
249         /* First we look for the head */
250         for (list = table->entries; list; list = list->next) {
251                 head = list->data;
252                 entry = head->entry;
253
254                 /* Buit-in chain */
255                 builtin = is_hook_entry(table, entry);
256                 if (builtin >= 0 && !strcmp(hooknames[builtin], chain_name))
257                         break;
258
259                 /* User defined chain */
260                 target = ipt_get_target(entry);
261                 if (!strcmp(target->u.user.name, IPT_ERROR_TARGET) &&
262                     !strcmp((char *)target->data, chain_name))
263                         break;
264         }
265
266         if (list == NULL)
267                 return NULL;
268
269         chain_head = list;
270
271         /* Then we look for the next chain */
272         for (list = chain_head->next; list; list = list->next) {
273                 tail = list->data;
274                 entry = tail->entry;
275
276                 if (is_chain(table, tail))
277                         return list;
278         }
279
280         /* Nothing found, we return the table end */
281         return g_list_last(table->entries);
282 }
283
284
285 static void update_offsets(struct connman_iptables *table)
286 {
287         GList *list, *prev;
288         struct connman_iptables_entry *entry, *prev_entry;
289
290         for (list = table->entries; list; list = list->next) {
291                 entry = list->data;
292
293                 if (list == table->entries) {
294                         entry->offset = 0;
295
296                         continue;
297                 }
298
299                 prev = list->prev;
300                 prev_entry = prev->data;
301
302                 entry->offset = prev_entry->offset +
303                                         prev_entry->entry->next_offset;
304         }
305 }
306
307 static int iptables_add_entry(struct connman_iptables *table,
308                                 struct ipt_entry *entry, GList *before)
309 {
310         GList *list;
311         struct connman_iptables_entry *e, *tmp, *entry_before;
312         struct xt_standard_target *t;
313
314         if (table == NULL)
315                 return -1;
316
317         e = g_try_malloc0(sizeof(struct connman_iptables_entry));
318         if (e == NULL)
319                 return -1;
320
321         e->entry = entry;
322
323         table->entries = g_list_insert_before(table->entries, before, e);
324         table->num_entries++;
325         table->size += entry->next_offset;
326
327         if (before == NULL) {
328                 e->offset = table->size - entry->next_offset;
329
330                 return 0;
331         }
332
333         entry_before = before->data;
334
335         /*
336          * We've just insterted a new entry. All references before it
337          * should be bumped accordingly.
338          */
339         for (list = table->entries; list != before; list = list->next) {
340                 tmp = list->data;
341
342                 if (!is_jump(tmp))
343                         continue;
344
345                 t = (struct xt_standard_target *)ipt_get_target(tmp->entry);
346
347                 if (t->verdict >= entry_before->offset)
348                         t->verdict += entry->next_offset;
349         }
350
351         update_offsets(table);
352
353         return 0;
354 }
355
356 static int iptables_add_chain(struct connman_iptables *table,
357                                         char *name)
358 {
359         GList *last;
360         struct ipt_entry *entry_head;
361         struct ipt_entry *entry_return;
362         struct ipt_error_target *error;
363         struct ipt_standard_target *standard;
364         u_int16_t entry_head_size, entry_return_size;
365
366         last = g_list_last(table->entries);
367
368         /*
369          * An empty chain is composed of:
370          * - A head entry, with no match and an error target.
371          *   The error target data is the chain name.
372          * - A tail entry, with no match and a standard target.
373          *   The standard target verdict is XT_RETURN (return to the
374          *   caller).
375          */
376
377         /* head entry */
378         entry_head_size = sizeof(struct ipt_entry) +
379                                 sizeof(struct ipt_error_target);
380         entry_head = g_try_malloc0(entry_head_size);
381         if (entry_head == NULL)
382                 goto err;
383
384         memset(entry_head, 0, entry_head_size);
385
386         entry_head->target_offset = sizeof(struct ipt_entry);
387         entry_head->next_offset = entry_head_size;
388
389         error = (struct ipt_error_target *) entry_head->elems;
390         strcpy(error->t.u.user.name, IPT_ERROR_TARGET);
391         error->t.u.user.target_size = ALIGN(sizeof(struct ipt_error_target));
392         strcpy(error->error, name);
393
394         if (iptables_add_entry(table, entry_head, last) < 0)
395                 goto err;
396
397         /* tail entry */
398         entry_return_size = sizeof(struct ipt_entry) +
399                                 sizeof(struct ipt_standard_target);
400         entry_return = g_try_malloc0(entry_return_size);
401         if (entry_return == NULL)
402                 goto err;
403
404         memset(entry_return, 0, entry_return_size);
405
406         entry_return->target_offset = sizeof(struct ipt_entry);
407         entry_return->next_offset = entry_return_size;
408
409         standard = (struct ipt_standard_target *) entry_return->elems;
410         standard->target.u.user.target_size =
411                                 ALIGN(sizeof(struct ipt_standard_target));
412         standard->verdict = XT_RETURN;
413
414         if (iptables_add_entry(table, entry_return, last) < 0)
415                 goto err;
416
417         return 0;
418
419 err:
420         g_free(entry_head);
421         g_free(entry_return);
422
423         return -ENOMEM;
424 }
425
426 static struct ipt_entry *
427 new_rule(struct connman_iptables *table, struct ipt_ip *ip,
428                 char *target_name, struct xtables_target *xt_t,
429                 char *match_name, struct xtables_match *xt_m)
430 {
431         struct ipt_entry *new_entry;
432         size_t match_size, target_size;
433         int is_builtin = is_builtin_target(target_name);
434
435         if (xt_m)
436                 match_size = xt_m->m->u.match_size;
437         else
438                 match_size = 0;
439
440         if (xt_t)
441                 target_size = ALIGN(xt_t->t->u.target_size);
442         else
443                 target_size = ALIGN(sizeof(struct xt_standard_target));
444
445         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
446                                                                 match_size);
447         if (new_entry == NULL)
448                 return NULL;
449
450         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
451
452         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
453         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
454                                                                 match_size;
455         if (xt_m) {
456                 struct xt_entry_match *entry_match;
457
458                 entry_match = (struct xt_entry_match *)new_entry->elems;
459                 memcpy(entry_match, xt_m->m, match_size);
460         }
461
462         if (xt_t) {
463                 struct xt_entry_target *entry_target;
464
465                 if (is_builtin) {
466                         struct xt_standard_target *target;
467
468                         target = (struct xt_standard_target *)(xt_t->t);
469                         strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
470                         target->verdict = target_to_verdict(target_name);
471                 }
472
473                 entry_target = ipt_get_target(new_entry);
474                 memcpy(entry_target, xt_t->t, target_size);
475         } else {
476                 struct connman_iptables_entry *target_rule;
477                 struct xt_standard_target *target;
478                 GList *chain_head;
479
480                 /*
481                  * This is a user defined target, i.e. a chain jump.
482                  * We search for the chain head, and the target verdict
483                  * is the first rule's offset on this chain.
484                  * The offset is from the beginning of the table.
485                  */
486
487                 chain_head = find_chain_head(table, target_name);
488                 if (chain_head == NULL || chain_head->next == NULL) {
489                         g_free(new_entry);
490                         return NULL;
491                 }
492
493                 target_rule = chain_head->next->data;
494
495                 target = (struct xt_standard_target *)ipt_get_target(new_entry);
496                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
497                 target->target.u.user.target_size = target_size;
498                 target->verdict = target_rule->offset;
499         }
500
501         return new_entry;
502 }
503
504 static int
505 iptables_add_rule(struct connman_iptables *table,
506                                 struct ipt_ip *ip, char *chain_name,
507                                 char *target_name, struct xtables_target *xt_t,
508                                 char *match_name, struct xtables_match *xt_m)
509 {
510         GList *chain_tail;
511         struct ipt_entry *new_entry;
512
513         chain_tail = find_chain_tail(table, chain_name);
514         if (chain_tail == NULL)
515                 return -EINVAL;
516
517         new_entry = new_rule(table, ip,
518                                 target_name, xt_t,
519                                 match_name, xt_m);
520         if (new_entry == NULL)
521                 return -EINVAL;
522
523         return iptables_add_entry(table, new_entry, chain_tail->prev);
524 }
525
526 static struct ipt_replace *
527 iptables_blob(struct connman_iptables *table)
528 {
529         struct ipt_replace *r;
530         GList *list;
531         struct connman_iptables_entry *e;
532         unsigned char *entry_index;
533
534         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
535         if (r == NULL)
536                 return NULL;
537
538         memset(r, 0, sizeof(*r) + table->size);
539
540         r->counters = g_try_malloc0(sizeof(struct xt_counters)
541                                 * table->num_entries);
542         if (r->counters == NULL) {
543                 g_free(r);
544                 return NULL;
545         }
546
547         strcpy(r->name, table->info->name);
548         r->num_entries = table->num_entries;
549         r->size = table->size;
550
551         r->num_counters = table->old_entries;
552         r->valid_hooks  = table->info->valid_hooks;
553
554         memcpy(r->hook_entry, table->info->hook_entry,
555                                 sizeof(table->info->hook_entry));
556         memcpy(r->underflow, table->info->underflow,
557                                 sizeof(table->info->underflow));
558
559         entry_index = (unsigned char *)r->entries;
560         for (list = table->entries; list; list = list->next) {
561                 e = list->data;
562
563                 memcpy(entry_index, e->entry, e->entry->next_offset);
564                 entry_index += e->entry->next_offset;
565         }
566
567         return r;
568 }
569
570 static void dump_ip(struct ipt_entry *entry)
571 {
572         struct ipt_ip *ip = &entry->ip;
573         char ip_string[INET6_ADDRSTRLEN];
574         char ip_mask[INET6_ADDRSTRLEN];
575
576         if (strlen(ip->iniface))
577                 connman_info("\tin %s", ip->iniface);
578
579         if (strlen(ip->outiface))
580                 connman_info("\tout %s", ip->outiface);
581
582         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
583                         inet_ntop(AF_INET, &ip->smsk,
584                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
585                 connman_info("\tsrc %s/%s", ip_string, ip_mask);
586
587         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
588                         inet_ntop(AF_INET, &ip->dmsk,
589                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
590                 connman_info("\tdst %s/%s", ip_string, ip_mask);
591 }
592
593 static void dump_target(struct connman_iptables *table,
594                                 struct ipt_entry *entry)
595
596 {
597         struct xtables_target *xt_t;
598         struct xt_entry_target *target;
599
600         target = ipt_get_target(entry);
601
602         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
603                 struct xt_standard_target *t;
604
605                 t = (struct xt_standard_target *)target;
606
607                 switch (t->verdict) {
608                 case XT_RETURN:
609                         connman_info("\ttarget RETURN");
610                         break;
611
612                 case -NF_ACCEPT - 1:
613                         connman_info("\ttarget ACCEPT");
614                         break;
615
616                 case -NF_DROP - 1:
617                         connman_info("\ttarget DROP");
618                         break;
619
620                 case -NF_QUEUE - 1:
621                         connman_info("\ttarget QUEUE");
622                         break;
623
624                 case -NF_STOP - 1:
625                         connman_info("\ttarget STOP");
626                         break;
627
628                 default:
629                         connman_info("\tJUMP @%p (0x%x)",
630                                 (char*)table->blob_entries->entrytable +
631                                 t->verdict, t->verdict);
632                         break;
633                 }
634
635                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
636                                                 XTF_LOAD_MUST_SUCCEED);
637
638                 if(xt_t->print != NULL)
639                         xt_t->print(NULL, target, 1);
640         } else {
641                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
642                 if (xt_t == NULL) {
643                         connman_info("\ttarget %s", target->u.user.name);
644                         return;
645                 }
646
647                 if(xt_t->print != NULL) {
648                         connman_info("\ttarget ");
649                         xt_t->print(NULL, target, 1);
650                 }
651         }
652 }
653
654 static void dump_match(struct connman_iptables *table, struct ipt_entry *entry)
655 {
656         struct xtables_match *xt_m;
657         struct xt_entry_match *match;
658
659         if (entry->elems == (unsigned char *)entry + entry->target_offset)
660                 return;
661
662         match = (struct xt_entry_match *) entry->elems;
663
664         if (!strlen(match->u.user.name))
665                 return;
666
667         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
668         if (xt_m == NULL)
669                 goto out;
670
671         if(xt_m->print != NULL) {
672                 connman_info("\tmatch ");
673                 xt_m->print(NULL, match, 1);
674
675                 return;
676         }
677
678 out:
679         connman_info("\tmatch %s", match->u.user.name);
680
681 }
682
683 static int dump_entry(struct ipt_entry *entry,
684                                 struct connman_iptables *table)
685 {
686         struct xt_entry_target *target;
687         unsigned int offset;
688         int builtin;
689
690         offset = (char *)entry - (char *)table->blob_entries->entrytable;
691         target = ipt_get_target(entry);
692         builtin = is_hook_entry(table, entry);
693
694         if (entry_to_offset(table, entry) + entry->next_offset ==
695                                         table->blob_entries->size) {
696                 connman_info("End of CHAIN 0x%x", offset);
697                 return 0;
698         }
699
700         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
701                 connman_info("USER CHAIN (%s) %p  match %p  target %p  size %d",
702                         target->data, entry, entry->elems,
703                         (char *)entry + entry->target_offset,
704                                 entry->next_offset);
705
706                 return 0;
707         } else if (builtin >= 0) {
708                 connman_info("CHAIN (%s) %p  match %p  target %p  size %d",
709                         hooknames[builtin], entry, entry->elems,
710                         (char *)entry + entry->target_offset,
711                                 entry->next_offset);
712         } else {
713                 connman_info("RULE %p  match %p  target %p  size %d", entry,
714                         entry->elems,
715                         (char *)entry + entry->target_offset,
716                                 entry->next_offset);
717         }
718
719         dump_match(table, entry);
720         dump_target(table, entry);
721         dump_ip(entry);
722
723         return 0;
724 }
725
726 static void iptables_dump(struct connman_iptables *table)
727 {
728         connman_info("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
729                         table->info->name,
730                         table->info->valid_hooks, table->info->num_entries,
731                                 table->info->size);
732
733         ENTRY_ITERATE(table->blob_entries->entrytable,
734                         table->blob_entries->size,
735                         dump_entry, table);
736
737 }
738
739 static int iptables_get_entries(struct connman_iptables *table)
740 {
741         socklen_t entry_size;
742
743         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
744
745         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
746                                 table->blob_entries, &entry_size);
747 }
748
749 static int iptables_replace(struct connman_iptables *table,
750                                         struct ipt_replace *r)
751 {
752         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
753                          sizeof(*r) + r->size);
754 }
755
756 static int add_entry(struct ipt_entry *entry, struct connman_iptables *table)
757 {
758         struct ipt_entry *new_entry;
759
760         new_entry = g_try_malloc0(entry->next_offset);
761         if (new_entry == NULL)
762                 return -ENOMEM;
763
764         memcpy(new_entry, entry, entry->next_offset);
765
766         return iptables_add_entry(table, new_entry, NULL);
767 }
768
769 static void table_cleanup(struct connman_iptables *table)
770 {
771         GList *list;
772         struct connman_iptables_entry *entry;
773
774         close(table->ipt_sock);
775
776         for (list = table->entries; list; list = list->next) {
777                 entry = list->data;
778
779                 g_free(entry->entry);
780         }
781
782         g_list_free(table->entries);
783         g_free(table->info);
784         g_free(table->blob_entries);
785         g_free(table);
786 }
787
788 static struct connman_iptables *iptables_init(char *table_name)
789 {
790         struct connman_iptables *table;
791         socklen_t s;
792
793         table = g_hash_table_lookup(table_hash, table_name);
794         if (table != NULL)
795                 return table;
796
797         table = g_try_new0(struct connman_iptables, 1);
798         if (table == NULL)
799                 return NULL;
800
801         table->info = g_try_new0(struct ipt_getinfo, 1);
802         if (table->info == NULL)
803                 goto err;
804
805         table->ipt_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
806         if (table->ipt_sock < 0)
807                 goto err;
808
809         s = sizeof(*table->info);
810         strcpy(table->info->name, table_name);
811         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
812                                                 table->info, &s) < 0)
813                 goto err;
814
815         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
816                                                 table->info->size);
817         if (table->blob_entries == NULL)
818                 goto err;
819
820         strcpy(table->blob_entries->name, table_name);
821         table->blob_entries->size = table->info->size;
822
823         if (iptables_get_entries(table) < 0)
824                 goto err;
825
826         table->num_entries = 0;
827         table->old_entries = table->info->num_entries;
828         table->size = 0;
829
830         ENTRY_ITERATE(table->blob_entries->entrytable,
831                         table->blob_entries->size,
832                                 add_entry, table);
833
834         g_hash_table_insert(table_hash, table_name, table);
835
836         return table;
837
838 err:
839
840         table_cleanup(table);
841
842         return NULL;
843 }
844
845 static struct option iptables_opts[] = {
846         {.name = "append",        .has_arg = 1, .val = 'A'},
847         {.name = "list",          .has_arg = 2, .val = 'L'},
848         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
849         {.name = "destination",   .has_arg = 1, .val = 'd'},
850         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
851         {.name = "jump",          .has_arg = 1, .val = 'j'},
852         {.name = "match",         .has_arg = 1, .val = 'm'},
853         {.name = "out-interface", .has_arg = 1, .val = 'o'},
854         {.name = "source",        .has_arg = 1, .val = 's'},
855         {.name = "table",         .has_arg = 1, .val = 't'},
856         {NULL},
857 };
858
859 struct xtables_globals iptables_globals = {
860         .option_offset = 0,
861         .opts = iptables_opts,
862         .orig_opts = iptables_opts,
863 };
864
865 static int iptables_command(int argc, char *argv[])
866 {
867         struct connman_iptables *table;
868         struct xtables_match *xt_m;
869         struct xtables_target *xt_t;
870         struct ipt_ip ip;
871         char *table_name, *chain, *new_chain, *match_name, *target_name;
872         int c, ret, in_len, out_len;
873         size_t size;
874         gboolean dump, invert;
875         struct in_addr src, dst;
876
877         if (argc == 0)
878                 return -EINVAL;
879
880         dump = FALSE;
881         invert = FALSE;
882         table_name = chain = new_chain = match_name = target_name = NULL;
883         memset(&ip, 0, sizeof(struct ipt_ip));
884         table = NULL;
885         xt_m = NULL;
886         xt_t = NULL;
887         ret = 0;
888
889         optind = 0;
890
891         while ((c = getopt_long(argc, argv,
892            "-A:L::N:d:j:i:m:o:s:t:", iptables_globals.opts, NULL)) != -1) {
893                 switch (c) {
894                 case 'A':
895                         chain = optarg;
896                         break;
897
898                 case 'L':
899                         dump = TRUE;
900                         break;
901
902                 case 'N':
903                         new_chain = optarg;
904                         break;
905
906                 case 'd':
907                         if (!inet_pton(AF_INET, optarg, &dst))
908                                 break;
909
910                         ip.dst = dst;
911                         inet_pton(AF_INET, "255.255.255.255", &ip.dmsk);
912
913                         if (invert)
914                                 ip.invflags |= IPT_INV_DSTIP;
915
916                         break;
917
918                 case 'i':
919                         in_len = strlen(optarg);
920
921                         if (in_len + 1 > IFNAMSIZ)
922                                 break;
923
924                         strcpy(ip.iniface, optarg);
925                         memset(ip.iniface_mask, 0xff, in_len + 1);
926
927                         if (invert)
928                                 ip.invflags |= IPT_INV_VIA_IN;
929
930                         break;
931
932                 case 'j':
933                         target_name = optarg;
934                         xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
935
936                         if (xt_t == NULL)
937                                 break;
938
939                         size = ALIGN(sizeof(struct ipt_entry_target)) +
940                                                                 xt_t->size;
941
942                         xt_t->t = g_try_malloc0(size);
943                         if (xt_t->t == NULL)
944                                 goto out;
945                         xt_t->t->u.target_size = size;
946                         strcpy(xt_t->t->u.user.name, target_name);
947                         xt_t->t->u.user.revision = xt_t->revision;
948                         if (xt_t->init != NULL)
949                                 xt_t->init(xt_t->t);
950                         iptables_globals.opts =
951                                 xtables_merge_options(iptables_globals.opts,
952                                                      xt_t->extra_opts,
953                                                      &xt_t->option_offset);
954                         if (iptables_globals.opts == NULL)
955                                 goto out;
956
957                         break;
958
959                 case 'm':
960                         match_name = optarg;
961
962                         xt_m = xtables_find_match(optarg, XTF_LOAD_MUST_SUCCEED, NULL);
963                         size = ALIGN(sizeof(struct ipt_entry_match)) +
964                                                                 xt_m->size;
965                         xt_m->m = g_try_malloc0(size);
966                         if (xt_m == NULL)
967                                 goto out;
968                         xt_m->m->u.match_size = size;
969                         strcpy(xt_m->m->u.user.name, xt_m->name);
970                         xt_m->m->u.user.revision = xt_m->revision;
971                         if (xt_m->init != NULL)
972                                 xt_m->init(xt_m->m);
973                         if (xt_m != xt_m->next) {
974                                 iptables_globals.opts =
975                                 xtables_merge_options(iptables_globals.opts,
976                                                 xt_m->extra_opts,
977                                                 &xt_m->option_offset);
978                                 if (iptables_globals.opts == NULL)
979                                         goto out;
980                         }
981
982                         break;
983
984                 case 'o':
985                         out_len = strlen(optarg);
986
987                         if (out_len + 1 > IFNAMSIZ)
988                                 break;
989
990                         strcpy(ip.outiface, optarg);
991                         memset(ip.outiface_mask, 0xff, out_len + 1);
992
993                         if (invert)
994                                 ip.invflags |= IPT_INV_VIA_OUT;
995
996                         break;
997
998                 case 's':
999                         if (!inet_pton(AF_INET, optarg, &src))
1000                                 break;
1001
1002                         ip.src = src;
1003                         inet_pton(AF_INET, "255.255.255.255", &ip.smsk);
1004
1005                         if (invert)
1006                                 ip.invflags |= IPT_INV_SRCIP;
1007
1008                         break;
1009
1010                 case 't':
1011                         table_name = optarg;
1012                         break;
1013
1014                 case 1:
1015                         if (optarg[0] == '!' && optarg[1] == '\0') {
1016                                 invert = TRUE;
1017                                 optarg[0] = '\0';
1018                                 continue;
1019                         }
1020
1021                         connman_error("Invalid option");
1022
1023                         ret = -EINVAL;
1024                         goto out;
1025
1026                 default:
1027                         if (xt_t == NULL || xt_t->parse == NULL ||
1028                             !xt_t->parse(c - xt_t->option_offset, argv, invert,
1029                                         &xt_t->tflags, NULL, &xt_t->t)) {
1030                                 if (xt_m == NULL || xt_m->parse == NULL)
1031                                         break;
1032
1033                                 xt_m->parse(c - xt_m->option_offset, argv,
1034                                         invert, &xt_m->mflags, NULL, &xt_m->m);
1035                         }
1036
1037                         break;
1038                 }
1039
1040                 invert = FALSE;
1041         }
1042
1043         if (table_name == NULL)
1044                 table_name = "filter";
1045
1046         table = iptables_init(table_name);
1047         if (table == NULL) {
1048                 ret = -EINVAL;
1049                 goto out;
1050         }
1051
1052         if (dump) {
1053                 iptables_dump(table);
1054
1055                 ret = 0;
1056                 goto out;
1057         }
1058
1059         if (chain && new_chain) {
1060                 ret = -EINVAL;
1061                 goto out;
1062         }
1063
1064         if (new_chain) {
1065                 DBG("New chain %s", new_chain);
1066
1067                 ret = iptables_add_chain(table, new_chain);
1068                 goto out;
1069         }
1070
1071         if (chain) {
1072                 if (target_name == NULL)
1073                         return -1;
1074
1075                 DBG("Adding %s to %s (match %s)",
1076                                 target_name, chain, match_name);
1077
1078                 ret = iptables_add_rule(table, &ip, chain, target_name, xt_t,
1079                                         match_name, xt_m);
1080
1081                 goto out;
1082         }
1083
1084 out:
1085         if (xt_t)
1086                 g_free(xt_t->t);
1087
1088         if (xt_m)
1089                 g_free(xt_m->m);
1090
1091         return ret;
1092 }
1093
1094 int __connman_iptables_command(const char *format, ...)
1095 {
1096         char **argv, **arguments, *command;
1097         int argc, i, ret;
1098         va_list args;
1099
1100         if (format == NULL)
1101                 return -EINVAL;
1102
1103         va_start(args, format);
1104
1105         command = g_strdup_vprintf(format, args);
1106
1107         va_end(args);
1108
1109         if (command == NULL)
1110                 return -ENOMEM;
1111
1112         arguments = g_strsplit_set(command, " ", -1);
1113
1114         for (argc = 0; arguments[argc]; argc++);
1115
1116         DBG("command %s argc %d", command, ++argc);
1117
1118         argv = g_try_malloc0(argc * sizeof(char *));
1119         if (argv == NULL) {
1120                 g_free(command);
1121                 g_strfreev(arguments);
1122                 return -ENOMEM;
1123         }
1124
1125         argv[0] = "iptables";
1126         for (i = 1; i < argc; i++)
1127                 argv[i] = arguments[i - 1];
1128
1129         ret = iptables_command(argc, argv);
1130
1131         g_free(command);
1132         g_strfreev(arguments);
1133         g_free(argv);
1134
1135         return ret;
1136 }
1137
1138
1139 int __connman_iptables_commit(const char *table_name)
1140 {
1141         struct connman_iptables *table;
1142         struct ipt_replace *repl;
1143
1144         table = g_hash_table_lookup(table_hash, table_name);
1145         if (table == NULL)
1146                 return -EINVAL;
1147
1148         repl = iptables_blob(table);
1149
1150         return iptables_replace(table, repl);
1151 }
1152
1153 static void remove_table(gpointer user_data)
1154 {
1155         struct connman_iptables *table = user_data;
1156
1157         table_cleanup(table);
1158 }
1159
1160 int __connman_iptables_init(void)
1161 {
1162         DBG("");
1163
1164         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
1165                                                 NULL, remove_table);
1166
1167         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
1168
1169         return 0;
1170
1171 }
1172
1173 void __connman_iptables_cleanup(void)
1174 {
1175         g_hash_table_destroy(table_hash);
1176
1177         xtables_free_opts(1);
1178 }