redirects: fix segmentation fault
[oweals/firewall3.git] / iptables.c
1 /*
2  * firewall3 - 3rd OpenWrt UCI firewall implementation
3  *
4  *   Copyright (C) 2013 Jo-Philipp Wich <jo@mein.io>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #define _GNU_SOURCE /* RTLD_NEXT */
20
21 /* include userspace headers */
22 #include <dlfcn.h>
23 #include <unistd.h>
24 #include <getopt.h>
25 #include <net/if.h>
26 #include <netinet/in.h>
27 #include <sys/utsname.h>
28 #include <sys/socket.h>
29
30 /* prevent indirect inclusion of kernel headers */
31 #define _LINUX_IF_H
32 #define _LINUX_IN_H
33 #define _LINUX_IN6_H
34
35 /* prevent libiptc from including kernel headers */
36 #define _FWCHAINS_KERNEL_HEADERS_H
37
38 /* finally include libiptc and xtables */
39 #include <libiptc/libiptc.h>
40 #include <libiptc/libip6tc.h>
41 #include <xtables.h>
42
43 #include <setjmp.h>
44
45 #include "options.h"
46
47 /* xtables interface */
48 #if (XTABLES_VERSION_CODE >= 10)
49 # include "xtables-10.h"
50 #elif (XTABLES_VERSION_CODE == 5)
51 # include "xtables-5.h"
52 #else
53 # error "Unsupported xtables version"
54 #endif
55
56 #include "iptables.h"
57
58 #define XT_LOCK_NAME "/var/run/xtables.lock"
59 static int xt_lock_fd = -1;
60
61 struct fw3_ipt_rule {
62         struct fw3_ipt_handle *h;
63
64         union {
65                 struct ipt_entry e;
66                 struct ip6t_entry e6;
67         };
68
69         struct xtables_rule_match *matches;
70         struct xtables_target *target;
71
72         int argc;
73         char **argv;
74
75         uint32_t protocol;
76         bool protocol_loaded;
77 };
78
79 static struct option base_opts[] = {
80         { .name = "match",         .has_arg = 1, .val = 'm' },
81         { .name = "jump",          .has_arg = 1, .val = 'j' },
82         { .name = "in-interface",  .has_arg = 1, .val = 'i' },
83         { .name = "out-interface", .has_arg = 1, .val = 'o' },
84         { .name = "source",        .has_arg = 1, .val = 's' },
85         { .name = "destination",   .has_arg = 1, .val = 'd' },
86         { NULL }
87 };
88
89
90 static jmp_buf fw3_ipt_error_jmp;
91
92 static __attribute__((noreturn))
93 void fw3_ipt_error_handler(enum xtables_exittype status,
94                            const char *fmt, ...)
95 {
96         va_list args;
97
98         fprintf(stderr, "     ! Exception: ");
99
100         va_start(args, fmt);
101         vfprintf(stderr, fmt, args);
102         va_end(args);
103
104         longjmp(fw3_ipt_error_jmp, status);
105 }
106
107 static struct xtables_globals xtg = {
108         .option_offset = 0,
109         .program_version = "4",
110         .orig_opts = base_opts,
111         .exit_err = fw3_ipt_error_handler,
112 #if XTABLES_VERSION_CODE > 10
113         .compat_rev = xtables_compatible_revision,
114 #endif
115 };
116
117 static struct xtables_globals xtg6 = {
118         .option_offset = 0,
119         .program_version = "6",
120         .orig_opts = base_opts,
121         .exit_err = fw3_ipt_error_handler,
122 #if XTABLES_VERSION_CODE > 10
123         .compat_rev = xtables_compatible_revision,
124 #endif
125 };
126
127 static struct {
128         bool retain;
129         int mcount, tcount;
130         struct xtables_match **matches;
131         struct xtables_target **targets;
132         void (*register_match)(struct xtables_match *);
133         void (*register_target)(struct xtables_target *);
134 } xext;
135
136
137 /* Required by certain extensions like SNAT and DNAT */
138 int kernel_version = 0;
139
140 void
141 get_kernel_version(void)
142 {
143         static struct utsname uts;
144         int x = 3, y = 0, z = 0;
145
146         if (uname(&uts) != -1)
147                 sscanf(uts.release, "%d.%d.%d", &x, &y, &z);
148
149         kernel_version = 0x10000 * x + 0x100 * y + z;
150 }
151
152 static void fw3_init_extensions(void)
153 {
154         init_extensions();
155         init_extensions4();
156
157 #ifndef DISABLE_IPV6
158         init_extensions6();
159 #endif
160 }
161
162 struct fw3_ipt_handle *
163 fw3_ipt_open(enum fw3_family family, enum fw3_table table)
164 {
165         int i;
166         struct fw3_ipt_handle *h;
167
168         h = fw3_alloc(sizeof(*h));
169
170         xtables_init();
171
172         while (!fw3_lock_path(&xt_lock_fd, XT_LOCK_NAME)) {
173                 warn("Currently busy xtables.lock - wait 1 second");
174                 sleep(1);
175         }
176
177         if (family == FW3_FAMILY_V6)
178         {
179 #ifndef DISABLE_IPV6
180                 h->family = FW3_FAMILY_V6;
181                 h->table  = table;
182                 h->handle = ip6tc_init(fw3_flag_names[table]);
183
184                 xtables_set_params(&xtg6);
185                 xtables_set_nfproto(NFPROTO_IPV6);
186 #endif
187         }
188         else
189         {
190                 h->family = FW3_FAMILY_V4;
191                 h->table  = table;
192                 h->handle = iptc_init(fw3_flag_names[table]);
193
194                 xtables_set_params(&xtg);
195                 xtables_set_nfproto(NFPROTO_IPV4);
196         }
197
198         if (!h->handle)
199         {
200                 free(h);
201                 fw3_unlock_path(&xt_lock_fd, XT_LOCK_NAME);
202                 return NULL;
203         }
204
205         fw3_xt_reset();
206         fw3_init_extensions();
207
208         if (xext.register_match)
209                 for (i = 0; i < xext.mcount; i++)
210                         xext.register_match(xext.matches[i]);
211
212         if (xext.register_target)
213                 for (i = 0; i < xext.tcount; i++)
214                         xext.register_target(xext.targets[i]);
215
216         return h;
217 }
218
219 static void
220 debug(struct fw3_ipt_handle *h, const char *fmt, ...)
221 {
222         va_list ap;
223
224         printf("%s -t %s ", (h->family == FW3_FAMILY_V6) ? "ip6tables" : "iptables",
225                             fw3_flag_names[h->table]);
226
227         va_start(ap, fmt);
228         vprintf(fmt, ap);
229         va_end(ap);
230 }
231
232 void
233 fw3_ipt_set_policy(struct fw3_ipt_handle *h, const char *chain,
234                    enum fw3_flag policy)
235 {
236         if (fw3_pr_debug)
237                 debug(h, "-P %s %s\n", chain, fw3_flag_names[policy]);
238
239 #ifndef DISABLE_IPV6
240         if (h->family == FW3_FAMILY_V6)
241                 ip6tc_set_policy(chain, fw3_flag_names[policy], NULL, h->handle);
242         else
243 #endif
244                 iptc_set_policy(chain, fw3_flag_names[policy], NULL, h->handle);
245 }
246
247 void
248 fw3_ipt_flush_chain(struct fw3_ipt_handle *h, const char *chain)
249 {
250         if (fw3_pr_debug)
251                 debug(h, "-F %s\n", chain);
252
253 #ifndef DISABLE_IPV6
254         if (h->family == FW3_FAMILY_V6)
255                 ip6tc_flush_entries(chain, h->handle);
256         else
257 #endif
258                 iptc_flush_entries(chain, h->handle);
259 }
260
261 static void
262 delete_rules(struct fw3_ipt_handle *h, const char *target)
263 {
264         unsigned int num;
265         const struct ipt_entry *e;
266         const char *chain;
267         const char *t;
268         bool found;
269
270 #ifndef DISABLE_IPV6
271         if (h->family == FW3_FAMILY_V6)
272         {
273                 for (chain = ip6tc_first_chain(h->handle);
274                      chain != NULL;
275                      chain = ip6tc_next_chain(h->handle))
276                 {
277                         do {
278                                 found = false;
279
280                                 const struct ip6t_entry *e6;
281                                 for (num = 0, e6 = ip6tc_first_rule(chain, h->handle);
282                                          e6 != NULL;
283                                          num++, e6 = ip6tc_next_rule(e6, h->handle))
284                                 {
285                                         t = ip6tc_get_target(e6, h->handle);
286
287                                         if (*t && !strcmp(t, target))
288                                         {
289                                                 if (fw3_pr_debug)
290                                                         debug(h, "-D %s %u\n", chain, num + 1);
291
292                                                 ip6tc_delete_num_entry(chain, num, h->handle);
293                                                 found = true;
294                                                 break;
295                                         }
296                                 }
297                         } while (found);
298                 }
299         }
300         else
301 #endif
302         {
303                 for (chain = iptc_first_chain(h->handle);
304                      chain != NULL;
305                      chain = iptc_next_chain(h->handle))
306                 {
307                         do {
308                                 found = false;
309
310                                 for (num = 0, e = iptc_first_rule(chain, h->handle);
311                                      e != NULL;
312                                          num++, e = iptc_next_rule(e, h->handle))
313                                 {
314                                         t = iptc_get_target(e, h->handle);
315
316                                         if (*t && !strcmp(t, target))
317                                         {
318                                                 if (fw3_pr_debug)
319                                                         debug(h, "-D %s %u\n", chain, num + 1);
320
321                                                 iptc_delete_num_entry(chain, num, h->handle);
322                                                 found = true;
323                                                 break;
324                                         }
325                                 }
326                         } while (found);
327                 }
328         }
329 }
330
331 static bool
332 is_referenced(struct fw3_ipt_handle *h, const char *target)
333 {
334         const struct ipt_entry *e;
335         const char *chain;
336         const char *t;
337
338 #ifndef DISABLE_IPV6
339         if (h->family == FW3_FAMILY_V6)
340         {
341                 for (chain = ip6tc_first_chain(h->handle);
342                      chain != NULL;
343                      chain = ip6tc_next_chain(h->handle))
344                 {
345                         const struct ip6t_entry *e6;
346                         for (e6 = ip6tc_first_rule(chain, h->handle);
347                              e6 != NULL;
348                              e6 = ip6tc_next_rule(e6, h->handle))
349                         {
350                                 t = ip6tc_get_target(e6, h->handle);
351
352                                 if (*t && !strcmp(t, target))
353                                         return true;
354                         }
355                 }
356         }
357         else
358 #endif
359         {
360                 for (chain = iptc_first_chain(h->handle);
361                      chain != NULL;
362                      chain = iptc_next_chain(h->handle))
363                 {
364                         for (e = iptc_first_rule(chain, h->handle);
365                              e != NULL;
366                              e = iptc_next_rule(e, h->handle))
367                         {
368                                 t = iptc_get_target(e, h->handle);
369
370                                 if (*t && !strcmp(t, target))
371                                         return true;
372                         }
373                 }
374         }
375
376         return false;
377 }
378
379 void
380 fw3_ipt_delete_chain(struct fw3_ipt_handle *h, bool if_unused,
381                      const char *chain)
382 {
383         if (if_unused && is_referenced(h, chain))
384                 return;
385
386         delete_rules(h, chain);
387
388         if (fw3_pr_debug)
389                 debug(h, "-X %s\n", chain);
390
391 #ifndef DISABLE_IPV6
392         if (h->family == FW3_FAMILY_V6)
393                 ip6tc_delete_chain(chain, h->handle);
394         else
395 #endif
396                 iptc_delete_chain(chain, h->handle);
397 }
398
399 static bool
400 has_rule_tag(const void *base, unsigned int start, unsigned int end)
401 {
402         unsigned int i;
403         const struct xt_entry_match *em;
404
405         for (i = start; i < end; i += em->u.match_size)
406         {
407                 em = base + i;
408
409                 if (strcmp(em->u.user.name, "comment"))
410                         continue;
411
412                 if (!memcmp(em->data, "!fw3", 4))
413                         return true;
414         }
415
416         return false;
417 }
418
419 void
420 fw3_ipt_delete_id_rules(struct fw3_ipt_handle *h, const char *chain)
421 {
422         unsigned int num;
423         const struct ipt_entry *e;
424         bool found;
425
426 #ifndef DISABLE_IPV6
427         if (h->family == FW3_FAMILY_V6)
428         {
429                 if (!ip6tc_is_chain(chain, h->handle))
430                         return;
431
432                 do {
433                         found = false;
434
435                         const struct ip6t_entry *e6;
436                         for (num = 0, e6 = ip6tc_first_rule(chain, h->handle);
437                                  e6 != NULL;
438                                  num++, e6 = ip6tc_next_rule(e6, h->handle))
439                         {
440                                 if (has_rule_tag(e6, sizeof(*e6), e6->target_offset))
441                                 {
442                                         if (fw3_pr_debug)
443                                                 debug(h, "-D %s %u\n", chain, num + 1);
444
445                                         ip6tc_delete_num_entry(chain, num, h->handle);
446                                         found = true;
447                                         break;
448                                 }
449                         }
450                 } while (found);
451         }
452         else
453 #endif
454         {
455                 if (!iptc_is_chain(chain, h->handle))
456                         return;
457
458                 do {
459                         found = false;
460
461                         for (num = 0, e = iptc_first_rule(chain, h->handle);
462                                  e != NULL;
463                                  num++, e = iptc_next_rule(e, h->handle))
464                         {
465                                 if (has_rule_tag(e, sizeof(*e), e->target_offset))
466                                 {
467                                         if (fw3_pr_debug)
468                                                 debug(h, "-D %s %u\n", chain, num + 1);
469
470                                         iptc_delete_num_entry(chain, num, h->handle);
471                                         found = true;
472                                         break;
473                                 }
474                         }
475                 } while (found);
476         }
477 }
478
479
480 static bool
481 is_chain(struct fw3_ipt_handle *h, const char *name)
482 {
483 #ifndef DISABLE_IPV6
484         if (h->family == FW3_FAMILY_V6)
485                 return ip6tc_is_chain(name, h->handle);
486         else
487 #endif
488                 return iptc_is_chain(name, h->handle);
489 }
490
491 void
492 fw3_ipt_create_chain(struct fw3_ipt_handle *h, bool ignore_existing,
493                      const char *chain)
494 {
495         if (ignore_existing && is_chain(h, chain))
496                 return;
497
498         if (fw3_pr_debug)
499                 debug(h, "-N %s\n", chain);
500
501         iptc_create_chain(chain, h->handle);
502 }
503
504 void
505 fw3_ipt_flush(struct fw3_ipt_handle *h)
506 {
507         const char *chain;
508
509 #ifndef DISABLE_IPV6
510         if (h->family == FW3_FAMILY_V6)
511         {
512                 for (chain = ip6tc_first_chain(h->handle);
513                      chain != NULL;
514                      chain = ip6tc_next_chain(h->handle))
515                 {
516                         ip6tc_flush_entries(chain, h->handle);
517                 }
518
519                 for (chain = ip6tc_first_chain(h->handle);
520                      chain != NULL;
521                      chain = ip6tc_next_chain(h->handle))
522                 {
523                         ip6tc_delete_chain(chain, h->handle);
524                 }
525         }
526         else
527 #endif
528         {
529                 for (chain = iptc_first_chain(h->handle);
530                      chain != NULL;
531                      chain = iptc_next_chain(h->handle))
532                 {
533                         iptc_flush_entries(chain, h->handle);
534                 }
535
536                 for (chain = iptc_first_chain(h->handle);
537                      chain != NULL;
538                      chain = iptc_next_chain(h->handle))
539                 {
540                         iptc_delete_chain(chain, h->handle);
541                 }
542         }
543 }
544
545 static bool
546 chain_is_empty(struct fw3_ipt_handle *h, const char *chain)
547 {
548 #ifndef DISABLE_IPV6
549         if (h->family == FW3_FAMILY_V6)
550                 return (!ip6tc_builtin(chain, h->handle) &&
551                         !ip6tc_first_rule(chain, h->handle));
552 #endif
553
554         return (!iptc_builtin(chain, h->handle) &&
555                 !iptc_first_rule(chain, h->handle));
556 }
557
558 void
559 fw3_ipt_gc(struct fw3_ipt_handle *h)
560 {
561         const char *chain;
562         bool found;
563
564 #ifndef DISABLE_IPV6
565         if (h->family == FW3_FAMILY_V6)
566         {
567                 do {
568                         found = false;
569
570                         for (chain = ip6tc_first_chain(h->handle);
571                                  chain != NULL;
572                                  chain = ip6tc_next_chain(h->handle))
573                         {
574                                 if (!chain_is_empty(h, chain))
575                                         continue;
576
577                                 fw3_ipt_delete_chain(h, false, chain);
578                                 found = true;
579                                 break;
580                         }
581                 } while(found);
582         }
583         else
584 #endif
585         {
586                 do {
587                         found = false;
588
589                         for (chain = iptc_first_chain(h->handle);
590                                  chain != NULL;
591                                  chain = iptc_next_chain(h->handle))
592                         {
593                                 warn("C=%s\n", chain);
594
595                                 if (!chain_is_empty(h, chain))
596                                         continue;
597
598                                 warn("D=%s\n", chain);
599
600                                 fw3_ipt_delete_chain(h, false, chain);
601                                 found = true;
602                                 break;
603                         }
604                 } while (found);
605         }
606 }
607
608 void
609 fw3_ipt_commit(struct fw3_ipt_handle *h)
610 {
611         int rv;
612
613 #ifndef DISABLE_IPV6
614         if (h->family == FW3_FAMILY_V6)
615         {
616                 rv = ip6tc_commit(h->handle);
617                 if (!rv)
618                         warn("ip6tc_commit(): %s", ip6tc_strerror(errno));
619         }
620         else
621 #endif
622         {
623                 rv = iptc_commit(h->handle);
624                 if (!rv)
625                         warn("iptc_commit(): %s", iptc_strerror(errno));
626         }
627 }
628
629 void
630 fw3_ipt_close(struct fw3_ipt_handle *h)
631 {
632         fw3_unlock_path(&xt_lock_fd, XT_LOCK_NAME);
633         free(h);
634 }
635
636 struct fw3_ipt_rule *
637 fw3_ipt_rule_new(struct fw3_ipt_handle *h)
638 {
639         struct fw3_ipt_rule *r;
640
641         r = fw3_alloc(sizeof(*r));
642
643         r->h = h;
644         r->argv = fw3_alloc(sizeof(char *));
645         r->argv[r->argc++] = "fw3";
646
647         return r;
648 }
649
650
651 static char *
652 get_protoname(struct fw3_ipt_rule *r)
653 {
654         const struct xtables_pprot *pp;
655
656         if (r->protocol)
657                 for (pp = xtables_chain_protos; pp->name; pp++)
658                         if (pp->num == r->protocol)
659                                 return (char *)pp->name;
660
661         return NULL;
662 }
663
664 static struct xtables_match *
665 find_match(struct fw3_ipt_rule *r, const char *name)
666 {
667         struct xtables_match *m;
668
669         xext.retain = true;
670         m = xtables_find_match(name, XTF_TRY_LOAD, &r->matches);
671         xext.retain = false;
672
673         return m;
674 }
675
676 static void
677 init_match(struct fw3_ipt_rule *r, struct xtables_match *m, bool no_clone)
678 {
679         size_t s;
680         struct xtables_globals *g;
681
682         if (!m)
683                 return;
684
685         s = XT_ALIGN(sizeof(struct xt_entry_match)) + m->size;
686
687         m->m = fw3_alloc(s);
688
689         fw3_xt_set_match_name(m);
690
691         m->m->u.user.revision = m->revision;
692         m->m->u.match_size = s;
693
694         /* free previous userspace data */
695         fw3_xt_free_match_udata(m);
696
697         if (m->init)
698                 m->init(m->m);
699
700         /* don't merge options if no_clone is set and this match is a clone */
701         if (no_clone && (m == m->next))
702                 return;
703
704         /* merge option table */
705         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
706         fw3_xt_merge_match_options(g, m);
707 }
708
709 static bool
710 need_protomatch(struct fw3_ipt_rule *r, const char *pname)
711 {
712         if (!pname)
713                 return false;
714
715         if (!xtables_find_match(pname, XTF_DONT_LOAD, NULL))
716                 return true;
717
718         return !r->protocol_loaded;
719 }
720
721 static struct xtables_match *
722 load_protomatch(struct fw3_ipt_rule *r)
723 {
724         const char *pname = get_protoname(r);
725
726         if (!need_protomatch(r, pname))
727                 return NULL;
728
729         return find_match(r, pname);
730 }
731
732 static struct xtables_target *
733 find_target(struct fw3_ipt_rule *r, const char *name)
734 {
735         struct xtables_target *t;
736
737         xext.retain = true;
738
739         if (is_chain(r->h, name))
740                 t = xtables_find_target(XT_STANDARD_TARGET, XTF_TRY_LOAD);
741         else
742                 t = xtables_find_target(name, XTF_TRY_LOAD);
743
744         xext.retain = false;
745
746         return t;
747 }
748
749 static struct xtables_target *
750 get_target(struct fw3_ipt_rule *r, const char *name)
751 {
752         size_t s;
753         struct xtables_target *t;
754         struct xtables_globals *g;
755
756         t = find_target(r, name);
757
758         if (!t)
759                 return NULL;
760
761         s = XT_ALIGN(sizeof(struct xt_entry_target)) + t->size;
762         t->t = fw3_alloc(s);
763
764         fw3_xt_set_target_name(t, name);
765
766         t->t->u.user.revision = t->revision;
767         t->t->u.target_size = s;
768
769         /* free previous userspace data */
770         fw3_xt_free_target_udata(t);
771
772         if (t->init)
773                 t->init(t->t);
774
775         /* merge option table */
776         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
777         fw3_xt_merge_target_options(g, t);
778
779         r->target = t;
780
781         return t;
782 }
783
784 void
785 fw3_ipt_rule_proto(struct fw3_ipt_rule *r, struct fw3_protocol *proto)
786 {
787         uint32_t pr;
788
789         if (!proto || proto->any)
790                 return;
791
792         pr = proto->protocol;
793
794 #ifndef DISABLE_IPV6
795         if (r->h->family == FW3_FAMILY_V6)
796         {
797                 if (pr == 1)
798                         pr = 58;
799
800                 r->e6.ipv6.proto = pr;
801                 r->e6.ipv6.flags |= IP6T_F_PROTO;
802
803                 if (proto->invert)
804                         r->e6.ipv6.invflags |= XT_INV_PROTO;
805         }
806         else
807 #endif
808         {
809                 r->e.ip.proto = pr;
810
811                 if (proto->invert)
812                         r->e.ip.invflags |= XT_INV_PROTO;
813         }
814
815         r->protocol = pr;
816 }
817
818 void
819 fw3_ipt_rule_in_out(struct fw3_ipt_rule *r,
820                     struct fw3_device *in, struct fw3_device *out)
821 {
822 #ifndef DISABLE_IPV6
823         if (r->h->family == FW3_FAMILY_V6)
824         {
825                 if (in && !in->any)
826                 {
827                         xtables_parse_interface(in->name, r->e6.ipv6.iniface,
828                                                           r->e6.ipv6.iniface_mask);
829
830                         if (in->invert)
831                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_IN;
832                 }
833
834                 if (out && !out->any)
835                 {
836                         xtables_parse_interface(out->name, r->e6.ipv6.outiface,
837                                                            r->e6.ipv6.outiface_mask);
838
839                         if (out->invert)
840                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_OUT;
841                 }
842         }
843         else
844 #endif
845         {
846                 if (in && !in->any)
847                 {
848                         xtables_parse_interface(in->name, r->e.ip.iniface,
849                                                           r->e.ip.iniface_mask);
850
851                         if (in->invert)
852                                 r->e.ip.invflags |= IPT_INV_VIA_IN;
853                 }
854
855                 if (out && !out->any)
856                 {
857                         xtables_parse_interface(out->name, r->e.ip.outiface,
858                                                            r->e.ip.outiface_mask);
859
860                         if (out->invert)
861                                 r->e.ip.invflags |= IPT_INV_VIA_OUT;
862                 }
863         }
864 }
865
866
867 void
868 fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
869                       struct fw3_address *src, struct fw3_address *dest)
870 {
871         if ((src && src->range) || (dest && dest->range))
872         {
873                 fw3_ipt_rule_addarg(r, false, "-m", "iprange");
874         }
875
876         if (src && src->set)
877         {
878                 if (src->range)
879                 {
880                         fw3_ipt_rule_addarg(r, src->invert, "--src-range",
881                                             fw3_address_to_string(src, false, false));
882                 }
883 #ifndef DISABLE_IPV6
884                 else if (r->h->family == FW3_FAMILY_V6)
885                 {
886                         r->e6.ipv6.src = src->address.v6;
887                         r->e6.ipv6.smsk = src->mask.v6;
888
889                         int i;
890                         for (i = 0; i < 4; i++)
891                                 r->e6.ipv6.src.s6_addr32[i] &= r->e6.ipv6.smsk.s6_addr32[i];
892
893                         if (src->invert)
894                                 r->e6.ipv6.invflags |= IP6T_INV_SRCIP;
895                 }
896 #endif
897                 else
898                 {
899                         r->e.ip.src = src->address.v4;
900                         r->e.ip.smsk = src->mask.v4;
901
902                         r->e.ip.src.s_addr &= r->e.ip.smsk.s_addr;
903
904                         if (src->invert)
905                                 r->e.ip.invflags |= IPT_INV_SRCIP;
906                 }
907         }
908
909         if (dest && dest->set)
910         {
911                 if (dest->range)
912                 {
913                         fw3_ipt_rule_addarg(r, dest->invert, "--dst-range",
914                                             fw3_address_to_string(dest, false, false));
915                 }
916 #ifndef DISABLE_IPV6
917                 else if (r->h->family == FW3_FAMILY_V6)
918                 {
919                         r->e6.ipv6.dst = dest->address.v6;
920                         r->e6.ipv6.dmsk = dest->mask.v6;
921
922                         int i;
923                         for (i = 0; i < 4; i++)
924                                 r->e6.ipv6.dst.s6_addr32[i] &= r->e6.ipv6.dmsk.s6_addr32[i];
925
926                         if (dest->invert)
927                                 r->e6.ipv6.invflags |= IP6T_INV_DSTIP;
928                 }
929 #endif
930                 else
931                 {
932                         r->e.ip.dst = dest->address.v4;
933                         r->e.ip.dmsk = dest->mask.v4;
934
935                         r->e.ip.dst.s_addr &= r->e.ip.dmsk.s_addr;
936
937                         if (dest->invert)
938                                 r->e.ip.invflags |= IPT_INV_DSTIP;
939                 }
940         }
941 }
942
943 void
944 fw3_ipt_rule_sport_dport(struct fw3_ipt_rule *r,
945                          struct fw3_port *sp, struct fw3_port *dp)
946 {
947         char buf[sizeof("65535:65535")];
948
949         if ((!sp || !sp->set) && (!dp || !dp->set))
950                 return;
951
952         if (!get_protoname(r))
953                 return;
954
955         if (sp && sp->set)
956         {
957                 if (sp->port_min == sp->port_max)
958                         snprintf(buf, sizeof(buf), "%u", sp->port_min);
959                 else
960                         snprintf(buf, sizeof(buf), "%u:%u", sp->port_min, sp->port_max);
961
962                 fw3_ipt_rule_addarg(r, sp->invert, "--sport", buf);
963         }
964
965         if (dp && dp->set)
966         {
967                 if (dp->port_min == dp->port_max)
968                         snprintf(buf, sizeof(buf), "%u", dp->port_min);
969                 else
970                         snprintf(buf, sizeof(buf), "%u:%u", dp->port_min, dp->port_max);
971
972                 fw3_ipt_rule_addarg(r, dp->invert, "--dport", buf);
973         }
974 }
975
976 void
977 fw3_ipt_rule_device(struct fw3_ipt_rule *r, const char *device, bool out)
978 {
979         struct fw3_device dev = { .any = false };
980
981         if (device) {
982                 snprintf(dev.name, sizeof(dev.name), "%s", device);
983                 fw3_ipt_rule_in_out(r, (out) ? NULL : &dev, (out) ? &dev : NULL);
984         }
985 }
986
987 void
988 fw3_ipt_rule_mac(struct fw3_ipt_rule *r, struct fw3_mac *mac)
989 {
990         char buf[sizeof("ff:ff:ff:ff:ff:ff")];
991         uint8_t *addr = mac->mac.ether_addr_octet;
992
993         if (!mac)
994                 return;
995
996         snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
997                  addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
998
999         fw3_ipt_rule_addarg(r, false, "-m", "mac");
1000         fw3_ipt_rule_addarg(r, mac->invert, "--mac-source", buf);
1001 }
1002
1003 void
1004 fw3_ipt_rule_icmptype(struct fw3_ipt_rule *r, struct fw3_icmptype *icmp)
1005 {
1006         char buf[sizeof("255/255")];
1007
1008         if (!icmp)
1009                 return;
1010
1011 #ifndef DISABLE_IPV6
1012         if (r->h->family == FW3_FAMILY_V6)
1013         {
1014                 if (icmp->code6_min == 0 && icmp->code6_max == 0xFF)
1015                         snprintf(buf, sizeof(buf), "%u", icmp->type6);
1016                 else
1017                         snprintf(buf, sizeof(buf), "%u/%u", icmp->type6, icmp->code6_min);
1018
1019                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmpv6-type", buf);
1020         }
1021         else
1022 #endif
1023         {
1024                 if (icmp->code_min == 0 && icmp->code_max == 0xFF)
1025                         sprintf(buf, "%u", icmp->type);
1026                 else
1027                         snprintf(buf, sizeof(buf), "%u/%u", icmp->type, icmp->code_min);
1028
1029                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmp-type", buf);
1030         }
1031 }
1032
1033 void
1034 fw3_ipt_rule_limit(struct fw3_ipt_rule *r, struct fw3_limit *limit)
1035 {
1036         char buf[sizeof("-4294967296/second")];
1037
1038         if (!limit || limit->rate <= 0)
1039                 return;
1040
1041         fw3_ipt_rule_addarg(r, false, "-m", "limit");
1042
1043         snprintf(buf, sizeof(buf), "%u/%s", limit->rate, fw3_limit_units[limit->unit]);
1044         fw3_ipt_rule_addarg(r, limit->invert, "--limit", buf);
1045
1046         if (limit->burst > 0)
1047         {
1048                 snprintf(buf, sizeof(buf), "%u", limit->burst);
1049                 fw3_ipt_rule_addarg(r, limit->invert, "--limit-burst", buf);
1050         }
1051 }
1052
1053 void
1054 fw3_ipt_rule_ipset(struct fw3_ipt_rule *r, struct fw3_setmatch *match)
1055 {
1056         char buf[sizeof("dst,dst,dst")];
1057         char *p = buf;
1058         int i = 0, len;
1059         size_t rem = sizeof(buf);
1060
1061         struct fw3_ipset *set;
1062         struct fw3_ipset_datatype *type;
1063
1064         if (!match || !match->set || !match->ptr)
1065                 return;
1066
1067         set = match->ptr;
1068         list_for_each_entry(type, &set->datatypes, list)
1069         {
1070                 if (i >= 3)
1071                         break;
1072
1073                 if (p > buf) {
1074                         if (rem <= 1)
1075                                 break;
1076
1077                         *p++ = ',';
1078                         *p = 0;
1079                         rem--;
1080                 }
1081
1082                 len = snprintf(p, rem, "%s", match->dir[i] ? match->dir[i] : type->dir);
1083
1084                 if (len < 0 || len >= rem)
1085                         break;
1086
1087                 rem -= len;
1088                 p += len;
1089
1090                 i++;
1091         }
1092
1093         fw3_ipt_rule_addarg(r, false, "-m", "set");
1094
1095         fw3_ipt_rule_addarg(r, match->invert, "--match-set",
1096                             set->external ? set->external : set->name);
1097
1098         fw3_ipt_rule_addarg(r, false, buf, NULL);
1099 }
1100
1101 void
1102 fw3_ipt_rule_helper(struct fw3_ipt_rule *r, struct fw3_cthelpermatch *match)
1103 {
1104         if (!match || !match->set || !match->ptr)
1105                 return;
1106
1107         fw3_ipt_rule_addarg(r, false, "-m", "helper");
1108         fw3_ipt_rule_addarg(r, match->invert, "--helper", match->ptr->name);
1109 }
1110
1111 void
1112 fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
1113 {
1114         int i, len;
1115         struct tm empty = { 0 };
1116
1117         char buf[84]; /* sizeof("1,2,3,...,30,31") */
1118         char *p;
1119
1120         bool d1 = memcmp(&time->datestart, &empty, sizeof(empty));
1121         bool d2 = memcmp(&time->datestop, &empty, sizeof(empty));
1122
1123         size_t rem;
1124
1125         if (!d1 && !d2 && !time->timestart && !time->timestop &&
1126             !(time->monthdays & 0xFFFFFFFE) && !(time->weekdays & 0xFE))
1127         {
1128                 return;
1129         }
1130
1131         fw3_ipt_rule_addarg(r, false, "-m", "time");
1132
1133         if (!time->utc)
1134                 fw3_ipt_rule_addarg(r, false, "--kerneltz", NULL);
1135
1136         if (d1)
1137         {
1138                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestart);
1139                 fw3_ipt_rule_addarg(r, false, "--datestart", buf);
1140         }
1141
1142         if (d2)
1143         {
1144                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestop);
1145                 fw3_ipt_rule_addarg(r, false, "--datestop", buf);
1146         }
1147
1148         if (time->timestart)
1149         {
1150                 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
1151                         time->timestart / 3600,
1152                         time->timestart % 3600 / 60,
1153                         time->timestart % 60);
1154
1155                 fw3_ipt_rule_addarg(r, false, "--timestart", buf);
1156         }
1157
1158         if (time->timestop)
1159         {
1160                 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
1161                         time->timestop / 3600,
1162                         time->timestop % 3600 / 60,
1163                         time->timestop % 60);
1164
1165                 fw3_ipt_rule_addarg(r, false, "--timestop", buf);
1166         }
1167
1168         if (time->monthdays & 0xFFFFFFFE)
1169         {
1170                 for (i = 1, p = buf, rem = sizeof(buf); i < 32; i++)
1171                 {
1172                         if (fw3_hasbit(time->monthdays, i))
1173                         {
1174                                 if (p > buf) {
1175                                         if (rem <= 1)
1176                                                 break;
1177
1178                                         *p++ = ',';
1179                                         *p = 0;
1180                                         rem--;
1181                                 }
1182
1183                                 len = snprintf(p, rem, "%u", i);
1184
1185                                 if (len < 0 || len >= rem)
1186                                         break;
1187
1188                                 rem -= len;
1189                                 p += len;
1190                         }
1191                 }
1192
1193                 fw3_ipt_rule_addarg(r, fw3_hasbit(time->monthdays, 0), "--monthdays", buf);
1194         }
1195
1196         if (time->weekdays & 0xFE)
1197         {
1198                 for (i = 1, p = buf, rem = sizeof(buf); i < 8; i++)
1199                 {
1200                         if (fw3_hasbit(time->weekdays, i))
1201                         {
1202                                 if (p > buf) {
1203                                         if (rem <= 1)
1204                                                 break;
1205
1206                                         *p++ = ',';
1207                                         *p = 0;
1208                                         rem--;
1209                                 }
1210
1211                                 p += snprintf(p, rem, "%u", i);
1212
1213                                 if (len < 0 || len >= rem)
1214                                         break;
1215
1216                                 rem -= len;
1217                                 p += len;
1218                         }
1219                 }
1220
1221                 fw3_ipt_rule_addarg(r, fw3_hasbit(time->weekdays, 0), "--weekdays", buf);
1222         }
1223 }
1224
1225 void
1226 fw3_ipt_rule_mark(struct fw3_ipt_rule *r, struct fw3_mark *mark)
1227 {
1228         char buf[sizeof("0xFFFFFFFF/0xFFFFFFFF")];
1229
1230         if (!mark || !mark->set)
1231                 return;
1232
1233         if (mark->mask < 0xFFFFFFFF)
1234                 snprintf(buf, sizeof(buf), "0x%x/0x%x", mark->mark, mark->mask);
1235         else
1236                 snprintf(buf, sizeof(buf), "0x%x", mark->mark);
1237
1238         fw3_ipt_rule_addarg(r, false, "-m", "mark");
1239         fw3_ipt_rule_addarg(r, mark->invert, "--mark", buf);
1240 }
1241
1242 void
1243 fw3_ipt_rule_dscp(struct fw3_ipt_rule *r, struct fw3_dscp *dscp)
1244 {
1245         char buf[sizeof("0xFF")];
1246
1247         if (!dscp || !dscp->set)
1248                 return;
1249
1250         snprintf(buf, sizeof(buf), "0x%x", dscp->dscp);
1251
1252         fw3_ipt_rule_addarg(r, false, "-m", "dscp");
1253         fw3_ipt_rule_addarg(r, dscp->invert, "--dscp", buf);
1254 }
1255
1256 void
1257 fw3_ipt_rule_comment(struct fw3_ipt_rule *r, const char *fmt, ...)
1258 {
1259         va_list ap;
1260         char buf[256];
1261
1262         if (!fmt || !*fmt)
1263                 return;
1264
1265         va_start(ap, fmt);
1266         vsnprintf(buf, sizeof(buf), fmt, ap);
1267         va_end(ap);
1268
1269         fw3_ipt_rule_addarg(r, false, "-m", "comment");
1270         fw3_ipt_rule_addarg(r, false, "--comment", buf);
1271 }
1272
1273 void
1274 fw3_ipt_rule_extra(struct fw3_ipt_rule *r, const char *extra)
1275 {
1276         char *p, **tmp, *s;
1277
1278         if (!extra || !*extra)
1279                 return;
1280
1281         s = fw3_strdup(extra);
1282
1283         for (p = strtok(s, " \t"); p; p = strtok(NULL, " \t"))
1284         {
1285                 tmp = realloc(r->argv, (r->argc + 1) * sizeof(*r->argv));
1286
1287                 if (!tmp)
1288                         break;
1289
1290                 r->argv = tmp;
1291                 r->argv[r->argc++] = fw3_strdup(p);
1292         }
1293
1294         free(s);
1295 }
1296
1297 #ifndef DISABLE_IPV6
1298 static void
1299 rule_print6(struct ip6t_entry *e)
1300 {
1301         char buf1[INET6_ADDRSTRLEN], buf2[INET6_ADDRSTRLEN];
1302         char *pname;
1303
1304         if (e->ipv6.flags & IP6T_F_PROTO)
1305         {
1306                 if (e->ipv6.invflags & XT_INV_PROTO)
1307                         printf(" !");
1308
1309                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e6));
1310
1311                 if (pname)
1312                         printf(" -p %s", pname);
1313                 else
1314                         printf(" -p %u", e->ipv6.proto);
1315         }
1316
1317         if (e->ipv6.iniface[0])
1318         {
1319                 if (e->ipv6.invflags & IP6T_INV_VIA_IN)
1320                         printf(" !");
1321
1322                 printf(" -i %s", e->ipv6.iniface);
1323         }
1324
1325         if (e->ipv6.outiface[0])
1326         {
1327                 if (e->ipv6.invflags & IP6T_INV_VIA_OUT)
1328                         printf(" !");
1329
1330                 printf(" -o %s", e->ipv6.outiface);
1331         }
1332
1333         if (memcmp(&e->ipv6.src, &in6addr_any, sizeof(struct in6_addr)))
1334         {
1335                 if (e->ipv6.invflags & IP6T_INV_SRCIP)
1336                         printf(" !");
1337
1338                 printf(" -s %s/%s",
1339                        inet_ntop(AF_INET6, &e->ipv6.src, buf1, sizeof(buf1)),
1340                        inet_ntop(AF_INET6, &e->ipv6.smsk, buf2, sizeof(buf2)));
1341         }
1342
1343         if (memcmp(&e->ipv6.dst, &in6addr_any, sizeof(struct in6_addr)))
1344         {
1345                 if (e->ipv6.invflags & IP6T_INV_DSTIP)
1346                         printf(" !");
1347
1348                 printf(" -d %s/%s",
1349                        inet_ntop(AF_INET6, &e->ipv6.dst, buf1, sizeof(buf1)),
1350                        inet_ntop(AF_INET6, &e->ipv6.dmsk, buf2, sizeof(buf2)));
1351         }
1352 }
1353 #endif
1354
1355 static void
1356 rule_print4(struct ipt_entry *e)
1357 {
1358         struct in_addr in_zero = { 0 };
1359         char buf1[sizeof("255.255.255.255")], buf2[sizeof("255.255.255.255")];
1360         char *pname;
1361
1362         if (e->ip.proto)
1363         {
1364                 if (e->ip.invflags & XT_INV_PROTO)
1365                         printf(" !");
1366
1367                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e));
1368
1369                 if (pname)
1370                         printf(" -p %s", pname);
1371                 else
1372                         printf(" -p %u", e->ip.proto);
1373         }
1374
1375         if (e->ip.iniface[0])
1376         {
1377                 if (e->ip.invflags & IPT_INV_VIA_IN)
1378                         printf(" !");
1379
1380                 printf(" -i %s", e->ip.iniface);
1381         }
1382
1383         if (e->ip.outiface[0])
1384         {
1385                 if (e->ip.invflags & IPT_INV_VIA_OUT)
1386                         printf(" !");
1387
1388                 printf(" -o %s", e->ip.outiface);
1389         }
1390
1391         if (memcmp(&e->ip.src, &in_zero, sizeof(struct in_addr)))
1392         {
1393                 if (e->ip.invflags & IPT_INV_SRCIP)
1394                         printf(" !");
1395
1396                 printf(" -s %s/%s",
1397                        inet_ntop(AF_INET, &e->ip.src, buf1, sizeof(buf1)),
1398                        inet_ntop(AF_INET, &e->ip.smsk, buf2, sizeof(buf2)));
1399         }
1400
1401         if (memcmp(&e->ip.dst, &in_zero, sizeof(struct in_addr)))
1402         {
1403                 if (e->ip.invflags & IPT_INV_DSTIP)
1404                         printf(" !");
1405
1406                 printf(" -d %s/%s",
1407                        inet_ntop(AF_INET, &e->ip.dst, buf1, sizeof(buf1)),
1408                        inet_ntop(AF_INET, &e->ip.dmsk, buf2, sizeof(buf2)));
1409         }
1410 }
1411
1412 static void
1413 rule_print(struct fw3_ipt_rule *r, const char *prefix, const char *chain)
1414 {
1415         debug(r->h, "%s %s", prefix, chain);
1416
1417 #ifndef DISABLE_IPV6
1418         if (r->h->family == FW3_FAMILY_V6)
1419                 rule_print6(&r->e6);
1420         else
1421 #endif
1422                 rule_print4(&r->e);
1423
1424         fw3_xt_print_matches(&r->e.ip, r->matches);
1425         fw3_xt_print_target(&r->e.ip, r->target);
1426
1427         printf("\n");
1428 }
1429
1430 static bool
1431 parse_option(struct fw3_ipt_rule *r, int optc, bool inv)
1432 {
1433         struct xtables_rule_match *m;
1434         struct xtables_match *em;
1435
1436         /* is a target option */
1437         if (r->target && fw3_xt_has_target_parse(r->target) &&
1438                 optc >= r->target->option_offset &&
1439                 optc < (r->target->option_offset + 256))
1440         {
1441                 xtables_option_tpcall(optc, r->argv, inv, r->target, &r->e);
1442                 return false;
1443         }
1444
1445         /* try to dispatch argument to one of the match parsers */
1446         for (m = r->matches; m; m = m->next)
1447         {
1448                 em = m->match;
1449
1450                 if (m->completed || !fw3_xt_has_match_parse(em))
1451                         continue;
1452
1453                 if (optc < em->option_offset ||
1454                         optc >= (em->option_offset + 256))
1455                         continue;
1456
1457                 xtables_option_mpcall(optc, r->argv, inv, em, &r->e);
1458                 return false;
1459         }
1460
1461         /* unhandled option, might belong to a protocol match */
1462         if ((em = load_protomatch(r)) != NULL)
1463         {
1464                 init_match(r, em, false);
1465
1466                 r->protocol_loaded = true;
1467                 optind--;
1468
1469                 return true;
1470         }
1471
1472         if (optc == ':')
1473                 warn("parse_option(): option '%s' needs argument", r->argv[optind-1]);
1474
1475         if (optc == '?')
1476                 warn("parse_option(): unknown option '%s'", r->argv[optind-1]);
1477
1478         return false;
1479 }
1480
1481 void
1482 fw3_ipt_rule_addarg(struct fw3_ipt_rule *r, bool inv,
1483                     const char *k, const char *v)
1484 {
1485         int n;
1486         char **tmp;
1487
1488         if (!k)
1489                 return;
1490
1491         n = inv + !!k + !!v;
1492         tmp = realloc(r->argv, (r->argc + n) * sizeof(*tmp));
1493
1494         if (!tmp)
1495                 return;
1496
1497         r->argv = tmp;
1498
1499         if (inv)
1500                 r->argv[r->argc++] = fw3_strdup("!");
1501
1502         r->argv[r->argc++] = fw3_strdup(k);
1503
1504         if (v)
1505                 r->argv[r->argc++] = fw3_strdup(v);
1506 }
1507
1508 static unsigned char *
1509 rule_mask(struct fw3_ipt_rule *r)
1510 {
1511         size_t s;
1512         unsigned char *p, *mask = NULL;
1513         struct xtables_rule_match *m;
1514
1515 #define SZ(x) XT_ALIGN(sizeof(struct x))
1516
1517 #ifndef DISABLE_IPV6
1518         if (r->h->family == FW3_FAMILY_V6)
1519         {
1520                 s = SZ(ip6t_entry);
1521
1522                 for (m = r->matches; m; m = m->next)
1523                         s += SZ(ip6t_entry_match) + m->match->size;
1524
1525                 s += SZ(ip6t_entry_target);
1526                 if (r->target)
1527                         s += r->target->size;
1528
1529                 mask = fw3_alloc(s);
1530                 memset(mask, 0xFF, SZ(ip6t_entry));
1531                 p = mask + SZ(ip6t_entry);
1532
1533                 for (m = r->matches; m; m = m->next)
1534                 {
1535                         memset(p, 0xFF, SZ(ip6t_entry_match) + m->match->userspacesize);
1536                         p += SZ(ip6t_entry_match) + m->match->size;
1537                 }
1538
1539                 memset(p, 0xFF, SZ(ip6t_entry_target) + (r->target ? r->target->userspacesize : 0));
1540         }
1541         else
1542 #endif
1543         {
1544                 s = SZ(ipt_entry);
1545
1546                 for (m = r->matches; m; m = m->next)
1547                         s += SZ(ipt_entry_match) + m->match->size;
1548
1549                 s += SZ(ipt_entry_target);
1550                 if (r->target)
1551                         s += r->target->size;
1552
1553                 mask = fw3_alloc(s);
1554                 memset(mask, 0xFF, SZ(ipt_entry));
1555                 p = mask + SZ(ipt_entry);
1556
1557                 for (m = r->matches; m; m = m->next)
1558                 {
1559                         memset(p, 0xFF, SZ(ipt_entry_match) + m->match->userspacesize);
1560                         p += SZ(ipt_entry_match) + m->match->size;
1561                 }
1562
1563                 memset(p, 0xFF, SZ(ipt_entry_target) + (r->target ? r->target->userspacesize : 0));
1564         }
1565
1566         return mask;
1567 }
1568
1569 static void *
1570 rule_build(struct fw3_ipt_rule *r)
1571 {
1572         size_t s, target_size = (r->target) ? r->target->t->u.target_size : 0;
1573         struct xtables_rule_match *m;
1574
1575 #ifndef DISABLE_IPV6
1576         if (r->h->family == FW3_FAMILY_V6)
1577         {
1578                 struct ip6t_entry *e6;
1579
1580                 s = XT_ALIGN(sizeof(struct ip6t_entry));
1581
1582                 for (m = r->matches; m; m = m->next)
1583                         s += m->match->m->u.match_size;
1584
1585                 e6 = fw3_alloc(s + target_size);
1586
1587                 memcpy(e6, &r->e6, sizeof(struct ip6t_entry));
1588
1589                 e6->target_offset = s;
1590                 e6->next_offset = s + target_size;
1591
1592                 s = 0;
1593
1594                 for (m = r->matches; m; m = m->next)
1595                 {
1596                         memcpy(e6->elems + s, m->match->m, m->match->m->u.match_size);
1597                         s += m->match->m->u.match_size;
1598                 }
1599
1600                 if (target_size)
1601                         memcpy(e6->elems + s, r->target->t, target_size);
1602
1603                 return e6;
1604         }
1605         else
1606 #endif
1607         {
1608                 struct ipt_entry *e;
1609
1610                 s = XT_ALIGN(sizeof(struct ipt_entry));
1611
1612                 for (m = r->matches; m; m = m->next)
1613                         s += m->match->m->u.match_size;
1614
1615                 e = fw3_alloc(s + target_size);
1616
1617                 memcpy(e, &r->e, sizeof(struct ipt_entry));
1618
1619                 e->target_offset = s;
1620                 e->next_offset = s + target_size;
1621
1622                 s = 0;
1623
1624                 for (m = r->matches; m; m = m->next)
1625                 {
1626                         memcpy(e->elems + s, m->match->m, m->match->m->u.match_size);
1627                         s += m->match->m->u.match_size;
1628                 }
1629
1630                 if (target_size)
1631                         memcpy(e->elems + s, r->target->t, target_size);
1632
1633                 return e;
1634         }
1635 }
1636
1637 static void
1638 set_rule_tag(struct fw3_ipt_rule *r)
1639 {
1640         int i;
1641         char *p, **tmp;
1642         const char *tag = "!fw3";
1643
1644         for (i = 0; i < r->argc; i++)
1645                 if (!strcmp(r->argv[i], "--comment") && (i + 1) < r->argc)
1646                         if (asprintf(&p, "%s: %s", tag, r->argv[i + 1]) > 0)
1647                         {
1648                                 free(r->argv[i + 1]);
1649                                 r->argv[i + 1] = p;
1650                                 return;
1651                         }
1652
1653         tmp = realloc(r->argv, (r->argc + 4) * sizeof(*r->argv));
1654
1655         if (tmp)
1656         {
1657                 r->argv = tmp;
1658                 r->argv[r->argc++] = fw3_strdup("-m");
1659                 r->argv[r->argc++] = fw3_strdup("comment");
1660                 r->argv[r->argc++] = fw3_strdup("--comment");
1661                 r->argv[r->argc++] = fw3_strdup(tag);
1662         }
1663 }
1664
1665 void
1666 __fw3_ipt_rule_append(struct fw3_ipt_rule *r, bool repl, const char *fmt, ...)
1667 {
1668         void *rule;
1669         unsigned char *mask;
1670
1671         struct xtables_rule_match *m;
1672         struct xtables_match *em;
1673         struct xtables_target *et;
1674         struct xtables_globals *g;
1675
1676         struct fw3_device dev;
1677         struct fw3_address addr;
1678
1679         enum xtables_exittype status;
1680
1681         int i, optc;
1682         bool inv = false;
1683         char buf[32];
1684         va_list ap;
1685
1686         va_start(ap, fmt);
1687         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
1688         va_end(ap);
1689
1690         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
1691         g->opts = g->orig_opts;
1692
1693         optind = 0;
1694         opterr = 0;
1695
1696         status = setjmp(fw3_ipt_error_jmp);
1697
1698         if (status > 0)
1699         {
1700                 info("     ! Skipping due to previous exception (code %u)", status);
1701                 goto free;
1702         }
1703
1704         set_rule_tag(r);
1705
1706         while ((optc = getopt_long(r->argc, r->argv, "-:m:j:i:o:s:d:", g->opts,
1707                                    NULL)) != -1)
1708         {
1709                 switch (optc)
1710                 {
1711                 case 'm':
1712                         em = find_match(r, optarg);
1713
1714                         if (!em)
1715                         {
1716                                 warn("fw3_ipt_rule_append(): Can't find match '%s'", optarg);
1717                                 goto free;
1718                         }
1719
1720                         init_match(r, em, true);
1721                         break;
1722
1723                 case 'j':
1724                         et = get_target(r, optarg);
1725
1726                         if (!et)
1727                         {
1728                                 warn("fw3_ipt_rule_append(): Can't find target '%s'", optarg);
1729                                 goto free;
1730                         }
1731
1732                         break;
1733
1734                 case 'i':
1735                 case 'o':
1736                         if (!fw3_parse_device(&dev, optarg, false) ||
1737                             dev.any || dev.invert || *dev.network)
1738                         {
1739                                 warn("fw3_ipt_rule_append(): Bad argument '%s'", optarg);
1740                                 goto free;
1741                         }
1742
1743                         dev.invert = inv;
1744                         fw3_ipt_rule_in_out(r, (optc == 'i') ? &dev : NULL,
1745                                                (optc == 'o') ? &dev : NULL);
1746                         break;
1747
1748                 case 's':
1749                 case 'd':
1750                         if (!fw3_parse_address(&addr, optarg, false) ||
1751                             addr.range || addr.invert)
1752                         {
1753                                 warn("fw3_ipt_rule_append(): Bad argument '%s'", optarg);
1754                                 goto free;
1755                         }
1756
1757                         addr.invert = inv;
1758                         fw3_ipt_rule_src_dest(r, (optc == 's') ? &addr : NULL,
1759                                                  (optc == 'd') ? &addr : NULL);
1760                         break;
1761
1762                 case 1:
1763                         if ((optarg[0] == '!') && (optarg[1] == '\0'))
1764                         {
1765                                 optarg[0] = '\0';
1766                                 inv = true;
1767                                 continue;
1768                         }
1769
1770                         warn("fw3_ipt_rule_append(): Bad argument '%s'", optarg);
1771                         goto free;
1772
1773                 default:
1774                         if (parse_option(r, optc, inv))
1775                                 continue;
1776                         break;
1777                 }
1778
1779                 inv = false;
1780         }
1781
1782         for (m = r->matches; m; m = m->next)
1783                 xtables_option_mfcall(m->match);
1784
1785         if (r->target)
1786                 xtables_option_tfcall(r->target);
1787
1788         rule = rule_build(r);
1789
1790 #ifndef DISABLE_IPV6
1791         if (r->h->family == FW3_FAMILY_V6)
1792         {
1793                 if (repl)
1794                 {
1795                         mask = rule_mask(r);
1796
1797                         while (ip6tc_delete_entry(buf, rule, mask, r->h->handle))
1798                                 if (fw3_pr_debug)
1799                                         rule_print(r, "-D", buf);
1800
1801                         free(mask);
1802                 }
1803
1804                 if (fw3_pr_debug)
1805                         rule_print(r, "-A", buf);
1806
1807                 if (!ip6tc_append_entry(buf, rule, r->h->handle))
1808                         warn("ip6tc_append_entry(): %s", ip6tc_strerror(errno));
1809         }
1810         else
1811 #endif
1812         {
1813                 if (repl)
1814                 {
1815                         mask = rule_mask(r);
1816
1817                         while (iptc_delete_entry(buf, rule, mask, r->h->handle))
1818                                 if (fw3_pr_debug)
1819                                         rule_print(r, "-D", buf);
1820
1821                         free(mask);
1822                 }
1823
1824                 if (fw3_pr_debug)
1825                         rule_print(r, "-A", buf);
1826
1827                 if (!iptc_append_entry(buf, rule, r->h->handle))
1828                         warn("iptc_append_entry(): %s\n", iptc_strerror(errno));
1829         }
1830
1831         free(rule);
1832
1833 free:
1834         for (i = 1; i < r->argc; i++)
1835                 free(r->argv[i]);
1836
1837         free(r->argv);
1838
1839         xtables_rule_matches_free(&r->matches);
1840
1841         if (r->target)
1842                 free(r->target->t);
1843
1844         free(r);
1845
1846         /* reset all targets and matches */
1847         for (em = xtables_matches; em; em = em->next)
1848                 em->mflags = 0;
1849
1850         for (et = xtables_targets; et; et = et->next)
1851         {
1852                 et->tflags = 0;
1853                 et->used = 0;
1854         }
1855
1856         xtables_free_opts(1);
1857 }
1858
1859 struct fw3_ipt_rule *
1860 fw3_ipt_rule_create(struct fw3_ipt_handle *handle, struct fw3_protocol *proto,
1861                     struct fw3_device *in, struct fw3_device *out,
1862                     struct fw3_address *src, struct fw3_address *dest)
1863 {
1864         struct fw3_ipt_rule *r;
1865
1866         r = fw3_ipt_rule_new(handle);
1867
1868         fw3_ipt_rule_proto(r, proto);
1869         fw3_ipt_rule_in_out(r, in, out);
1870         fw3_ipt_rule_src_dest(r, src, dest);
1871
1872         return r;
1873 }
1874
1875 void
1876 xtables_register_match(struct xtables_match *me)
1877 {
1878         int i;
1879         static struct xtables_match **tmp;
1880
1881         if (!xext.register_match)
1882                 xext.register_match = dlsym(RTLD_NEXT, "xtables_register_match");
1883
1884         if (!xext.register_match)
1885                 return;
1886
1887         xext.register_match(me);
1888
1889         if (xext.retain)
1890         {
1891                 for (i = 0; i < xext.mcount; i++)
1892                         if (xext.matches[i] == me)
1893                                 return;
1894
1895                 tmp = realloc(xext.matches, sizeof(me) * (xext.mcount + 1));
1896
1897                 if (!tmp)
1898                         return;
1899
1900                 xext.matches = tmp;
1901                 xext.matches[xext.mcount++] = me;
1902         }
1903 }
1904
1905 void
1906 xtables_register_target(struct xtables_target *me)
1907 {
1908         int i;
1909         static struct xtables_target **tmp;
1910
1911         if (!xext.register_target)
1912                 xext.register_target = dlsym(RTLD_NEXT, "xtables_register_target");
1913
1914         if (!xext.register_target)
1915                 return;
1916
1917         xext.register_target(me);
1918
1919         if (xext.retain)
1920         {
1921                 for (i = 0; i < xext.tcount; i++)
1922                         if (xext.targets[i] == me)
1923                                 return;
1924
1925                 tmp = realloc(xext.targets, sizeof(me) * (xext.tcount + 1));
1926
1927                 if (!tmp)
1928                         return;
1929
1930                 xext.targets = tmp;
1931                 xext.targets[xext.tcount++] = me;
1932         }
1933 }