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