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