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