84e40829cb37e59644dc2b46a2e3d7443719dcd4
[platform/upstream/connman.git] / src / iptables.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2012  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 /*
41  * Some comments on how the iptables API works (some of them from the
42  * source code from iptables and the kernel):
43  *
44  * - valid_hooks: bit indicates valid IDs for hook_entry
45  * - hook_entry[ID] offset to the chain start
46  * - overflows should be end of entry chains, and uncodintional policy nodes.
47  * - policy entry: last entry in a chain
48  * - user chain: end of last builtin + policy entry
49  * - final entry must be error node
50  * - Underflows must be unconditional and use the STANDARD target with
51  *   ACCEPT/DROP
52  * - IPT_SO_GET_INFO and IPT_SO_GET_ENTRIES are used to read a table
53  * - IPT_SO_GET_INFO: struct ipt_getinfo (note the lack of table content)
54  * - IPT_SO_GET_ENTRIES: struct ipt_get_entries (contains only parts of the
55  *   table header/meta info. The table is appended after the header. The entries
56  *   are of the type struct ipt_entry.
57  * - After the ipt_entry the matches are appended. After the matches
58  *   the target is appended.
59  * - ipt_entry->target_offset =  Size of ipt_entry + matches
60  * - ipt_entry->next_offset =  Size of ipt_entry + matches + target
61  * - IPT_SO_SET_REPLACE is used to write a table (contains the complete
62  * - hook_entry and overflow mark the begining and the end of a chain, e.g
63  *     entry hook: pre/in/fwd/out/post -1/0/352/504/-1
64  *     underflow:  pre/in/fwd/out/post -1/200/352/904/-1
65  *   means that INPUT starts at offset 0 and ends at 200 (the start offset to
66  *   the last element). FORWARD has one entry starting/ending at 352. The entry
67  *   has a size of 152. 352 + 152 = 504 which is the start of the OUTPUT chain
68  *   which then ends at 904. PREROUTING and POSTROUTING are invalid hooks in
69  *   the filter table.
70  * - 'iptables -t filter -A INPUT -m mark --mark 999 -j LOG'
71  *   writing that table looks like this:
72  *
73  *   filter valid_hooks 0x0000000e  num_entries 5  size 856
74  *   entry hook: pre/in/fwd/out/post -1/0/376/528/-1
75  *   underflow:  pre/in/fwd/out/post -1/224/376/528/-1
76  *   entry 0x699d30  offset 0  size 224
77  *     RULE  match 0x699da0  target 0x699dd0
78  *             match  mark match 0x3e7
79  *             target  LOG flags 0 level 4
80  *             src 0.0.0.0/0.0.0.0
81  *             dst 0.0.0.0/0.0.0.0
82  *   entry 0x699e10  offset 224  size 152
83  *     RULE  match 0x699e80  target 0x699e80
84  *             target ACCEPT
85  *             src 0.0.0.0/0.0.0.0
86  *             dst 0.0.0.0/0.0.0.0
87  *   entry 0x699ea8  offset 376  size 152
88  *     RULE  match 0x699f18  target 0x699f18
89  *             target ACCEPT
90  *             src 0.0.0.0/0.0.0.0
91  *             dst 0.0.0.0/0.0.0.0
92  *   entry 0x699f40  offset 528  size 152
93  *     RULE  match 0x699fb0  target 0x699fb0
94  *             target ACCEPT
95  *             src 0.0.0.0/0.0.0.0
96  *             dst 0.0.0.0/0.0.0.0
97  *   entry 0x699fd8  offset 680  size 176
98  *     USER CHAIN (ERROR)  match 0x69a048  target 0x69a048
99  *
100  *   Reading the filter table looks like this:
101  *
102  *   filter valid_hooks 0x0000000e  num_entries 5  size 856
103  *   entry hook: pre/in/fwd/out/post -1/0/376/528/-1
104  *   underflow:  pre/in/fwd/out/post -1/224/376/528/-1
105  *   entry 0x25fec28  offset 0  size 224
106  *     CHAIN (INPUT)  match 0x25fec98  target 0x25fecc8
107  *             match  mark match 0x3e7
108  *             target  LOG flags 0 level 4
109  *             src 0.0.0.0/0.0.0.0
110  *             dst 0.0.0.0/0.0.0.0
111  *   entry 0x25fed08  offset 224  size 152
112  *     RULE  match 0x25fed78  target 0x25fed78
113  *             target ACCEPT
114  *             src 0.0.0.0/0.0.0.0
115  *             dst 0.0.0.0/0.0.0.0
116  *   entry 0x25feda0  offset 376  size 152
117  *     CHAIN (FORWARD)  match 0x25fee10  target 0x25fee10
118  *             target ACCEPT
119  *             src 0.0.0.0/0.0.0.0
120  *             dst 0.0.0.0/0.0.0.0
121  *   entry 0x25fee38  offset 528  size 152
122  *     CHAIN (OUTPUT)  match 0x25feea8  target 0x25feea8
123  *             target ACCEPT
124  *             src 0.0.0.0/0.0.0.0
125  *             dst 0.0.0.0/0.0.0.0
126  *   entry 0x25feed0  offset 680  size 176
127  *     End of CHAIN
128  */
129
130 static const char *hooknames[] = {
131         [NF_IP_PRE_ROUTING]     = "PREROUTING",
132         [NF_IP_LOCAL_IN]        = "INPUT",
133         [NF_IP_FORWARD]         = "FORWARD",
134         [NF_IP_LOCAL_OUT]       = "OUTPUT",
135         [NF_IP_POST_ROUTING]    = "POSTROUTING",
136 };
137
138 #define LABEL_ACCEPT  "ACCEPT"
139 #define LABEL_DROP    "DROP"
140 #define LABEL_QUEUE   "QUEUE"
141 #define LABEL_RETURN  "RETURN"
142
143 #define XT_OPTION_OFFSET_SCALE 256
144
145 /* fn returns 0 to continue iteration */
146 #define _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, n, fn, args...) \
147 ({                                                              \
148         unsigned int __i;                                       \
149         int __n;                                                \
150         int __ret = 0;                                          \
151         type *__entry;                                          \
152                                                                 \
153         for (__i = 0, __n = 0; __i < (size);                    \
154              __i += __entry->next_offset, __n++) {              \
155                 __entry = (void *)(entries) + __i;              \
156                 if (__n < n)                                    \
157                         continue;                               \
158                                                                 \
159                 __ret = fn(__entry,  ## args);                  \
160                 if (__ret != 0)                                 \
161                         break;                                  \
162         }                                                       \
163         __ret;                                                  \
164 })
165
166 /* fn returns 0 to continue iteration */
167 #define _XT_ENTRY_ITERATE(type, entries, size, fn, args...) \
168         _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, 0, fn, args)
169
170 #define ENTRY_ITERATE(entries, size, fn, args...) \
171         _XT_ENTRY_ITERATE(struct ipt_entry, entries, size, fn, ## args)
172
173 #define MIN_ALIGN (__alignof__(struct ipt_entry))
174
175 #define ALIGN(s) (((s) + ((MIN_ALIGN)-1)) & ~((MIN_ALIGN)-1))
176
177 struct error_target {
178         struct xt_entry_target t;
179         char error[IPT_TABLE_MAXNAMELEN];
180 };
181
182 struct connman_iptables_entry {
183         int offset;
184         int builtin;
185
186         struct ipt_entry *entry;
187 };
188
189 struct connman_iptables {
190         int ipt_sock;
191
192         struct ipt_getinfo *info;
193         struct ipt_get_entries *blob_entries;
194
195         unsigned int num_entries;
196         unsigned int old_entries;
197         unsigned int size;
198
199         unsigned int underflow[NF_INET_NUMHOOKS];
200         unsigned int hook_entry[NF_INET_NUMHOOKS];
201
202         GList *entries;
203 };
204
205 static GHashTable *table_hash = NULL;
206
207 static struct ipt_entry *get_entry(struct connman_iptables *table,
208                                         unsigned int offset)
209 {
210         return (struct ipt_entry *)((char *)table->blob_entries->entrytable +
211                                                                         offset);
212 }
213
214 static int is_hook_entry(struct connman_iptables *table,
215                                 struct ipt_entry *entry)
216 {
217         unsigned int i;
218
219         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
220                 if ((table->info->valid_hooks & (1 << i))
221                 && get_entry(table, table->info->hook_entry[i]) == entry)
222                         return i;
223         }
224
225         return -1;
226 }
227
228 static unsigned long entry_to_offset(struct connman_iptables *table,
229                                         struct ipt_entry *entry)
230 {
231         return (void *)entry - (void *)table->blob_entries->entrytable;
232 }
233
234 static int target_to_verdict(char *target_name)
235 {
236         if (!strcmp(target_name, LABEL_ACCEPT))
237                 return -NF_ACCEPT - 1;
238
239         if (!strcmp(target_name, LABEL_DROP))
240                 return -NF_DROP - 1;
241
242         if (!strcmp(target_name, LABEL_QUEUE))
243                 return -NF_QUEUE - 1;
244
245         if (!strcmp(target_name, LABEL_RETURN))
246                 return XT_RETURN;
247
248         return 0;
249 }
250
251 static gboolean is_builtin_target(char *target_name)
252 {
253         if (!strcmp(target_name, LABEL_ACCEPT) ||
254                 !strcmp(target_name, LABEL_DROP) ||
255                 !strcmp(target_name, LABEL_QUEUE) ||
256                 !strcmp(target_name, LABEL_RETURN))
257                 return TRUE;
258
259         return FALSE;
260 }
261
262 static gboolean is_jump(struct connman_iptables_entry *e)
263 {
264         struct xt_entry_target *target;
265
266         target = ipt_get_target(e->entry);
267
268         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
269                 struct xt_standard_target *t;
270
271                 t = (struct xt_standard_target *)target;
272
273                 switch (t->verdict) {
274                 case XT_RETURN:
275                 case -NF_ACCEPT - 1:
276                 case -NF_DROP - 1:
277                 case -NF_QUEUE - 1:
278                 case -NF_STOP - 1:
279                         return false;
280
281                 default:
282                         return true;
283                 }
284         }
285
286         return false;
287 }
288
289 static gboolean is_chain(struct connman_iptables *table,
290                                 struct connman_iptables_entry *e)
291 {
292         struct ipt_entry *entry;
293         struct xt_entry_target *target;
294
295         entry = e->entry;
296         if (e->builtin >= 0)
297                 return TRUE;
298
299         target = ipt_get_target(entry);
300         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
301                 return TRUE;
302
303         return FALSE;
304 }
305
306 static GList *find_chain_head(struct connman_iptables *table,
307                                 char *chain_name)
308 {
309         GList *list;
310         struct connman_iptables_entry *head;
311         struct ipt_entry *entry;
312         struct xt_entry_target *target;
313         int builtin;
314
315         for (list = table->entries; list; list = list->next) {
316                 head = list->data;
317                 entry = head->entry;
318
319                 /* Buit-in chain */
320                 builtin = head->builtin;
321                 if (builtin >= 0 && !strcmp(hooknames[builtin], chain_name))
322                         break;
323
324                 /* User defined chain */
325                 target = ipt_get_target(entry);
326                 if (!strcmp(target->u.user.name, IPT_ERROR_TARGET) &&
327                     !strcmp((char *)target->data, chain_name))
328                         break;
329         }
330
331         return list;
332 }
333
334 static GList *find_chain_tail(struct connman_iptables *table,
335                                 char *chain_name)
336 {
337         struct connman_iptables_entry *tail;
338         GList *chain_head, *list;
339
340         chain_head = find_chain_head(table, chain_name);
341         if (chain_head == NULL)
342                 return NULL;
343
344         /* Then we look for the next chain */
345         for (list = chain_head->next; list; list = list->next) {
346                 tail = list->data;
347
348                 if (is_chain(table, tail))
349                         return list;
350         }
351
352         /* Nothing found, we return the table end */
353         return g_list_last(table->entries);
354 }
355
356
357 static void update_offsets(struct connman_iptables *table)
358 {
359         GList *list, *prev;
360         struct connman_iptables_entry *entry, *prev_entry;
361
362         for (list = table->entries; list; list = list->next) {
363                 entry = list->data;
364
365                 if (list == table->entries) {
366                         entry->offset = 0;
367
368                         continue;
369                 }
370
371                 prev = list->prev;
372                 prev_entry = prev->data;
373
374                 entry->offset = prev_entry->offset +
375                                         prev_entry->entry->next_offset;
376         }
377 }
378
379 static void update_targets_reference(struct connman_iptables *table,
380                                 struct connman_iptables_entry *entry_before,
381                                 struct connman_iptables_entry *modified_entry,
382                                 gboolean is_removing)
383 {
384         struct connman_iptables_entry *tmp;
385         struct xt_standard_target *t;
386         GList *list;
387         int offset;
388
389         offset = modified_entry->entry->next_offset;
390
391         for (list = table->entries; list; list = list->next) {
392                 tmp = list->data;
393
394                 if (!is_jump(tmp))
395                         continue;
396
397                 t = (struct xt_standard_target *)ipt_get_target(tmp->entry);
398
399                 if (is_removing == TRUE) {
400                         if (t->verdict >= entry_before->offset)
401                                 t->verdict -= offset;
402                 } else {
403                         if (t->verdict > entry_before->offset)
404                                 t->verdict += offset;
405                 }
406         }
407 }
408
409 static int iptables_add_entry(struct connman_iptables *table,
410                                 struct ipt_entry *entry, GList *before,
411                                         int builtin)
412 {
413         struct connman_iptables_entry *e, *entry_before;
414
415         if (table == NULL)
416                 return -1;
417
418         e = g_try_malloc0(sizeof(struct connman_iptables_entry));
419         if (e == NULL)
420                 return -1;
421
422         e->entry = entry;
423         e->builtin = builtin;
424
425         table->entries = g_list_insert_before(table->entries, before, e);
426         table->num_entries++;
427         table->size += entry->next_offset;
428
429         if (before == NULL) {
430                 e->offset = table->size - entry->next_offset;
431
432                 return 0;
433         }
434
435         entry_before = before->data;
436
437         /*
438          * We've just appended/insterted a new entry. All references
439          * should be bumped accordingly.
440          */
441         update_targets_reference(table, entry_before, e, FALSE);
442
443         update_offsets(table);
444
445         return 0;
446 }
447
448 static int remove_table_entry(struct connman_iptables *table,
449                                 struct connman_iptables_entry *entry)
450 {
451         int removed = 0;
452
453         table->num_entries--;
454         table->size -= entry->entry->next_offset;
455         removed = entry->entry->next_offset;
456
457         g_free(entry->entry);
458
459         table->entries = g_list_remove(table->entries, entry);
460
461         return removed;
462 }
463
464 static int iptables_flush_chain(struct connman_iptables *table,
465                                                 char *name)
466 {
467         GList *chain_head, *chain_tail, *list, *next;
468         struct connman_iptables_entry *entry;
469         int builtin, removed = 0;
470
471         chain_head = find_chain_head(table, name);
472         if (chain_head == NULL)
473                 return -EINVAL;
474
475         chain_tail = find_chain_tail(table, name);
476         if (chain_tail == NULL)
477                 return -EINVAL;
478
479         entry = chain_head->data;
480         builtin = entry->builtin;
481
482         if (builtin >= 0)
483                 list = chain_head;
484         else
485                 list = chain_head->next;
486
487         if (list == chain_tail->prev)
488                 return 0;
489
490         while (list != chain_tail->prev) {
491                 entry = list->data;
492                 next = g_list_next(list);
493
494                 removed += remove_table_entry(table, entry);
495
496                 list = next;
497         }
498
499         if (builtin >= 0) {
500                 struct connman_iptables_entry *e;
501
502                 entry = list->data;
503
504                 entry->builtin = builtin;
505
506                 table->underflow[builtin] -= removed;
507
508                 for (list = chain_tail; list; list = list->next) {
509                         e = list->data;
510
511                         builtin = e->builtin;
512                         if (builtin < 0)
513                                 continue;
514
515                         table->hook_entry[builtin] -= removed;
516                         table->underflow[builtin] -= removed;
517                 }
518         }
519
520         update_offsets(table);
521
522         return 0;
523 }
524
525 static int iptables_add_chain(struct connman_iptables *table,
526                                         char *name)
527 {
528         GList *last;
529         struct ipt_entry *entry_head;
530         struct ipt_entry *entry_return;
531         struct error_target *error;
532         struct ipt_standard_target *standard;
533         u_int16_t entry_head_size, entry_return_size;
534
535         last = g_list_last(table->entries);
536
537         /*
538          * An empty chain is composed of:
539          * - A head entry, with no match and an error target.
540          *   The error target data is the chain name.
541          * - A tail entry, with no match and a standard target.
542          *   The standard target verdict is XT_RETURN (return to the
543          *   caller).
544          */
545
546         /* head entry */
547         entry_head_size = sizeof(struct ipt_entry) +
548                                 sizeof(struct error_target);
549         entry_head = g_try_malloc0(entry_head_size);
550         if (entry_head == NULL)
551                 goto err_head;
552
553         memset(entry_head, 0, entry_head_size);
554
555         entry_head->target_offset = sizeof(struct ipt_entry);
556         entry_head->next_offset = entry_head_size;
557
558         error = (struct error_target *) entry_head->elems;
559         strcpy(error->t.u.user.name, IPT_ERROR_TARGET);
560         error->t.u.user.target_size = ALIGN(sizeof(struct error_target));
561         strcpy(error->error, name);
562
563         if (iptables_add_entry(table, entry_head, last, -1) < 0)
564                 goto err_head;
565
566         /* tail entry */
567         entry_return_size = sizeof(struct ipt_entry) +
568                                 sizeof(struct ipt_standard_target);
569         entry_return = g_try_malloc0(entry_return_size);
570         if (entry_return == NULL)
571                 goto err;
572
573         memset(entry_return, 0, entry_return_size);
574
575         entry_return->target_offset = sizeof(struct ipt_entry);
576         entry_return->next_offset = entry_return_size;
577
578         standard = (struct ipt_standard_target *) entry_return->elems;
579         standard->target.u.user.target_size =
580                                 ALIGN(sizeof(struct ipt_standard_target));
581         standard->verdict = XT_RETURN;
582
583         if (iptables_add_entry(table, entry_return, last, -1) < 0)
584                 goto err;
585
586         return 0;
587
588 err:
589         g_free(entry_return);
590 err_head:
591         g_free(entry_head);
592
593         return -ENOMEM;
594 }
595
596 static int iptables_delete_chain(struct connman_iptables *table, char *name)
597 {
598         struct connman_iptables_entry *entry;
599         GList *chain_head, *chain_tail;
600
601         chain_head = find_chain_head(table, name);
602         if (chain_head == NULL)
603                 return -EINVAL;
604
605         entry = chain_head->data;
606
607         /* We cannot remove builtin chain */
608         if (entry->builtin >= 0)
609                 return -EINVAL;
610
611         chain_tail = find_chain_tail(table, name);
612         if (chain_tail == NULL)
613                 return -EINVAL;
614
615         /* Chain must be flushed */
616         if (chain_head->next != chain_tail->prev)
617                 return -EINVAL;
618
619         remove_table_entry(table, entry);
620
621         entry = chain_tail->prev->data;
622         remove_table_entry(table, entry);
623
624         update_offsets(table);
625
626         return 0;
627 }
628
629 static struct ipt_entry *new_rule(struct ipt_ip *ip,
630                 char *target_name, struct xtables_target *xt_t,
631                 struct xtables_rule_match *xt_rm)
632 {
633         struct xtables_rule_match *tmp_xt_rm;
634         struct ipt_entry *new_entry;
635         size_t match_size, target_size;
636
637         match_size = 0;
638         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL; tmp_xt_rm = tmp_xt_rm->next)
639                 match_size += tmp_xt_rm->match->m->u.match_size;
640
641         if (xt_t)
642                 target_size = ALIGN(xt_t->t->u.target_size);
643         else
644                 target_size = ALIGN(sizeof(struct xt_standard_target));
645
646         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
647                                                                 match_size);
648         if (new_entry == NULL)
649                 return NULL;
650
651         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
652
653         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
654         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
655                                                                 match_size;
656
657         match_size = 0;
658         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
659                                 tmp_xt_rm = tmp_xt_rm->next) {
660                 memcpy(new_entry->elems + match_size, tmp_xt_rm->match->m,
661                                         tmp_xt_rm->match->m->u.match_size);
662                 match_size += tmp_xt_rm->match->m->u.match_size;
663         }
664
665         if (xt_t) {
666                 struct xt_entry_target *entry_target;
667
668                 entry_target = ipt_get_target(new_entry);
669                 memcpy(entry_target, xt_t->t, target_size);
670         }
671
672         return new_entry;
673 }
674
675 static void update_hooks(struct connman_iptables *table, GList *chain_head,
676                                 struct ipt_entry *entry)
677 {
678         GList *list;
679         struct connman_iptables_entry *head, *e;
680         int builtin;
681
682         if (chain_head == NULL)
683                 return;
684
685         head = chain_head->data;
686
687         builtin = head->builtin;
688         if (builtin < 0)
689                 return;
690
691         table->underflow[builtin] += entry->next_offset;
692
693         for (list = chain_head->next; list; list = list->next) {
694                 e = list->data;
695
696                 builtin = e->builtin;
697                 if (builtin < 0)
698                         continue;
699
700                 table->hook_entry[builtin] += entry->next_offset;
701                 table->underflow[builtin] += entry->next_offset;
702         }
703 }
704
705 static struct ipt_entry *prepare_rule_inclusion(struct connman_iptables *table,
706                                 struct ipt_ip *ip, char *chain_name,
707                                 char *target_name, struct xtables_target *xt_t,
708                                 int *builtin, struct xtables_rule_match *xt_rm)
709 {
710         GList *chain_tail, *chain_head;
711         struct ipt_entry *new_entry;
712         struct connman_iptables_entry *head;
713
714         chain_head = find_chain_head(table, chain_name);
715         if (chain_head == NULL)
716                 return NULL;
717
718         chain_tail = find_chain_tail(table, chain_name);
719         if (chain_tail == NULL)
720                 return NULL;
721
722         new_entry = new_rule(ip, target_name, xt_t, xt_rm);
723         if (new_entry == NULL)
724                 return NULL;
725
726         update_hooks(table, chain_head, new_entry);
727
728         /*
729          * If the chain is builtin, and does not have any rule,
730          * then the one that we're inserting is becoming the head
731          * and thus needs the builtin flag.
732          */
733         head = chain_head->data;
734         if (head->builtin < 0)
735                 *builtin = -1;
736         else if (chain_head == chain_tail->prev) {
737                 *builtin = head->builtin;
738                 head->builtin = -1;
739         }
740
741         return new_entry;
742 }
743
744 static int iptables_append_rule(struct connman_iptables *table,
745                                 struct ipt_ip *ip, char *chain_name,
746                                 char *target_name, struct xtables_target *xt_t,
747                                 struct xtables_rule_match *xt_rm)
748 {
749         GList *chain_tail;
750         struct ipt_entry *new_entry;
751         int builtin = -1, ret;
752
753         DBG("");
754
755         chain_tail = find_chain_tail(table, chain_name);
756         if (chain_tail == NULL)
757                 return -EINVAL;
758
759         new_entry = prepare_rule_inclusion(table, ip, chain_name,
760                                         target_name, xt_t, &builtin, xt_rm);
761         if (new_entry == NULL)
762                 return -EINVAL;
763
764         ret = iptables_add_entry(table, new_entry, chain_tail->prev, builtin);
765         if (ret < 0)
766                 g_free(new_entry);
767
768         return ret;
769 }
770
771 static int iptables_insert_rule(struct connman_iptables *table,
772                                 struct ipt_ip *ip, char *chain_name,
773                                 char *target_name, struct xtables_target *xt_t,
774                                 struct xtables_rule_match *xt_rm)
775 {
776         struct ipt_entry *new_entry;
777         int builtin = -1, ret;
778         GList *chain_head;
779
780         chain_head = find_chain_head(table, chain_name);
781         if (chain_head == NULL)
782                 return -EINVAL;
783
784         new_entry = prepare_rule_inclusion(table, ip, chain_name,
785                                         target_name, xt_t, &builtin, xt_rm);
786         if (new_entry == NULL)
787                 return -EINVAL;
788
789         if (builtin == -1)
790                 chain_head = chain_head->next;
791
792         ret = iptables_add_entry(table, new_entry, chain_head, builtin);
793         if (ret < 0)
794                 g_free(new_entry);
795
796         return ret;
797 }
798
799 static gboolean is_same_ipt_entry(struct ipt_entry *i_e1,
800                                         struct ipt_entry *i_e2)
801 {
802         if (memcmp(&i_e1->ip, &i_e2->ip, sizeof(struct ipt_ip)) != 0)
803                 return FALSE;
804
805         if (i_e1->target_offset != i_e2->target_offset)
806                 return FALSE;
807
808         if (i_e1->next_offset != i_e2->next_offset)
809                 return FALSE;
810
811         return TRUE;
812 }
813
814 static gboolean is_same_target(struct xt_entry_target *xt_e_t1,
815                                         struct xt_entry_target *xt_e_t2)
816 {
817         if (xt_e_t1 == NULL || xt_e_t2 == NULL)
818                 return FALSE;
819
820         if (strcmp(xt_e_t1->u.user.name, IPT_STANDARD_TARGET) == 0) {
821                 struct xt_standard_target *xt_s_t1;
822                 struct xt_standard_target *xt_s_t2;
823
824                 xt_s_t1 = (struct xt_standard_target *) xt_e_t1;
825                 xt_s_t2 = (struct xt_standard_target *) xt_e_t2;
826
827                 if (xt_s_t1->verdict != xt_s_t2->verdict)
828                         return FALSE;
829         } else {
830                 if (xt_e_t1->u.target_size != xt_e_t2->u.target_size)
831                         return FALSE;
832
833                 if (strcmp(xt_e_t1->u.user.name, xt_e_t2->u.user.name) != 0)
834                         return FALSE;
835         }
836
837         return TRUE;
838 }
839
840 static gboolean is_same_match(struct xt_entry_match *xt_e_m1,
841                                 struct xt_entry_match *xt_e_m2)
842 {
843         if (xt_e_m1 == NULL || xt_e_m2 == NULL)
844                 return FALSE;
845
846         if (xt_e_m1->u.match_size != xt_e_m2->u.match_size)
847                 return FALSE;
848
849         if (xt_e_m1->u.user.revision != xt_e_m2->u.user.revision)
850                 return FALSE;
851
852         if (strcmp(xt_e_m1->u.user.name, xt_e_m2->u.user.name) != 0)
853                 return FALSE;
854
855         return TRUE;
856 }
857
858 static GList *find_existing_rule(struct connman_iptables *table,
859                                 struct ipt_ip *ip, char *chain_name,
860                                 char *target_name, struct xtables_target *xt_t,
861                                 struct xtables_match *xt_m,
862                                 struct xtables_rule_match *xt_rm)
863 {
864         GList *chain_tail, *chain_head, *list;
865         struct xt_entry_target *xt_e_t = NULL;
866         struct xt_entry_match *xt_e_m = NULL;
867         struct connman_iptables_entry *entry;
868         struct ipt_entry *entry_test;
869         int builtin;
870
871         chain_head = find_chain_head(table, chain_name);
872         if (chain_head == NULL)
873                 return NULL;
874
875         chain_tail = find_chain_tail(table, chain_name);
876         if (chain_tail == NULL)
877                 return NULL;
878
879         if (!xt_t && !xt_m)
880                 return NULL;
881
882         entry_test = new_rule(ip, target_name, xt_t, xt_rm);
883         if (entry_test == NULL)
884                 return NULL;
885
886         if (xt_t != NULL)
887                 xt_e_t = ipt_get_target(entry_test);
888         if (xt_m != NULL)
889                 xt_e_m = (struct xt_entry_match *)entry_test->elems;
890
891         entry = chain_head->data;
892         builtin = entry->builtin;
893
894         if (builtin >= 0)
895                 list = chain_head;
896         else
897                 list = chain_head->next;
898
899         for (; list != chain_tail->prev; list = list->next) {
900                 struct connman_iptables_entry *tmp;
901                 struct ipt_entry *tmp_e;
902
903                 tmp = list->data;
904                 tmp_e = tmp->entry;
905
906                 if (is_same_ipt_entry(entry_test, tmp_e) == FALSE)
907                         continue;
908
909                 if (xt_t != NULL) {
910                         struct xt_entry_target *tmp_xt_e_t;
911
912                         tmp_xt_e_t = ipt_get_target(tmp_e);
913
914                         if (!is_same_target(tmp_xt_e_t, xt_e_t))
915                                 continue;
916                 }
917
918                 if (xt_m != NULL) {
919                         struct xt_entry_match *tmp_xt_e_m;
920
921                         tmp_xt_e_m = (struct xt_entry_match *)tmp_e->elems;
922
923                         if (!is_same_match(tmp_xt_e_m, xt_e_m))
924                                 continue;
925                 }
926
927                 break;
928         }
929
930         g_free(entry_test);
931
932         if (list != chain_tail->prev)
933                 return list;
934
935         return NULL;
936 }
937
938 static int iptables_delete_rule(struct connman_iptables *table,
939                                 struct ipt_ip *ip, char *chain_name,
940                                 char *target_name, struct xtables_target *xt_t,
941                                 struct xtables_match *xt_m,
942                                 struct xtables_rule_match *xt_rm)
943 {
944         struct connman_iptables_entry *entry;
945         GList *chain_tail, *list;
946         int builtin, removed;
947
948         removed = 0;
949
950         chain_tail = find_chain_tail(table, chain_name);
951         if (chain_tail == NULL)
952                 return -EINVAL;
953
954         list = find_existing_rule(table, ip, chain_name, target_name,
955                                                         xt_t, xt_m, xt_rm);
956         if (list == NULL)
957                 return -EINVAL;
958
959         entry = list->data;
960         if (entry == NULL)
961                 return -EINVAL;
962
963         builtin = entry->builtin;
964
965         /* We have deleted a rule,
966          * all references should be bumped accordingly */
967         if (list->next != NULL)
968                 update_targets_reference(table, list->next->data,
969                                                 list->data, TRUE);
970
971         removed += remove_table_entry(table, entry);
972
973         if (builtin >= 0) {
974                 list = list->next;
975                 if (list) {
976                         entry = list->data;
977                         entry->builtin = builtin;
978                 }
979
980                 table->underflow[builtin] -= removed;
981                 for (list = chain_tail; list; list = list->next) {
982                         entry = list->data;
983
984                         builtin = entry->builtin;
985                         if (builtin < 0)
986                                 continue;
987
988                         table->hook_entry[builtin] -= removed;
989                         table->underflow[builtin] -= removed;
990                 }
991         }
992
993         update_offsets(table);
994
995         return 0;
996 }
997
998 static int iptables_compare_rule(struct connman_iptables *table,
999                                 struct ipt_ip *ip, char *chain_name,
1000                                 char *target_name, struct xtables_target *xt_t,
1001                                 struct xtables_match *xt_m,
1002                                 struct xtables_rule_match *xt_rm)
1003 {
1004         struct connman_iptables_entry *entry;
1005         GList *found;
1006
1007         found = find_existing_rule(table, ip, chain_name, target_name,
1008                                                         xt_t, xt_m, xt_rm);
1009         if (found == NULL)
1010                 return -EINVAL;
1011
1012         entry = found->data;
1013         if (entry == NULL)
1014                 return -EINVAL;
1015
1016         return 0;
1017 }
1018
1019
1020 static int iptables_change_policy(struct connman_iptables *table,
1021                                         char *chain_name, char *policy)
1022 {
1023         GList *chain_head;
1024         struct connman_iptables_entry *entry;
1025         struct xt_entry_target *target;
1026         struct xt_standard_target *t;
1027         int verdict;
1028
1029         verdict = target_to_verdict(policy);
1030         if (verdict == 0)
1031                 return -EINVAL;
1032
1033         chain_head = find_chain_head(table, chain_name);
1034         if (chain_head == NULL)
1035                 return -EINVAL;
1036
1037         entry = chain_head->data;
1038         if (entry->builtin < 0)
1039                 return -EINVAL;
1040
1041         target = ipt_get_target(entry->entry);
1042
1043         t = (struct xt_standard_target *)target;
1044         t->verdict = verdict;
1045
1046         return 0;
1047 }
1048
1049 static struct ipt_replace *iptables_blob(struct connman_iptables *table)
1050 {
1051         struct ipt_replace *r;
1052         GList *list;
1053         struct connman_iptables_entry *e;
1054         unsigned char *entry_index;
1055
1056         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
1057         if (r == NULL)
1058                 return NULL;
1059
1060         memset(r, 0, sizeof(*r) + table->size);
1061
1062         r->counters = g_try_malloc0(sizeof(struct xt_counters)
1063                                 * table->old_entries);
1064         if (r->counters == NULL) {
1065                 g_free(r);
1066                 return NULL;
1067         }
1068
1069         strcpy(r->name, table->info->name);
1070         r->num_entries = table->num_entries;
1071         r->size = table->size;
1072
1073         r->num_counters = table->old_entries;
1074         r->valid_hooks  = table->info->valid_hooks;
1075
1076         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
1077         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
1078
1079         entry_index = (unsigned char *)r->entries;
1080         for (list = table->entries; list; list = list->next) {
1081                 e = list->data;
1082
1083                 memcpy(entry_index, e->entry, e->entry->next_offset);
1084                 entry_index += e->entry->next_offset;
1085         }
1086
1087         return r;
1088 }
1089
1090 static void dump_ip(struct ipt_entry *entry)
1091 {
1092         struct ipt_ip *ip = &entry->ip;
1093         char ip_string[INET6_ADDRSTRLEN];
1094         char ip_mask[INET6_ADDRSTRLEN];
1095
1096         if (strlen(ip->iniface))
1097                 connman_info("\tin %s", ip->iniface);
1098
1099         if (strlen(ip->outiface))
1100                 connman_info("\tout %s", ip->outiface);
1101
1102         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
1103                         inet_ntop(AF_INET, &ip->smsk,
1104                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1105                 connman_info("\tsrc %s/%s", ip_string, ip_mask);
1106
1107         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
1108                         inet_ntop(AF_INET, &ip->dmsk,
1109                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
1110                 connman_info("\tdst %s/%s", ip_string, ip_mask);
1111 }
1112
1113 static void dump_target(struct connman_iptables *table,
1114                                 struct ipt_entry *entry)
1115
1116 {
1117         struct xtables_target *xt_t;
1118         struct xt_entry_target *target;
1119
1120         target = ipt_get_target(entry);
1121
1122         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
1123                 struct xt_standard_target *t;
1124
1125                 t = (struct xt_standard_target *)target;
1126
1127                 switch (t->verdict) {
1128                 case XT_RETURN:
1129                         connman_info("\ttarget RETURN");
1130                         break;
1131
1132                 case -NF_ACCEPT - 1:
1133                         connman_info("\ttarget ACCEPT");
1134                         break;
1135
1136                 case -NF_DROP - 1:
1137                         connman_info("\ttarget DROP");
1138                         break;
1139
1140                 case -NF_QUEUE - 1:
1141                         connman_info("\ttarget QUEUE");
1142                         break;
1143
1144                 case -NF_STOP - 1:
1145                         connman_info("\ttarget STOP");
1146                         break;
1147
1148                 default:
1149                         connman_info("\tJUMP @%p (0x%x)",
1150                                 (char*)table->blob_entries->entrytable +
1151                                 t->verdict, t->verdict);
1152                         break;
1153                 }
1154
1155                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1156                                                 XTF_LOAD_MUST_SUCCEED);
1157
1158                 if(xt_t->print != NULL)
1159                         xt_t->print(NULL, target, 1);
1160         } else {
1161                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
1162                 if (xt_t == NULL) {
1163                         connman_info("\ttarget %s", target->u.user.name);
1164                         return;
1165                 }
1166
1167                 if(xt_t->print != NULL) {
1168                         connman_info("\ttarget ");
1169                         xt_t->print(NULL, target, 1);
1170                 }
1171         }
1172 }
1173
1174 static void dump_match(struct connman_iptables *table, struct ipt_entry *entry)
1175 {
1176         struct xtables_match *xt_m;
1177         struct xt_entry_match *match;
1178
1179         if (entry->elems == (unsigned char *)entry + entry->target_offset)
1180                 return;
1181
1182         match = (struct xt_entry_match *) entry->elems;
1183
1184         if (!strlen(match->u.user.name))
1185                 return;
1186
1187         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
1188         if (xt_m == NULL)
1189                 goto out;
1190
1191         if(xt_m->print != NULL) {
1192                 connman_info("\tmatch ");
1193                 xt_m->print(NULL, match, 1);
1194
1195                 return;
1196         }
1197
1198 out:
1199         connman_info("\tmatch %s", match->u.user.name);
1200
1201 }
1202
1203 static int dump_entry(struct ipt_entry *entry,
1204                                 struct connman_iptables *table)
1205 {
1206         struct xt_entry_target *target;
1207         unsigned int offset;
1208         int builtin;
1209
1210         offset = (char *)entry - (char *)table->blob_entries->entrytable;
1211         target = ipt_get_target(entry);
1212         builtin = is_hook_entry(table, entry);
1213
1214         if (entry_to_offset(table, entry) + entry->next_offset ==
1215                                         table->blob_entries->size) {
1216                 connman_info("End of CHAIN 0x%x", offset);
1217                 return 0;
1218         }
1219
1220         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
1221                 connman_info("USER CHAIN (%s) %p  match %p  target %p  size %d",
1222                         target->data, entry, entry->elems,
1223                         (char *)entry + entry->target_offset,
1224                                 entry->next_offset);
1225
1226                 return 0;
1227         } else if (builtin >= 0) {
1228                 connman_info("CHAIN (%s) %p  match %p  target %p  size %d",
1229                         hooknames[builtin], entry, entry->elems,
1230                         (char *)entry + entry->target_offset,
1231                                 entry->next_offset);
1232         } else {
1233                 connman_info("RULE %p  match %p  target %p  size %d", entry,
1234                         entry->elems,
1235                         (char *)entry + entry->target_offset,
1236                                 entry->next_offset);
1237         }
1238
1239         dump_match(table, entry);
1240         dump_target(table, entry);
1241         dump_ip(entry);
1242
1243         return 0;
1244 }
1245
1246 static void iptables_dump(struct connman_iptables *table)
1247 {
1248         connman_info("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
1249                         table->info->name,
1250                         table->info->valid_hooks, table->info->num_entries,
1251                                 table->info->size);
1252
1253         ENTRY_ITERATE(table->blob_entries->entrytable,
1254                         table->blob_entries->size,
1255                         dump_entry, table);
1256
1257 }
1258
1259 static int iptables_get_entries(struct connman_iptables *table)
1260 {
1261         socklen_t entry_size;
1262
1263         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
1264
1265         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
1266                                 table->blob_entries, &entry_size);
1267 }
1268
1269 static int iptables_replace(struct connman_iptables *table,
1270                                         struct ipt_replace *r)
1271 {
1272         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
1273                          sizeof(*r) + r->size);
1274 }
1275
1276 static int add_entry(struct ipt_entry *entry, struct connman_iptables *table)
1277 {
1278         struct ipt_entry *new_entry;
1279         int builtin;
1280
1281         new_entry = g_try_malloc0(entry->next_offset);
1282         if (new_entry == NULL)
1283                 return -ENOMEM;
1284
1285         memcpy(new_entry, entry, entry->next_offset);
1286
1287         builtin = is_hook_entry(table, entry);
1288
1289         return iptables_add_entry(table, new_entry, NULL, builtin);
1290 }
1291
1292 static void table_cleanup(struct connman_iptables *table)
1293 {
1294         GList *list;
1295         struct connman_iptables_entry *entry;
1296
1297         if (table == NULL)
1298                 return;
1299
1300         if (table->ipt_sock >= 0)
1301                 close(table->ipt_sock);
1302
1303         for (list = table->entries; list; list = list->next) {
1304                 entry = list->data;
1305
1306                 g_free(entry->entry);
1307                 g_free(entry);
1308         }
1309
1310         g_list_free(table->entries);
1311         g_free(table->info);
1312         g_free(table->blob_entries);
1313         g_free(table);
1314 }
1315
1316 static struct connman_iptables *iptables_init(char *table_name)
1317 {
1318         struct connman_iptables *table = NULL;
1319         char *module = NULL;
1320         socklen_t s;
1321
1322         if (table_name == NULL)
1323                 table_name = "filter";
1324
1325         DBG("%s", table_name);
1326
1327         if (xtables_insmod("ip_tables", NULL, TRUE) != 0)
1328                 DBG("ip_tables module loading gives error but trying anyway");
1329
1330         module = g_strconcat("iptable_", table_name, NULL);
1331         if (module == NULL)
1332                 return NULL;
1333
1334         if (xtables_insmod(module, NULL, TRUE) != 0)
1335                 DBG("%s module loading gives error but trying anyway", module);
1336
1337         g_free(module);
1338
1339         table = g_hash_table_lookup(table_hash, table_name);
1340         if (table != NULL)
1341                 return table;
1342
1343         table = g_try_new0(struct connman_iptables, 1);
1344         if (table == NULL)
1345                 return NULL;
1346
1347         table->info = g_try_new0(struct ipt_getinfo, 1);
1348         if (table->info == NULL)
1349                 goto err;
1350
1351         table->ipt_sock = socket(AF_INET, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_RAW);
1352         if (table->ipt_sock < 0)
1353                 goto err;
1354
1355         s = sizeof(*table->info);
1356         strcpy(table->info->name, table_name);
1357         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
1358                                                 table->info, &s) < 0) {
1359                 connman_error("iptables support missing error %d (%s)", errno,
1360                         strerror(errno));
1361                 goto err;
1362         }
1363
1364         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
1365                                                 table->info->size);
1366         if (table->blob_entries == NULL)
1367                 goto err;
1368
1369         strcpy(table->blob_entries->name, table_name);
1370         table->blob_entries->size = table->info->size;
1371
1372         if (iptables_get_entries(table) < 0)
1373                 goto err;
1374
1375         table->num_entries = 0;
1376         table->old_entries = table->info->num_entries;
1377         table->size = 0;
1378
1379         memcpy(table->underflow, table->info->underflow,
1380                                 sizeof(table->info->underflow));
1381         memcpy(table->hook_entry, table->info->hook_entry,
1382                                 sizeof(table->info->hook_entry));
1383
1384         ENTRY_ITERATE(table->blob_entries->entrytable,
1385                         table->blob_entries->size,
1386                                 add_entry, table);
1387
1388         g_hash_table_insert(table_hash, g_strdup(table_name), table);
1389
1390         return table;
1391
1392 err:
1393         table_cleanup(table);
1394
1395         return NULL;
1396 }
1397
1398 static struct option iptables_opts[] = {
1399         {.name = "append",        .has_arg = 1, .val = 'A'},
1400         {.name = "compare",       .has_arg = 1, .val = 'C'},
1401         {.name = "delete",        .has_arg = 1, .val = 'D'},
1402         {.name = "flush-chain",   .has_arg = 1, .val = 'F'},
1403         {.name = "insert",        .has_arg = 1, .val = 'I'},
1404         {.name = "list",          .has_arg = 2, .val = 'L'},
1405         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
1406         {.name = "policy",        .has_arg = 1, .val = 'P'},
1407         {.name = "delete-chain",  .has_arg = 1, .val = 'X'},
1408         {.name = "destination",   .has_arg = 1, .val = 'd'},
1409         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
1410         {.name = "jump",          .has_arg = 1, .val = 'j'},
1411         {.name = "match",         .has_arg = 1, .val = 'm'},
1412         {.name = "out-interface", .has_arg = 1, .val = 'o'},
1413         {.name = "source",        .has_arg = 1, .val = 's'},
1414         {.name = "table",         .has_arg = 1, .val = 't'},
1415         {NULL},
1416 };
1417
1418 struct xtables_globals iptables_globals = {
1419         .option_offset = 0,
1420         .opts = iptables_opts,
1421         .orig_opts = iptables_opts,
1422 };
1423
1424 static struct xtables_target *prepare_target(struct connman_iptables *table,
1425                                                         char *target_name)
1426 {
1427         struct xtables_target *xt_t = NULL;
1428         gboolean is_builtin, is_user_defined;
1429         GList *chain_head = NULL;
1430         size_t target_size;
1431
1432         is_builtin = FALSE;
1433         is_user_defined = FALSE;
1434
1435         if (is_builtin_target(target_name))
1436                 is_builtin = TRUE;
1437         else {
1438                 chain_head = find_chain_head(table, target_name);
1439                 if (chain_head != NULL && chain_head->next != NULL)
1440                         is_user_defined = TRUE;
1441         }
1442
1443         if (is_builtin || is_user_defined)
1444                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
1445                                                 XTF_LOAD_MUST_SUCCEED);
1446         else
1447                 xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1448
1449         if (xt_t == NULL)
1450                 return NULL;
1451
1452         target_size = ALIGN(sizeof(struct ipt_entry_target)) + xt_t->size;
1453
1454         xt_t->t = g_try_malloc0(target_size);
1455         if (xt_t->t == NULL)
1456                 return NULL;
1457
1458         xt_t->t->u.target_size = target_size;
1459
1460         if (is_builtin || is_user_defined) {
1461                 struct xt_standard_target *target;
1462
1463                 target = (struct xt_standard_target *)(xt_t->t);
1464                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
1465
1466                 if (is_builtin == TRUE)
1467                         target->verdict = target_to_verdict(target_name);
1468                 else if (is_user_defined == TRUE) {
1469                         struct connman_iptables_entry *target_rule;
1470
1471                         if (chain_head == NULL) {
1472                                 g_free(xt_t->t);
1473                                 return NULL;
1474                         }
1475
1476                         target_rule = chain_head->next->data;
1477                         target->verdict = target_rule->offset;
1478                 }
1479         } else {
1480                 strcpy(xt_t->t->u.user.name, target_name);
1481                 xt_t->t->u.user.revision = xt_t->revision;
1482                 if (xt_t->init != NULL)
1483                         xt_t->init(xt_t->t);
1484         }
1485
1486 #if XTABLES_VERSION_CODE > 5
1487         if (xt_t->x6_options != NULL)
1488                 iptables_globals.opts =
1489                         xtables_options_xfrm(
1490                                 iptables_globals.orig_opts,
1491                                 iptables_globals.opts,
1492                                 xt_t->x6_options,
1493                                 &xt_t->option_offset);
1494         else
1495 #endif
1496                 iptables_globals.opts =
1497                         xtables_merge_options(
1498 #if XTABLES_VERSION_CODE > 5
1499                                 iptables_globals.orig_opts,
1500 #endif
1501                                 iptables_globals.opts,
1502                                 xt_t->extra_opts,
1503                                 &xt_t->option_offset);
1504
1505         if (iptables_globals.opts == NULL) {
1506                 g_free(xt_t->t);
1507                 xt_t = NULL;
1508         }
1509
1510         return xt_t;
1511 }
1512
1513 static struct xtables_match *prepare_matches(struct connman_iptables *table,
1514                         struct xtables_rule_match **xt_rm, char *match_name)
1515 {
1516         struct xtables_match *xt_m;
1517         size_t match_size;
1518
1519         if (match_name == NULL)
1520                 return NULL;
1521
1522         xt_m = xtables_find_match(match_name, XTF_LOAD_MUST_SUCCEED, xt_rm);
1523         match_size = ALIGN(sizeof(struct ipt_entry_match)) + xt_m->size;
1524
1525         xt_m->m = g_try_malloc0(match_size);
1526         if (xt_m->m == NULL)
1527                 return NULL;
1528
1529         xt_m->m->u.match_size = match_size;
1530         strcpy(xt_m->m->u.user.name, xt_m->name);
1531         xt_m->m->u.user.revision = xt_m->revision;
1532
1533         if (xt_m->init != NULL)
1534                 xt_m->init(xt_m->m);
1535
1536         if (xt_m == xt_m->next)
1537                 goto done;
1538
1539 #if XTABLES_VERSION_CODE > 5
1540         if (xt_m->x6_options != NULL)
1541                 iptables_globals.opts =
1542                         xtables_options_xfrm(
1543                                 iptables_globals.orig_opts,
1544                                 iptables_globals.opts,
1545                                 xt_m->x6_options,
1546                                 &xt_m->option_offset);
1547         else
1548 #endif
1549                         iptables_globals.opts =
1550                         xtables_merge_options(
1551 #if XTABLES_VERSION_CODE > 5
1552                                 iptables_globals.orig_opts,
1553 #endif
1554                                 iptables_globals.opts,
1555                                 xt_m->extra_opts,
1556                                 &xt_m->option_offset);
1557
1558         if (iptables_globals.opts == NULL) {
1559                 g_free(xt_m->m);
1560                 xt_m = NULL;
1561         }
1562
1563 done:
1564         return xt_m;
1565 }
1566
1567 static int parse_ip_and_mask(const char *str, struct in_addr *ip, struct in_addr *mask)
1568 {
1569         char **tokens;
1570         uint32_t prefixlength;
1571         uint32_t tmp;
1572         int err;
1573
1574         tokens = g_strsplit(str, "/", 2);
1575         if (tokens == NULL)
1576                 return -1;
1577
1578         if (!inet_pton(AF_INET, tokens[0], ip)) {
1579                 err = -1;
1580                 goto out;
1581         }
1582
1583         if (tokens[1] != NULL) {
1584                 prefixlength = strtol(tokens[1], NULL, 10);
1585                 if (prefixlength > 31) {
1586                         err = -1;
1587                         goto out;
1588                 }
1589
1590                 tmp = ~(0xffffffff >> prefixlength);
1591         } else {
1592                 tmp = 0xffffffff;
1593         }
1594
1595         mask->s_addr = htonl(tmp);
1596         ip->s_addr = ip->s_addr & mask->s_addr;
1597         err = 0;
1598 out:
1599         g_strfreev(tokens);
1600
1601         return err;
1602 }
1603
1604 static struct connman_iptables *pre_load_table(char *table_name,
1605                                         struct connman_iptables *table)
1606 {
1607         if (table != NULL)
1608                 return table;
1609
1610         return iptables_init(table_name);
1611 }
1612
1613 static int iptables_command(int argc, char *argv[])
1614 {
1615         struct connman_iptables *table;
1616         struct xtables_rule_match *xt_rm, *tmp_xt_rm;
1617         struct xtables_match *xt_m, *xt_m_t;
1618         struct xtables_target *xt_t;
1619         struct ipt_ip ip;
1620         char *table_name, *chain, *new_chain, *match_name, *target_name;
1621         char *flush_chain, *delete_chain, *policy;
1622         int c, ret, in_len, out_len;
1623         gboolean dump, invert, insert, delete, compare;
1624
1625         if (argc == 0)
1626                 return -EINVAL;
1627
1628         dump = FALSE;
1629         invert = FALSE;
1630         insert = FALSE;
1631         delete = FALSE;
1632         compare = FALSE;
1633         chain = new_chain = match_name = target_name = NULL;
1634         flush_chain = delete_chain = policy = table_name = NULL;
1635         memset(&ip, 0, sizeof(struct ipt_ip));
1636         table = NULL;
1637         xt_rm = NULL;
1638         xt_m = NULL;
1639         xt_t = NULL;
1640         /* Default code for options parsing */
1641         ret = -EINVAL;
1642
1643         /* extension's options will generate false-positives errors */
1644         opterr = 0;
1645
1646         optind = 0;
1647
1648         while ((c = getopt_long(argc, argv,
1649                                         "-A:C:D:F:I:L::N:P:X:d:j:i:m:o:s:t:",
1650                                         iptables_globals.opts, NULL)) != -1) {
1651                 switch (c) {
1652                 case 'A':
1653                         /* It is either -A, -C, -D or -I at once */
1654                         if (chain)
1655                                 goto out;
1656
1657                         chain = optarg;
1658                         break;
1659
1660                 case 'C':
1661                         /* It is either -A, -C, -D or -I at once */
1662                         if (chain)
1663                                 goto out;
1664
1665                         chain = optarg;
1666                         compare = TRUE;
1667                         break;
1668
1669                 case 'D':
1670                         /* It is either -A, -C, -D or -I at once */
1671                         if (chain)
1672                                 goto out;
1673
1674                         chain = optarg;
1675                         delete = TRUE;
1676                         break;
1677
1678                 case 'F':
1679                         flush_chain = optarg;
1680                         break;
1681
1682                 case 'I':
1683                         /* It is either -A, -C, -D or -I at once */
1684                         if (chain)
1685                                 goto out;
1686
1687                         chain = optarg;
1688                         insert = TRUE;
1689                         break;
1690
1691                 case 'L':
1692                         dump = TRUE;
1693                         break;
1694
1695                 case 'N':
1696                         new_chain = optarg;
1697                         break;
1698
1699                 case 'P':
1700                         chain = optarg;
1701                         if (optind < argc)
1702                                 policy = argv[optind++];
1703                         else
1704                                 goto out;
1705
1706                         break;
1707
1708                 case 'X':
1709                         delete_chain = optarg;
1710                         break;
1711
1712                 case 'd':
1713                         if (!parse_ip_and_mask(optarg, &ip.dst, &ip.dmsk))
1714                                 break;
1715
1716                         if (invert)
1717                                 ip.invflags |= IPT_INV_DSTIP;
1718
1719                         break;
1720
1721                 case 'i':
1722                         in_len = strlen(optarg);
1723
1724                         if (in_len + 1 > IFNAMSIZ)
1725                                 break;
1726
1727                         strcpy(ip.iniface, optarg);
1728                         memset(ip.iniface_mask, 0xff, in_len + 1);
1729
1730                         if (invert)
1731                                 ip.invflags |= IPT_INV_VIA_IN;
1732
1733                         break;
1734
1735                 case 'j':
1736                         target_name = optarg;
1737
1738                         table = pre_load_table(table_name, table);
1739                         if (table == NULL)
1740                                 goto out;
1741
1742                         xt_t = prepare_target(table, target_name);
1743                         if (xt_t == NULL)
1744                                 goto out;
1745
1746                         break;
1747
1748                 case 'm':
1749                         match_name = optarg;
1750
1751                         table = pre_load_table(table_name, table);
1752                         if (table == NULL)
1753                                 goto out;
1754
1755                         xt_m = prepare_matches(table, &xt_rm, match_name);
1756                         if (xt_m == NULL)
1757                                 goto out;
1758
1759                         break;
1760
1761                 case 'o':
1762                         out_len = strlen(optarg);
1763
1764                         if (out_len + 1 > IFNAMSIZ)
1765                                 break;
1766
1767                         strcpy(ip.outiface, optarg);
1768                         memset(ip.outiface_mask, 0xff, out_len + 1);
1769
1770                         if (invert)
1771                                 ip.invflags |= IPT_INV_VIA_OUT;
1772
1773                         break;
1774
1775                 case 's':
1776                         if (!parse_ip_and_mask(optarg, &ip.src, &ip.smsk))
1777                                 break;
1778
1779                         if (invert)
1780                                 ip.invflags |= IPT_INV_SRCIP;
1781
1782                         break;
1783
1784                 case 't':
1785                         table_name = optarg;
1786
1787                         table = pre_load_table(table_name, table);
1788                         if (table == NULL)
1789                                 goto out;
1790
1791                         break;
1792
1793                 case 1:
1794                         if (optarg[0] == '!' && optarg[1] == '\0') {
1795                                 invert = TRUE;
1796                                 optarg[0] = '\0';
1797                                 continue;
1798                         }
1799
1800                         connman_error("Invalid option");
1801
1802                         goto out;
1803
1804                 default:
1805 #if XTABLES_VERSION_CODE > 5
1806                         if (xt_t != NULL && (xt_t->x6_parse != NULL ||
1807                                                 xt_t->parse != NULL) &&
1808                                         (c >= (int) xt_t->option_offset &&
1809                                         c < (int) xt_t->option_offset +
1810                                         XT_OPTION_OFFSET_SCALE)) {
1811                                 xtables_option_tpcall(c, argv,
1812                                                         invert, xt_t, NULL);
1813
1814                                 break;
1815                         }
1816
1817                         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
1818                                                 tmp_xt_rm = tmp_xt_rm->next) {
1819                                 xt_m_t = tmp_xt_rm->match;
1820
1821                                 if (tmp_xt_rm->completed ||
1822                                                 (xt_m_t->x6_parse == NULL &&
1823                                                  xt_m_t->parse == NULL))
1824                                         continue;
1825
1826                                 if (c < (int) xt_m_t->option_offset ||
1827                                         c >= (int) xt_m_t->option_offset
1828                                         + XT_OPTION_OFFSET_SCALE)
1829                                         continue;
1830
1831                                 xtables_option_mpcall(c, argv,
1832                                                         invert, xt_m_t, NULL);
1833
1834                                 break;
1835                         }
1836 #else
1837                         if (xt_t == NULL || xt_t->parse == NULL ||
1838                                 !xt_t->parse(c - xt_t->option_offset,
1839                                 argv, invert, &xt_t->tflags, NULL, &xt_t->t)) {
1840
1841                                 for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
1842                                                 tmp_xt_rm = tmp_xt_rm->next) {
1843                                         xt_m_t = tmp_xt_rm->match;
1844
1845                                         if (tmp_xt_rm->completed ||
1846                                                         xt_m_t->parse == NULL)
1847                                                 continue;
1848
1849                                         if (xt_m->parse(c - xt_m->option_offset,
1850                                                 argv, invert, &xt_m->mflags,
1851                                                 NULL, &xt_m->m))
1852                                                 break;
1853                                 }
1854                         }
1855 #endif
1856                         break;
1857                 }
1858
1859                 invert = FALSE;
1860         }
1861
1862 #if XTABLES_VERSION_CODE > 5
1863         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
1864                                 tmp_xt_rm = tmp_xt_rm->next)
1865                 xtables_option_mfcall(tmp_xt_rm->match);
1866
1867         if (xt_t != NULL)
1868                 xtables_option_tfcall(xt_t);
1869 #else
1870         for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
1871                                 tmp_xt_rm = tmp_xt_rm->next)
1872                 if (tmp_xt_rm->match->final_check != NULL)
1873                         tmp_xt_rm->match->final_check(
1874                                         tmp_xt_rm->match->mflags);
1875
1876         if (xt_t != NULL && xt_t->final_check != NULL)
1877                 xt_t->final_check(xt_t->tflags);
1878 #endif
1879
1880         table = pre_load_table(table_name, table);
1881         if (table == NULL)
1882                 goto out;
1883
1884         /* Option parsing went fine, falling back to succes code */
1885         ret = 0;
1886
1887         if (delete_chain != NULL) {
1888                 printf("Delete chain %s\n", delete_chain);
1889
1890                 iptables_delete_chain(table, delete_chain);
1891
1892                 goto out;
1893         }
1894
1895         if (dump) {
1896                 iptables_dump(table);
1897
1898                 goto out;
1899         }
1900
1901         if (flush_chain) {
1902                 DBG("Flush chain %s", flush_chain);
1903
1904                 iptables_flush_chain(table, flush_chain);
1905
1906                 goto out;
1907         }
1908
1909         if (chain && new_chain) {
1910                 ret = -EINVAL;
1911                 goto out;
1912         }
1913
1914         if (new_chain) {
1915                 DBG("New chain %s", new_chain);
1916
1917                 ret = iptables_add_chain(table, new_chain);
1918                 goto out;
1919         }
1920
1921         if (chain) {
1922                 if (policy != NULL) {
1923                         printf("Changing policy of %s to %s\n", chain, policy);
1924
1925                         iptables_change_policy(table, chain, policy);
1926
1927                         goto out;
1928                 }
1929
1930                 if (xt_t == NULL)
1931                         goto out;
1932
1933                 if (compare == TRUE) {
1934                         ret = iptables_compare_rule(table, &ip, chain,
1935                                         target_name, xt_t, xt_m, xt_rm);
1936                         goto out;
1937                 }
1938
1939                 if (delete == TRUE) {
1940                         DBG("Deleting %s to %s (match %s)\n",
1941                                         target_name, chain, match_name);
1942
1943                         ret = iptables_delete_rule(table, &ip, chain,
1944                                         target_name, xt_t, xt_m, xt_rm);
1945
1946                         goto out;
1947                 }
1948
1949                 if (insert == TRUE) {
1950                         DBG("Inserting %s to %s (match %s)",
1951                                         target_name, chain, match_name);
1952
1953                         ret = iptables_insert_rule(table, &ip, chain,
1954                                                 target_name, xt_t, xt_rm);
1955
1956                         goto out;
1957                 } else {
1958                         DBG("Adding %s to %s (match %s)",
1959                                         target_name, chain, match_name);
1960
1961                         ret = iptables_append_rule(table, &ip, chain,
1962                                                 target_name, xt_t, xt_rm);
1963
1964                         goto out;
1965                 }
1966         }
1967
1968 out:
1969         if (xt_t)
1970                 g_free(xt_t->t);
1971
1972         if (xt_m)
1973                 g_free(xt_m->m);
1974
1975         return ret;
1976 }
1977
1978 int __connman_iptables_command(const char *format, ...)
1979 {
1980         char **argv, **arguments, *command;
1981         int argc, i, ret;
1982         va_list args;
1983
1984         if (format == NULL)
1985                 return -EINVAL;
1986
1987         va_start(args, format);
1988
1989         command = g_strdup_vprintf(format, args);
1990
1991         va_end(args);
1992
1993         if (command == NULL)
1994                 return -ENOMEM;
1995
1996         arguments = g_strsplit_set(command, " ", -1);
1997
1998         for (argc = 0; arguments[argc]; argc++);
1999         ++argc;
2000
2001         DBG("command %s argc %d", command, argc);
2002
2003         argv = g_try_malloc0(argc * sizeof(char *));
2004         if (argv == NULL) {
2005                 g_free(command);
2006                 g_strfreev(arguments);
2007                 return -ENOMEM;
2008         }
2009
2010         argv[0] = "iptables";
2011         for (i = 1; i < argc; i++)
2012                 argv[i] = arguments[i - 1];
2013
2014         ret = iptables_command(argc, argv);
2015
2016         g_free(command);
2017         g_strfreev(arguments);
2018         g_free(argv);
2019
2020         return ret;
2021 }
2022
2023
2024 int __connman_iptables_commit(const char *table_name)
2025 {
2026         struct connman_iptables *table;
2027         struct ipt_replace *repl;
2028         int err;
2029
2030         DBG("%s", table_name);
2031
2032         table = g_hash_table_lookup(table_hash, table_name);
2033         if (table == NULL)
2034                 return -EINVAL;
2035
2036         repl = iptables_blob(table);
2037
2038         err = iptables_replace(table, repl);
2039
2040         g_free(repl->counters);
2041         g_free(repl);
2042
2043         if (err < 0)
2044             return err;
2045
2046         g_hash_table_remove(table_hash, table_name);
2047
2048         return 0;
2049 }
2050
2051 static void remove_table(gpointer user_data)
2052 {
2053         struct connman_iptables *table = user_data;
2054
2055         table_cleanup(table);
2056 }
2057
2058 int __connman_iptables_init(void)
2059 {
2060         DBG("");
2061
2062         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
2063                                                 g_free, remove_table);
2064
2065         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
2066
2067         return 0;
2068
2069 }
2070
2071 void __connman_iptables_cleanup(void)
2072 {
2073         DBG("");
2074
2075         g_hash_table_destroy(table_hash);
2076
2077         xtables_free_opts(1);
2078 }