Dynamically create rules for available libext*.a libraries, clean up rules
[project/firewall3.git] / iptables.c
1 /*
2  * firewall3 - 3rd OpenWrt UCI firewall implementation
3  *
4  *   Copyright (C) 2013 Jo-Philipp Wich <jow@openwrt.org>
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 #include "iptables.h"
20
21
22 static struct option base_opts[] = {
23         { .name = "match",  .has_arg = 1, .val = 'm' },
24         { .name = "jump",   .has_arg = 1, .val = 'j' },
25         { .name = "append", .has_arg = 1, .val = 'A' },
26         { NULL }
27 };
28
29 static struct xtables_globals xtg = {
30         .option_offset = 0,
31         .program_version = "4",
32         .orig_opts = base_opts,
33 };
34
35 static struct xtables_globals xtg6 = {
36         .option_offset = 0,
37         .program_version = "6",
38         .orig_opts = base_opts,
39 };
40
41 /* Required by certain extensions like SNAT and DNAT */
42 int kernel_version = 0;
43
44 void
45 get_kernel_version(void)
46 {
47         static struct utsname uts;
48         int x = 0, y = 0, z = 0;
49
50         if (uname(&uts) == -1)
51                 sprintf(uts.release, "3.0.0");
52
53         sscanf(uts.release, "%d.%d.%d", &x, &y, &z);
54         kernel_version = 0x10000 * x + 0x100 * y + z;
55 }
56
57 #undef __ipt_module
58 #define __ipt_module(x) libxt_##x##_init, libipt_##x##_init, libip6t_##x##_init,
59
60 static void fw3_init_extensions(void)
61 {
62         int i;
63         void (*initfuncs[])(void) = { FW3_IPT_MODULES };
64
65         for (i = 0; i < sizeof(initfuncs)/sizeof(initfuncs[0]); i++)
66                 if (initfuncs[i])
67                         initfuncs[i]();
68 }
69
70 struct fw3_ipt_handle *
71 fw3_ipt_open(enum fw3_family family, enum fw3_table table)
72 {
73         struct fw3_ipt_handle *h;
74
75         h = fw3_alloc(sizeof(*h));
76
77         xtables_init();
78
79         if (family == FW3_FAMILY_V6)
80         {
81                 h->family = FW3_FAMILY_V6;
82                 h->table  = table;
83                 h->handle = ip6tc_init(fw3_flag_names[table]);
84
85                 xtables_set_params(&xtg6);
86                 xtables_set_nfproto(NFPROTO_IPV6);
87         }
88         else
89         {
90                 h->family = FW3_FAMILY_V4;
91                 h->table  = table;
92                 h->handle = iptc_init(fw3_flag_names[table]);
93
94                 xtables_set_params(&xtg);
95                 xtables_set_nfproto(NFPROTO_IPV4);
96         }
97
98         if (!h->handle)
99         {
100                 free(h);
101                 return NULL;
102         }
103
104         xtables_pending_matches = NULL;
105         xtables_pending_targets = NULL;
106
107         xtables_matches = NULL;
108         xtables_targets = NULL;
109
110         fw3_init_extensions();
111
112         return h;
113 }
114
115 static void
116 debug(struct fw3_ipt_handle *h, const char *fmt, ...)
117 {
118         va_list ap;
119
120         printf("%s -t %s ", (h->family == FW3_FAMILY_V6) ? "ip6tables" : "iptables",
121                             fw3_flag_names[h->table]);
122
123         va_start(ap, fmt);
124         vprintf(fmt, ap);
125         va_end(ap);
126 }
127
128 void
129 fw3_ipt_set_policy(struct fw3_ipt_handle *h, const char *chain,
130                    enum fw3_flag policy)
131 {
132         if (fw3_pr_debug)
133                 debug(h, "-P %s %s\n", chain, fw3_flag_names[policy]);
134
135         if (h->family == FW3_FAMILY_V6)
136                 ip6tc_set_policy(chain, fw3_flag_names[policy], NULL, h->handle);
137         else
138                 iptc_set_policy(chain, fw3_flag_names[policy], NULL, h->handle);
139 }
140
141 void
142 fw3_ipt_delete_chain(struct fw3_ipt_handle *h, const char *chain)
143 {
144         if (fw3_pr_debug)
145         {
146                 debug(h, "-F %s\n", chain);
147                 debug(h, "-X %s\n", chain);
148         }
149
150         if (h->family == FW3_FAMILY_V6)
151         {
152                 if (ip6tc_flush_entries(chain, h->handle))
153                         ip6tc_delete_chain(chain, h->handle);
154         }
155         else
156         {
157                 if (iptc_flush_entries(chain, h->handle))
158                         iptc_delete_chain(chain, h->handle);
159         }
160 }
161
162 void
163 fw3_ipt_delete_rules(struct fw3_ipt_handle *h, const char *target)
164 {
165         unsigned int num;
166         const struct ipt_entry *e;
167         const struct ip6t_entry *e6;
168         const char *chain;
169         const char *t;
170         bool found;
171
172         if (h->family == FW3_FAMILY_V6)
173         {
174                 for (chain = ip6tc_first_chain(h->handle);
175                      chain != NULL;
176                      chain = ip6tc_next_chain(h->handle))
177                 {
178                         do {
179                                 found = false;
180
181                                 for (num = 0, e6 = ip6tc_first_rule(chain, h->handle);
182                                          e6 != NULL;
183                                          num++, e6 = ip6tc_next_rule(e6, h->handle))
184                                 {
185                                         t = ip6tc_get_target(e6, h->handle);
186
187                                         if (*t && !strcmp(t, target))
188                                         {
189                                                 if (fw3_pr_debug)
190                                                         debug(h, "-D %s %u\n", chain, num + 1);
191
192                                                 ip6tc_delete_num_entry(chain, num, h->handle);
193                                                 found = true;
194                                                 break;
195                                         }
196                                 }
197                         } while (found);
198                 }
199         }
200         else
201         {
202                 for (chain = iptc_first_chain(h->handle);
203                      chain != NULL;
204                      chain = iptc_next_chain(h->handle))
205                 {
206                         do {
207                                 found = false;
208
209                                 for (num = 0, e = iptc_first_rule(chain, h->handle);
210                                      e != NULL;
211                                          num++, e = iptc_next_rule(e, h->handle))
212                                 {
213                                         t = iptc_get_target(e, h->handle);
214
215                                         if (*t && !strcmp(t, target))
216                                         {
217                                                 if (fw3_pr_debug)
218                                                         debug(h, "-D %s %u\n", chain, num + 1);
219
220                                                 iptc_delete_num_entry(chain, num, h->handle);
221                                                 found = true;
222                                                 break;
223                                         }
224                                 }
225                         } while (found);
226                 }
227         }
228 }
229
230 void
231 fw3_ipt_create_chain(struct fw3_ipt_handle *h, const char *fmt, ...)
232 {
233         char buf[32];
234         va_list ap;
235
236         va_start(ap, fmt);
237         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
238         va_end(ap);
239
240         if (fw3_pr_debug)
241                 debug(h, "-N %s\n", buf);
242
243         iptc_create_chain(buf, h->handle);
244 }
245
246 void
247 fw3_ipt_flush(struct fw3_ipt_handle *h)
248 {
249         const char *chain;
250
251         if (h->family == FW3_FAMILY_V6)
252         {
253                 for (chain = ip6tc_first_chain(h->handle);
254                      chain != NULL;
255                      chain = ip6tc_next_chain(h->handle))
256                 {
257                         ip6tc_flush_entries(chain, h->handle);
258                 }
259
260                 for (chain = ip6tc_first_chain(h->handle);
261                      chain != NULL;
262                      chain = ip6tc_next_chain(h->handle))
263                 {
264                         ip6tc_delete_chain(chain, h->handle);
265                 }
266         }
267         else
268         {
269                 for (chain = iptc_first_chain(h->handle);
270                      chain != NULL;
271                      chain = iptc_next_chain(h->handle))
272                 {
273                         iptc_flush_entries(chain, h->handle);
274                 }
275
276                 for (chain = iptc_first_chain(h->handle);
277                      chain != NULL;
278                      chain = iptc_next_chain(h->handle))
279                 {
280                         iptc_delete_chain(chain, h->handle);
281                 }
282         }
283 }
284
285 void
286 fw3_ipt_commit(struct fw3_ipt_handle *h)
287 {
288         int rv;
289
290         if (h->family == FW3_FAMILY_V6)
291         {
292                 rv = ip6tc_commit(h->handle);
293                 if (!rv)
294                         fprintf(stderr, "ip6tc_commit(): %s\n", ip6tc_strerror(errno));
295         }
296         else
297         {
298                 rv = iptc_commit(h->handle);
299                 if (!rv)
300                         fprintf(stderr, "iptc_commit(): %s\n", iptc_strerror(errno));
301         }
302
303         free(h);
304 }
305
306 struct fw3_ipt_rule *
307 fw3_ipt_rule_new(struct fw3_ipt_handle *h)
308 {
309         struct fw3_ipt_rule *r;
310
311         r = fw3_alloc(sizeof(*r));
312
313         r->h = h;
314         r->argv = fw3_alloc(sizeof(char *));
315         r->argv[r->argc++] = "fw3";
316
317         return r;
318 }
319
320
321 static bool
322 is_chain(struct fw3_ipt_handle *h, const char *name)
323 {
324         if (h->family == FW3_FAMILY_V6)
325                 return ip6tc_is_chain(name, h->handle);
326         else
327                 return iptc_is_chain(name, h->handle);
328 }
329
330 static char *
331 get_protoname(struct fw3_ipt_rule *r)
332 {
333         const struct xtables_pprot *pp;
334
335         if (r->protocol)
336                 for (pp = xtables_chain_protos; pp->name; pp++)
337                         if (pp->num == r->protocol)
338                                 return (char *)pp->name;
339
340         return NULL;
341 }
342
343 static struct xtables_match *
344 find_match(struct fw3_ipt_rule *r, const char *name)
345 {
346         return xtables_find_match(name, XTF_TRY_LOAD, &r->matches);
347 }
348
349 static void
350 init_match(struct fw3_ipt_rule *r, struct xtables_match *m, bool no_clone)
351 {
352         size_t s;
353         struct xtables_globals *g;
354
355         if (!m)
356                 return;
357
358         s = XT_ALIGN(sizeof(struct xt_entry_match)) + m->size;
359
360         m->m = fw3_alloc(s);
361
362         fw3_xt_set_match_name(m);
363
364         m->m->u.user.revision = m->revision;
365         m->m->u.match_size = s;
366
367         /* free previous userspace data */
368         fw3_xt_free_match_udata(m);
369
370         if (m->init)
371                 m->init(m->m);
372
373         /* don't merge options if no_clone is set and this match is a clone */
374         if (no_clone && (m == m->next))
375                 return;
376
377         /* merge option table */
378         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
379         fw3_xt_merge_match_options(g, m);
380 }
381
382 static bool
383 need_protomatch(struct fw3_ipt_rule *r, const char *pname)
384 {
385         if (!pname)
386                 return false;
387
388         if (!xtables_find_match(pname, XTF_DONT_LOAD, NULL))
389                 return true;
390
391         return !r->protocol_loaded;
392 }
393
394 static struct xtables_match *
395 load_protomatch(struct fw3_ipt_rule *r)
396 {
397         const char *pname = get_protoname(r);
398
399         if (!need_protomatch(r, pname))
400                 return NULL;
401
402         return find_match(r, pname);
403 }
404
405 static struct xtables_target *
406 get_target(struct fw3_ipt_rule *r, const char *name)
407 {
408         size_t s;
409         struct xtables_target *t;
410         struct xtables_globals *g;
411
412         bool chain = is_chain(r->h, name);
413
414         if (chain)
415                 t = xtables_find_target(XT_STANDARD_TARGET, XTF_LOAD_MUST_SUCCEED);
416         else
417                 t = xtables_find_target(name, XTF_TRY_LOAD);
418
419         if (!t)
420                 return NULL;
421
422         s = XT_ALIGN(sizeof(struct xt_entry_target)) + t->size;
423         t->t = fw3_alloc(s);
424
425         fw3_xt_set_target_name(t, name);
426
427         t->t->u.user.revision = t->revision;
428         t->t->u.target_size = s;
429
430         /* free previous userspace data */
431         fw3_xt_free_target_udata(t);
432
433         if (t->init)
434                 t->init(t->t);
435
436         /* merge option table */
437         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
438         fw3_xt_merge_target_options(g, t);
439
440         r->target = t;
441
442         return t;
443 }
444
445 void
446 fw3_ipt_rule_proto(struct fw3_ipt_rule *r, struct fw3_protocol *proto)
447 {
448         uint32_t pr;
449
450         if (!proto || proto->any)
451                 return;
452
453         pr = proto->protocol;
454
455         if (r->h->family == FW3_FAMILY_V6)
456         {
457                 if (pr == 1)
458                         pr = 58;
459
460                 r->e6.ipv6.proto = pr;
461                 r->e6.ipv6.flags |= IP6T_F_PROTO;
462
463                 if (proto->invert)
464                         r->e6.ipv6.invflags |= XT_INV_PROTO;
465         }
466         else
467         {
468                 r->e.ip.proto = pr;
469
470                 if (proto->invert)
471                         r->e.ip.invflags |= XT_INV_PROTO;
472         }
473
474         r->protocol = pr;
475 }
476
477 void
478 fw3_ipt_rule_in_out(struct fw3_ipt_rule *r,
479                     struct fw3_device *in, struct fw3_device *out)
480 {
481         if (r->h->family == FW3_FAMILY_V6)
482         {
483                 if (in && !in->any)
484                 {
485                         xtables_parse_interface(in->name, r->e6.ipv6.iniface,
486                                                           r->e6.ipv6.iniface_mask);
487
488                         if (in->invert)
489                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_IN;
490                 }
491
492                 if (out && !out->any)
493                 {
494                         xtables_parse_interface(out->name, r->e6.ipv6.outiface,
495                                                            r->e6.ipv6.outiface_mask);
496
497                         if (out->invert)
498                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_OUT;
499                 }
500         }
501         else
502         {
503                 if (in && !in->any)
504                 {
505                         xtables_parse_interface(in->name, r->e.ip.iniface,
506                                                           r->e.ip.iniface_mask);
507
508                         if (in->invert)
509                                 r->e.ip.invflags |= IPT_INV_VIA_IN;
510                 }
511
512                 if (out && !out->any)
513                 {
514                         xtables_parse_interface(out->name, r->e.ip.outiface,
515                                                            r->e.ip.outiface_mask);
516
517                         if (out->invert)
518                                 r->e.ip.invflags |= IPT_INV_VIA_OUT;
519                 }
520         }
521 }
522
523
524 static void
525 ip4prefix2mask(int prefix, struct in_addr *mask)
526 {
527         mask->s_addr = htonl(~((1 << (32 - prefix)) - 1));
528 }
529
530 static void
531 ip6prefix2mask(int prefix, struct in6_addr *mask)
532 {
533         char *p = (char *)mask;
534
535         if (prefix > 0)
536         {
537                 memset(p, 0xff, prefix / 8);
538                 memset(p + (prefix / 8) + 1, 0, (128 - prefix) / 8);
539                 p[prefix / 8] = 0xff << (8 - (prefix & 7));
540         }
541         else
542         {
543                 memset(mask, 0, sizeof(*mask));
544         }
545 }
546
547 void
548 fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
549                       struct fw3_address *src, struct fw3_address *dest)
550 {
551         int i;
552
553         if ((src && src->range) || (dest && dest->range))
554         {
555                 fw3_ipt_rule_addarg(r, false, "-m", "iprange");
556         }
557
558         if (src && src->set)
559         {
560                 if (src->range)
561                 {
562                         fw3_ipt_rule_addarg(r, src->invert, "--src-range",
563                                             fw3_address_to_string(src, false));
564                 }
565                 else if (r->h->family == FW3_FAMILY_V6)
566                 {
567                         r->e6.ipv6.src = src->address.v6;
568                         ip6prefix2mask(src->mask, &r->e6.ipv6.smsk);
569
570                         for (i = 0; i < 4; i++)
571                                 r->e6.ipv6.src.s6_addr32[i] &= r->e6.ipv6.smsk.s6_addr32[i];
572
573                         if (src->invert)
574                                 r->e6.ipv6.invflags |= IP6T_INV_SRCIP;
575                 }
576                 else
577                 {
578                         r->e.ip.src = src->address.v4;
579                         ip4prefix2mask(src->mask, &r->e.ip.smsk);
580
581                         r->e.ip.src.s_addr &= r->e.ip.smsk.s_addr;
582
583                         if (src->invert)
584                                 r->e.ip.invflags |= IPT_INV_SRCIP;
585                 }
586         }
587
588         if (dest && dest->set)
589         {
590                 if (dest->range)
591                 {
592                         fw3_ipt_rule_addarg(r, dest->invert, "--dst-range",
593                                             fw3_address_to_string(dest, false));
594                 }
595                 else if (r->h->family == FW3_FAMILY_V6)
596                 {
597                         r->e6.ipv6.dst = dest->address.v6;
598                         ip6prefix2mask(dest->mask, &r->e6.ipv6.dmsk);
599
600                         for (i = 0; i < 4; i++)
601                                 r->e6.ipv6.dst.s6_addr32[i] &= r->e6.ipv6.dmsk.s6_addr32[i];
602
603                         if (dest->invert)
604                                 r->e6.ipv6.invflags |= IP6T_INV_DSTIP;
605                 }
606                 else
607                 {
608                         r->e.ip.dst = dest->address.v4;
609                         ip4prefix2mask(dest->mask, &r->e.ip.dmsk);
610
611                         r->e.ip.dst.s_addr &= r->e.ip.dmsk.s_addr;
612
613                         if (dest->invert)
614                                 r->e.ip.invflags |= IPT_INV_DSTIP;
615                 }
616         }
617 }
618
619 void
620 fw3_ipt_rule_sport_dport(struct fw3_ipt_rule *r,
621                          struct fw3_port *sp, struct fw3_port *dp)
622 {
623         char buf[sizeof("65535:65535\0")];
624
625         if ((!sp || !sp->set) && (!dp || !dp->set))
626                 return;
627
628         if (!get_protoname(r))
629                 return;
630
631         if (sp && sp->set)
632         {
633                 if (sp->port_min == sp->port_max)
634                         sprintf(buf, "%u", sp->port_min);
635                 else
636                         sprintf(buf, "%u:%u", sp->port_min, sp->port_max);
637
638                 fw3_ipt_rule_addarg(r, sp->invert, "--sport", buf);
639         }
640
641         if (dp && dp->set)
642         {
643                 if (dp->port_min == dp->port_max)
644                         sprintf(buf, "%u", dp->port_min);
645                 else
646                         sprintf(buf, "%u:%u", dp->port_min, dp->port_max);
647
648                 fw3_ipt_rule_addarg(r, dp->invert, "--dport", buf);
649         }
650 }
651
652 void
653 fw3_ipt_rule_mac(struct fw3_ipt_rule *r, struct fw3_mac *mac)
654 {
655         if (!mac)
656                 return;
657
658         fw3_ipt_rule_addarg(r, false, "-m", "mac");
659         fw3_ipt_rule_addarg(r, mac->invert, "--mac-source", ether_ntoa(&mac->mac));
660 }
661
662 void
663 fw3_ipt_rule_icmptype(struct fw3_ipt_rule *r, struct fw3_icmptype *icmp)
664 {
665         char buf[sizeof("255/255\0")];
666
667         if (!icmp)
668                 return;
669
670         if (r->h->family == FW3_FAMILY_V6)
671         {
672                 if (icmp->code6_min == 0 && icmp->code6_max == 0xFF)
673                         sprintf(buf, "%u", icmp->type6);
674                 else
675                         sprintf(buf, "%u/%u", icmp->type6, icmp->code6_min);
676
677                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmpv6-type", buf);
678         }
679         else
680         {
681                 if (icmp->code_min == 0 && icmp->code_max == 0xFF)
682                         sprintf(buf, "%u", icmp->type);
683                 else
684                         sprintf(buf, "%u/%u", icmp->type, icmp->code_min);
685
686                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmp-type", buf);
687         }
688 }
689
690 void
691 fw3_ipt_rule_limit(struct fw3_ipt_rule *r, struct fw3_limit *limit)
692 {
693         char buf[sizeof("-4294967296/second\0")];
694
695         if (!limit || limit->rate <= 0)
696                 return;
697
698         fw3_ipt_rule_addarg(r, false, "-m", "limit");
699
700         sprintf(buf, "%u/%s", limit->rate, fw3_limit_units[limit->unit]);
701         fw3_ipt_rule_addarg(r, limit->invert, "--limit", buf);
702
703         if (limit->burst > 0)
704         {
705                 sprintf(buf, "%u", limit->burst);
706                 fw3_ipt_rule_addarg(r, limit->invert, "--limit-burst", buf);
707         }
708 }
709
710 void
711 fw3_ipt_rule_ipset(struct fw3_ipt_rule *r, struct fw3_ipset *ipset,
712                    bool invert)
713 {
714         char buf[sizeof("dst,dst,dst\0")];
715         char *p = buf;
716
717         struct fw3_ipset_datatype *type;
718
719         if (!ipset)
720                 return;
721
722         list_for_each_entry(type, &ipset->datatypes, list)
723         {
724                 if (p > buf)
725                         *p++ = ',';
726
727                 p += sprintf(p, "%s", type->dest ? "dst" : "src");
728         }
729
730         fw3_ipt_rule_addarg(r, false, "-m", "set");
731
732         fw3_ipt_rule_addarg(r, invert, "--match-set",
733                             ipset->external ? ipset->external : ipset->name);
734
735         fw3_ipt_rule_addarg(r, false, buf, NULL);
736 }
737
738 void
739 fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
740 {
741         int i;
742         struct tm empty = { 0 };
743
744         char buf[84]; /* sizeof("1,2,3,...,30,31\0") */
745         char *p;
746
747         bool d1 = memcmp(&time->datestart, &empty, sizeof(empty));
748         bool d2 = memcmp(&time->datestop, &empty, sizeof(empty));
749
750         if (!d1 && !d2 && !time->timestart && !time->timestop &&
751             !(time->monthdays & 0xFFFFFFFE) && !(time->weekdays & 0xFE))
752         {
753                 return;
754         }
755
756         fw3_ipt_rule_addarg(r, false, "-m", "time");
757
758         if (time->utc)
759                 fw3_ipt_rule_addarg(r, false, "--utc", NULL);
760
761         if (d1)
762         {
763                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestart);
764                 fw3_ipt_rule_addarg(r, false, "--datestart", buf);
765         }
766
767         if (d2)
768         {
769                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestop);
770                 fw3_ipt_rule_addarg(r, false, "--datestop", buf);
771         }
772
773         if (time->timestart)
774         {
775                 sprintf(buf, "%02d:%02d:%02d",
776                         time->timestart / 3600,
777                         time->timestart % 3600 / 60,
778                         time->timestart % 60);
779
780                 fw3_ipt_rule_addarg(r, false, "--timestart", buf);
781         }
782
783         if (time->timestop)
784         {
785                 sprintf(buf, "%02d:%02d:%02d",
786                         time->timestop / 3600,
787                         time->timestop % 3600 / 60,
788                         time->timestop % 60);
789
790                 fw3_ipt_rule_addarg(r, false, "--timestop", buf);
791         }
792
793         if (time->monthdays & 0xFFFFFFFE)
794         {
795                 for (i = 1, p = buf; i < 32; i++)
796                 {
797                         if (hasbit(time->monthdays, i))
798                         {
799                                 if (p > buf)
800                                         *p++ = ',';
801
802                                 p += sprintf(p, "%u", i);
803                         }
804                 }
805
806                 fw3_ipt_rule_addarg(r, hasbit(time->monthdays, 0), "--monthdays", buf);
807         }
808
809         if (time->weekdays & 0xFE)
810         {
811                 for (i = 1, p = buf; i < 8; i++)
812                 {
813                         if (hasbit(time->weekdays, i))
814                         {
815                                 if (p > buf)
816                                         *p++ = ',';
817
818                                 p += sprintf(p, "%u", i);
819                         }
820                 }
821
822                 fw3_ipt_rule_addarg(r, hasbit(time->weekdays, 0), "--weekdays", buf);
823         }
824 }
825
826 void
827 fw3_ipt_rule_mark(struct fw3_ipt_rule *r, struct fw3_mark *mark)
828 {
829         char buf[sizeof("0xFFFFFFFF/0xFFFFFFFF\0")];
830
831         if (!mark || !mark->set)
832                 return;
833
834         if (mark->mask < 0xFFFFFFFF)
835                 sprintf(buf, "0x%x/0x%x", mark->mark, mark->mask);
836         else
837                 sprintf(buf, "0x%x", mark->mark);
838
839         fw3_ipt_rule_addarg(r, false, "-m", "mark");
840         fw3_ipt_rule_addarg(r, mark->invert, "--mark", buf);
841 }
842
843 void
844 fw3_ipt_rule_comment(struct fw3_ipt_rule *r, const char *fmt, ...)
845 {
846         va_list ap;
847         char buf[256];
848
849         if (!fmt || !*fmt)
850                 return;
851
852         va_start(ap, fmt);
853         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
854         va_end(ap);
855
856         fw3_ipt_rule_addarg(r, false, "-m", "comment");
857         fw3_ipt_rule_addarg(r, false, "--comment", buf);
858 }
859
860 void
861 fw3_ipt_rule_extra(struct fw3_ipt_rule *r, const char *extra)
862 {
863         char *p, **tmp, *s;
864
865         if (!extra || !*extra)
866                 return;
867
868         s = fw3_strdup(extra);
869
870         for (p = strtok(s, " \t"); p; p = strtok(NULL, " \t"))
871         {
872                 tmp = realloc(r->argv, (r->argc + 1) * sizeof(*r->argv));
873
874                 if (!tmp)
875                         break;
876
877                 r->argv = tmp;
878                 r->argv[r->argc++] = fw3_strdup(p);
879         }
880
881         free(s);
882 }
883
884 static void
885 rule_print6(struct ip6t_entry *e)
886 {
887         char buf[INET6_ADDRSTRLEN];
888         char *pname;
889
890         if (e->ipv6.flags & IP6T_F_PROTO)
891         {
892                 if (e->ipv6.flags & XT_INV_PROTO)
893                         printf(" !");
894
895                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e6));
896
897                 if (pname)
898                         printf(" -p %s", pname);
899                 else
900                         printf(" -p %u", e->ipv6.proto);
901         }
902
903         if (e->ipv6.iniface[0])
904         {
905                 if (e->ipv6.flags & IP6T_INV_VIA_IN)
906                         printf(" !");
907
908                 printf(" -i %s", e->ipv6.iniface);
909         }
910
911         if (e->ipv6.outiface[0])
912         {
913                 if (e->ipv6.flags & IP6T_INV_VIA_OUT)
914                         printf(" !");
915
916                 printf(" -o %s", e->ipv6.outiface);
917         }
918
919         if (memcmp(&e->ipv6.src, &in6addr_any, sizeof(struct in6_addr)))
920         {
921                 if (e->ipv6.flags & IP6T_INV_SRCIP)
922                         printf(" !");
923
924                 printf(" -s %s/%u", inet_ntop(AF_INET6, &e->ipv6.src, buf, sizeof(buf)),
925                                     xtables_ip6mask_to_cidr(&e->ipv6.smsk));
926         }
927
928         if (memcmp(&e->ipv6.dst, &in6addr_any, sizeof(struct in6_addr)))
929         {
930                 if (e->ipv6.flags & IP6T_INV_DSTIP)
931                         printf(" !");
932
933                 printf(" -d %s/%u", inet_ntop(AF_INET6, &e->ipv6.dst, buf, sizeof(buf)),
934                                     xtables_ip6mask_to_cidr(&e->ipv6.dmsk));
935         }
936 }
937
938 static void
939 rule_print4(struct ipt_entry *e)
940 {
941         struct in_addr in_zero = { 0 };
942         char buf[sizeof("255.255.255.255\0")];
943         char *pname;
944
945         if (e->ip.proto)
946         {
947                 if (e->ip.flags & XT_INV_PROTO)
948                         printf(" !");
949
950                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e));
951
952                 if (pname)
953                         printf(" -p %s", pname);
954                 else
955                         printf(" -p %u", e->ip.proto);
956         }
957
958         if (e->ip.iniface[0])
959         {
960                 if (e->ip.flags & IPT_INV_VIA_IN)
961                         printf(" !");
962
963                 printf(" -i %s", e->ip.iniface);
964         }
965
966         if (e->ip.outiface[0])
967         {
968                 if (e->ip.flags & IPT_INV_VIA_OUT)
969                         printf(" !");
970
971                 printf(" -o %s", e->ip.outiface);
972         }
973
974         if (memcmp(&e->ip.src, &in_zero, sizeof(struct in_addr)))
975         {
976                 if (e->ip.flags & IPT_INV_SRCIP)
977                         printf(" !");
978
979                 printf(" -s %s/%u", inet_ntop(AF_INET, &e->ip.src, buf, sizeof(buf)),
980                                     xtables_ipmask_to_cidr(&e->ip.smsk));
981         }
982
983         if (memcmp(&e->ip.dst, &in_zero, sizeof(struct in_addr)))
984         {
985                 if (e->ip.flags & IPT_INV_DSTIP)
986                         printf(" !");
987
988                 printf(" -d %s/%u", inet_ntop(AF_INET, &e->ip.dst, buf, sizeof(buf)),
989                                     xtables_ipmask_to_cidr(&e->ip.dmsk));
990         }
991 }
992
993 static void
994 rule_print(struct fw3_ipt_rule *r, const char *chain)
995 {
996         struct xtables_rule_match *rm;
997         struct xtables_match *m;
998         struct xtables_target *t;
999
1000         debug(r->h, "-A %s", chain);
1001
1002         if (r->h->family == FW3_FAMILY_V6)
1003                 rule_print6(&r->e6);
1004         else
1005                 rule_print4(&r->e);
1006
1007         for (rm = r->matches; rm; rm = rm->next)
1008         {
1009                 m = rm->match;
1010                 printf(" -m %s", fw3_xt_get_match_name(m));
1011
1012                 if (m->save)
1013                         m->save(&r->e.ip, m->m);
1014         }
1015
1016         if (r->target)
1017         {
1018                 t = r->target;
1019                 printf(" -j %s", fw3_xt_get_target_name(t));
1020
1021                 if (t->save)
1022                         t->save(&r->e.ip, t->t);
1023         }
1024
1025         printf("\n");
1026 }
1027
1028 static bool
1029 parse_option(struct fw3_ipt_rule *r, int optc, bool inv)
1030 {
1031         struct xtables_rule_match *m;
1032         struct xtables_match *em;
1033
1034         /* is a target option */
1035         if (r->target && fw3_xt_has_target_parse(r->target) &&
1036                 optc >= r->target->option_offset &&
1037                 optc < (r->target->option_offset + 256))
1038         {
1039                 xtables_option_tpcall(optc, r->argv, inv, r->target, &r->e);
1040                 return false;
1041         }
1042
1043         /* try to dispatch argument to one of the match parsers */
1044         for (m = r->matches; m; m = m->next)
1045         {
1046                 em = m->match;
1047
1048                 if (m->completed || !fw3_xt_has_match_parse(em))
1049                         continue;
1050
1051                 if (optc < em->option_offset ||
1052                         optc >= (em->option_offset + 256))
1053                         continue;
1054
1055                 xtables_option_mpcall(optc, r->argv, inv, em, &r->e);
1056                 return false;
1057         }
1058
1059         /* unhandled option, might belong to a protocol match */
1060         if ((em = load_protomatch(r)) != NULL)
1061         {
1062                 init_match(r, em, false);
1063
1064                 r->protocol_loaded = true;
1065                 optind--;
1066
1067                 return true;
1068         }
1069
1070         if (optc == ':')
1071                 fprintf(stderr, "parse_option(): option '%s' needs argument\n",
1072                         r->argv[optind-1]);
1073
1074         if (optc == '?')
1075                 fprintf(stderr, "parse_option(): unknown option '%s'\n",
1076                         r->argv[optind-1]);
1077
1078         return false;
1079 }
1080
1081 void
1082 fw3_ipt_rule_addarg(struct fw3_ipt_rule *r, bool inv,
1083                     const char *k, const char *v)
1084 {
1085         int n;
1086         char **tmp;
1087
1088         if (!k)
1089                 return;
1090
1091         n = inv + !!k + !!v;
1092         tmp = realloc(r->argv, (r->argc + n) * sizeof(*tmp));
1093
1094         if (!tmp)
1095                 return;
1096
1097         r->argv = tmp;
1098
1099         if (inv)
1100                 r->argv[r->argc++] = fw3_strdup("!");
1101
1102         r->argv[r->argc++] = fw3_strdup(k);
1103
1104         if (v)
1105                 r->argv[r->argc++] = fw3_strdup(v);
1106 }
1107
1108 void
1109 fw3_ipt_rule_append(struct fw3_ipt_rule *r, const char *fmt, ...)
1110 {
1111         size_t s;
1112         struct xtables_rule_match *m;
1113         struct xtables_match *em;
1114         struct xtables_target *et;
1115         struct xtables_globals *g;
1116         struct ipt_entry *e;
1117         struct ip6t_entry *e6;
1118
1119         int i, optc;
1120         bool inv = false;
1121         char buf[32];
1122         va_list ap;
1123
1124         va_start(ap, fmt);
1125         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
1126         va_end(ap);
1127
1128         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
1129         g->opts = g->orig_opts;
1130
1131         optind = 0;
1132         opterr = 0;
1133
1134         while ((optc = getopt_long(r->argc, r->argv, "m:j:", g->opts, NULL)) != -1)
1135         {
1136                 switch (optc)
1137                 {
1138                 case 'm':
1139                         em = find_match(r, optarg);
1140
1141                         if (!em)
1142                         {
1143                                 fprintf(stderr, "fw3_ipt_rule_append(): Can't find match '%s'\n", optarg);
1144                                 goto free;
1145                         }
1146
1147                         init_match(r, em, true);
1148                         break;
1149
1150                 case 'j':
1151                         et = get_target(r, optarg);
1152
1153                         if (!et)
1154                         {
1155                                 fprintf(stderr, "fw3_ipt_rule_append(): Can't find target '%s'\n", optarg);
1156                                 goto free;
1157                         }
1158
1159                         break;
1160
1161                 case 1:
1162                         if ((optarg[0] == '!') && (optarg[1] == '\0'))
1163                         {
1164                                 inv = true;
1165                                 continue;
1166                         }
1167
1168                         fprintf(stderr, "fw3_ipt_rule_append(): Bad argument '%s'\n", optarg);
1169                         return;
1170
1171                 default:
1172                         if (parse_option(r, optc, inv))
1173                                 continue;
1174                         break;
1175                 }
1176
1177                 inv = false;
1178         }
1179
1180         for (m = r->matches; m; m = m->next)
1181                 xtables_option_mfcall(m->match);
1182
1183         if (r->target)
1184                 xtables_option_tfcall(r->target);
1185
1186         if (fw3_pr_debug)
1187                 rule_print(r, buf);
1188
1189         if (r->h->family == FW3_FAMILY_V6)
1190         {
1191                 s = XT_ALIGN(sizeof(struct ip6t_entry));
1192
1193                 for (m = r->matches; m; m = m->next)
1194                         s += m->match->m->u.match_size;
1195
1196                 e6 = fw3_alloc(s + r->target->t->u.target_size);
1197
1198                 memcpy(e6, &r->e6, sizeof(struct ip6t_entry));
1199
1200                 e6->target_offset = s;
1201                 e6->next_offset = s + r->target->t->u.target_size;
1202
1203                 s = 0;
1204
1205                 for (m = r->matches; m; m = m->next)
1206                 {
1207                         memcpy(e6->elems + s, m->match->m, m->match->m->u.match_size);
1208                         s += m->match->m->u.match_size;
1209                 }
1210
1211                 memcpy(e6->elems + s, r->target->t, r->target->t->u.target_size);
1212                 ip6tc_append_entry(buf, e6, r->h->handle);
1213                 free(e6);
1214         }
1215         else
1216         {
1217                 s = XT_ALIGN(sizeof(struct ipt_entry));
1218
1219                 for (m = r->matches; m; m = m->next)
1220                         s += m->match->m->u.match_size;
1221
1222                 e = fw3_alloc(s + r->target->t->u.target_size);
1223
1224                 memcpy(e, &r->e, sizeof(struct ipt_entry));
1225
1226                 e->target_offset = s;
1227                 e->next_offset = s + r->target->t->u.target_size;
1228
1229                 s = 0;
1230
1231                 for (m = r->matches; m; m = m->next)
1232                 {
1233                         memcpy(e->elems + s, m->match->m, m->match->m->u.match_size);
1234                         s += m->match->m->u.match_size;
1235                 }
1236
1237                 memcpy(e->elems + s, r->target->t, r->target->t->u.target_size);
1238
1239                 if (!iptc_append_entry(buf, e, r->h->handle))
1240                         fprintf(stderr, "iptc_append_entry(): %s\n", iptc_strerror(errno));
1241
1242                 free(e);
1243         }
1244
1245 free:
1246         for (i = 1; i < r->argc; i++)
1247                 free(r->argv[i]);
1248
1249         free(r->argv);
1250
1251         xtables_rule_matches_free(&r->matches);
1252
1253         if (r->target)
1254                 free(r->target->t);
1255
1256         free(r);
1257
1258         /* reset all targets and matches */
1259         for (em = xtables_matches; em; em = em->next)
1260                 em->mflags = 0;
1261
1262         for (et = xtables_targets; et; et = et->next)
1263         {
1264                 et->tflags = 0;
1265                 et->used = 0;
1266         }
1267
1268         xtables_free_opts(1);
1269 }
1270
1271 struct fw3_ipt_rule *
1272 fw3_ipt_rule_create(struct fw3_ipt_handle *handle, struct fw3_protocol *proto,
1273                     struct fw3_device *in, struct fw3_device *out,
1274                     struct fw3_address *src, struct fw3_address *dest)
1275 {
1276         struct fw3_ipt_rule *r;
1277
1278         r = fw3_ipt_rule_new(handle);
1279
1280         fw3_ipt_rule_proto(r, proto);
1281         fw3_ipt_rule_in_out(r, in, out);
1282         fw3_ipt_rule_src_dest(r, src, dest);
1283
1284         return r;
1285 }