Commit 7e95a8db authored by Arturo Borrero Gonzalez's avatar Arturo Borrero Gonzalez
Browse files

Imported Upstream version 1.4.21

parents
.TH iptables-extensions 8 "" "@PACKAGE_STRING@" "@PACKAGE_STRING@"
.SH NAME
iptables-extensions \(em list of extensions in the standard iptables distribution
.SH SYNOPSIS
\fBip6tables\fP [\fB\-m\fP \fIname\fP [\fImodule-options\fP...]]
[\fB\-j\fP \fItarget-name\fP [\fItarget-options\fP...]
.PP
\fBiptables\fP [\fB\-m\fP \fIname\fP [\fImodule-options\fP...]]
[\fB\-j\fP \fItarget-name\fP [\fItarget-options\fP...]
.SH MATCH EXTENSIONS
iptables can use extended packet matching modules
with the \fB\-m\fP or \fB\-\-match\fP
options, followed by the matching module name; after these, various
extra command line options become available, depending on the specific
module. You can specify multiple extended match modules in one line,
and you can use the \fB\-h\fP or \fB\-\-help\fP
options after the module has been specified to receive help specific
to that module. The extended match modules are evaluated in the order
they are specified in the rule.
.PP
If the \fB\-p\fP or \fB\-\-protocol\fP was specified and if and only if an
unknown option is encountered, iptables will try load a match module of the
same name as the protocol, to try making the option available.
.\" @MATCH@
.SH TARGET EXTENSIONS
iptables can use extended target modules: the following are included
in the standard distribution.
.\" @TARGET@
#ifndef _IPTABLES_MULTI_H
#define _IPTABLES_MULTI_H 1
extern int iptables_main(int, char **);
extern int iptables_save_main(int, char **);
extern int iptables_restore_main(int, char **);
#endif /* _IPTABLES_MULTI_H */
.TH IPTABLES-RESTORE 8 "" "@PACKAGE_STRING@" "@PACKAGE_STRING@"
.\"
.\" Man page written by Harald Welte <laforge@gnumonks.org>
.\" It is based on the iptables man page.
.\"
.\" This program is free software; you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation; either version 2 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program; if not, write to the Free Software
.\" Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
.\"
.\"
.SH NAME
iptables-restore \(em Restore IP Tables
.P
ip6tables-restore \(em Restore IPv6 Tables
.SH SYNOPSIS
\fBiptables\-restore\fP [\fB\-chntv\fP] [\fB\-M\fP \fImodprobe\fP]
.P
\fBip6tables\-restore\fP [\fB\-chntv\fP] [\fB\-M\fP \fImodprobe\fP]
[\fB\-T\fP \fIname\fP]
.SH DESCRIPTION
.PP
.B iptables-restore
and
.B ip6tables-restore
are used to restore IP and IPv6 Tables from data specified on STDIN. Use
I/O redirection provided by your shell to read from a file
.TP
\fB\-c\fR, \fB\-\-counters\fR
restore the values of all packet and byte counters
.TP
\fB\-h\fP, \fB\-\-help\fP
Print a short option summary.
.TP
\fB\-n\fR, \fB\-\-noflush\fR
don't flush the previous contents of the table. If not specified,
both commands flush (delete) all previous contents of the respective table.
.TP
\fB\-t\fP, \fB\-\-test\fP
Only parse and construct the ruleset, but do not commit it.
.TP
\fB\-v\fP, \fB\-\-verbose\fP
Print additional debug info during ruleset processing.
.TP
\fB\-M\fP, \fB\-\-modprobe\fP \fImodprobe_program\fP
Specify the path to the modprobe program. By default, iptables-restore will
inspect /proc/sys/kernel/modprobe to determine the executable's path.
.TP
\fB\-T\fP, \fB\-\-table\fP \fIname\fP
Restore only the named table even if the input stream contains other ones.
.SH BUGS
None known as of iptables-1.2.1 release
.SH AUTHORS
Harald Welte <laforge@gnumonks.org> wrote iptables-restore based on code
from Rusty Russell.
.br
Andras Kis-Szabo <kisza@sch.bme.hu> contributed ip6tables-restore.
.SH SEE ALSO
\fBiptables\-save\fP(8), \fBiptables\fP(8)
.PP
The iptables-HOWTO, which details more iptables usage, the NAT-HOWTO,
which details NAT, and the netfilter-hacking-HOWTO which details the
internals.
/* Code to restore the iptables state, from file by iptables-save.
* (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
* based on previous code from Rusty Russell <rusty@linuxcare.com.au>
*
* This code is distributed under the terms of GNU GPL v2
*/
#include <getopt.h>
#include <sys/errno.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "iptables.h"
#include "xtables.h"
#include "libiptc/libiptc.h"
#include "iptables-multi.h"
#ifdef DEBUG
#define DEBUGP(x, args...) fprintf(stderr, x, ## args)
#else
#define DEBUGP(x, args...)
#endif
static int binary = 0, counters = 0, verbose = 0, noflush = 0;
/* Keeping track of external matches and targets. */
static const struct option options[] = {
{.name = "binary", .has_arg = false, .val = 'b'},
{.name = "counters", .has_arg = false, .val = 'c'},
{.name = "verbose", .has_arg = false, .val = 'v'},
{.name = "test", .has_arg = false, .val = 't'},
{.name = "help", .has_arg = false, .val = 'h'},
{.name = "noflush", .has_arg = false, .val = 'n'},
{.name = "modprobe", .has_arg = true, .val = 'M'},
{.name = "table", .has_arg = true, .val = 'T'},
{NULL},
};
static void print_usage(const char *name, const char *version) __attribute__((noreturn));
#define prog_name iptables_globals.program_name
static void print_usage(const char *name, const char *version)
{
fprintf(stderr, "Usage: %s [-b] [-c] [-v] [-t] [-h]\n"
" [ --binary ]\n"
" [ --counters ]\n"
" [ --verbose ]\n"
" [ --test ]\n"
" [ --help ]\n"
" [ --noflush ]\n"
" [ --table=<TABLE> ]\n"
" [ --modprobe=<command>]\n", name);
exit(1);
}
static struct xtc_handle *create_handle(const char *tablename)
{
struct xtc_handle *handle;
handle = iptc_init(tablename);
if (!handle) {
/* try to insmod the module if iptc_init failed */
xtables_load_ko(xtables_modprobe_program, false);
handle = iptc_init(tablename);
}
if (!handle) {
xtables_error(PARAMETER_PROBLEM, "%s: unable to initialize "
"table '%s'\n", prog_name, tablename);
exit(1);
}
return handle;
}
static int parse_counters(char *string, struct xt_counters *ctr)
{
unsigned long long pcnt, bcnt;
int ret;
ret = sscanf(string, "[%llu:%llu]", &pcnt, &bcnt);
ctr->pcnt = pcnt;
ctr->bcnt = bcnt;
return ret == 2;
}
/* global new argv and argc */
static char *newargv[255];
static int newargc;
/* function adding one argument to newargv, updating newargc
* returns true if argument added, false otherwise */
static int add_argv(char *what) {
DEBUGP("add_argv: %s\n", what);
if (what && newargc + 1 < ARRAY_SIZE(newargv)) {
newargv[newargc] = strdup(what);
newargv[++newargc] = NULL;
return 1;
} else {
xtables_error(PARAMETER_PROBLEM,
"Parser cannot handle more arguments\n");
return 0;
}
}
static void free_argv(void) {
int i;
for (i = 0; i < newargc; i++)
free(newargv[i]);
}
static void add_param_to_argv(char *parsestart)
{
int quote_open = 0, escaped = 0, param_len = 0;
char param_buffer[1024], *curchar;
/* After fighting with strtok enough, here's now
* a 'real' parser. According to Rusty I'm now no
* longer a real hacker, but I can live with that */
for (curchar = parsestart; *curchar; curchar++) {
if (quote_open) {
if (escaped) {
param_buffer[param_len++] = *curchar;
escaped = 0;
continue;
} else if (*curchar == '\\') {
escaped = 1;
continue;
} else if (*curchar == '"') {
quote_open = 0;
*curchar = ' ';
} else {
param_buffer[param_len++] = *curchar;
continue;
}
} else {
if (*curchar == '"') {
quote_open = 1;
continue;
}
}
if (*curchar == ' '
|| *curchar == '\t'
|| * curchar == '\n') {
if (!param_len) {
/* two spaces? */
continue;
}
param_buffer[param_len] = '\0';
/* check if table name specified */
if (!strncmp(param_buffer, "-t", 2)
|| !strncmp(param_buffer, "--table", 8)) {
xtables_error(PARAMETER_PROBLEM,
"The -t option (seen in line %u) cannot be "
"used in iptables-restore.\n", line);
exit(1);
}
add_argv(param_buffer);
param_len = 0;
} else {
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
"Parameter too long!");
}
}
}
int
iptables_restore_main(int argc, char *argv[])
{
struct xtc_handle *handle = NULL;
char buffer[10240];
int c;
char curtable[XT_TABLE_MAXNAMELEN + 1];
FILE *in;
int in_table = 0, testing = 0;
const char *tablename = NULL;
const struct xtc_ops *ops = &iptc_ops;
line = 0;
iptables_globals.program_name = "iptables-restore";
c = xtables_init_all(&iptables_globals, NFPROTO_IPV4);
if (c < 0) {
fprintf(stderr, "%s/%s Failed to initialize xtables\n",
iptables_globals.program_name,
iptables_globals.program_version);
exit(1);
}
#if defined(ALL_INCLUSIVE) || defined(NO_SHARED_LIBS)
init_extensions();
init_extensions4();
#endif
while ((c = getopt_long(argc, argv, "bcvthnM:T:", options, NULL)) != -1) {
switch (c) {
case 'b':
binary = 1;
break;
case 'c':
counters = 1;
break;
case 'v':
verbose = 1;
break;
case 't':
testing = 1;
break;
case 'h':
print_usage("iptables-restore",
IPTABLES_VERSION);
break;
case 'n':
noflush = 1;
break;
case 'M':
xtables_modprobe_program = optarg;
break;
case 'T':
tablename = optarg;
break;
}
}
if (optind == argc - 1) {
in = fopen(argv[optind], "re");
if (!in) {
fprintf(stderr, "Can't open %s: %s\n", argv[optind],
strerror(errno));
exit(1);
}
}
else if (optind < argc) {
fprintf(stderr, "Unknown arguments found on commandline\n");
exit(1);
}
else in = stdin;
/* Grab standard input. */
while (fgets(buffer, sizeof(buffer), in)) {
int ret = 0;
line++;
if (buffer[0] == '\n')
continue;
else if (buffer[0] == '#') {
if (verbose)
fputs(buffer, stdout);
continue;
} else if ((strcmp(buffer, "COMMIT\n") == 0) && (in_table)) {
if (!testing) {
DEBUGP("Calling commit\n");
ret = ops->commit(handle);
ops->free(handle);
handle = NULL;
} else {
DEBUGP("Not calling commit, testing\n");
ret = 1;
}
in_table = 0;
} else if ((buffer[0] == '*') && (!in_table)) {
/* New table */
char *table;
table = strtok(buffer+1, " \t\n");
DEBUGP("line %u, table '%s'\n", line, table);
if (!table) {
xtables_error(PARAMETER_PROBLEM,
"%s: line %u table name invalid\n",
xt_params->program_name, line);
exit(1);
}
strncpy(curtable, table, XT_TABLE_MAXNAMELEN);
curtable[XT_TABLE_MAXNAMELEN] = '\0';
if (tablename && (strcmp(tablename, table) != 0))
continue;
if (handle)
ops->free(handle);
handle = create_handle(table);
if (noflush == 0) {
DEBUGP("Cleaning all chains of table '%s'\n",
table);
for_each_chain4(flush_entries4, verbose, 1,
handle);
DEBUGP("Deleting all user-defined chains "
"of table '%s'\n", table);
for_each_chain4(delete_chain4, verbose, 0,
handle);
}
ret = 1;
in_table = 1;
} else if ((buffer[0] == ':') && (in_table)) {
/* New chain. */
char *policy, *chain;
chain = strtok(buffer+1, " \t\n");
DEBUGP("line %u, chain '%s'\n", line, chain);
if (!chain) {
xtables_error(PARAMETER_PROBLEM,
"%s: line %u chain name invalid\n",
xt_params->program_name, line);
exit(1);
}
if (strlen(chain) >= XT_EXTENSION_MAXNAMELEN)
xtables_error(PARAMETER_PROBLEM,
"Invalid chain name `%s' "
"(%u chars max)",
chain, XT_EXTENSION_MAXNAMELEN - 1);
if (ops->builtin(chain, handle) <= 0) {
if (noflush && ops->is_chain(chain, handle)) {
DEBUGP("Flushing existing user defined chain '%s'\n", chain);
if (!ops->flush_entries(chain, handle))
xtables_error(PARAMETER_PROBLEM,
"error flushing chain "
"'%s':%s\n", chain,
strerror(errno));
} else {
DEBUGP("Creating new chain '%s'\n", chain);
if (!ops->create_chain(chain, handle))
xtables_error(PARAMETER_PROBLEM,
"error creating chain "
"'%s':%s\n", chain,
strerror(errno));
}
}
policy = strtok(NULL, " \t\n");
DEBUGP("line %u, policy '%s'\n", line, policy);
if (!policy) {
xtables_error(PARAMETER_PROBLEM,
"%s: line %u policy invalid\n",
xt_params->program_name, line);
exit(1);
}
if (strcmp(policy, "-") != 0) {
struct xt_counters count;
if (counters) {
char *ctrs;
ctrs = strtok(NULL, " \t\n");
if (!ctrs || !parse_counters(ctrs, &count))
xtables_error(PARAMETER_PROBLEM,
"invalid policy counters "
"for chain '%s'\n", chain);
} else {
memset(&count, 0, sizeof(count));
}
DEBUGP("Setting policy of chain %s to %s\n",
chain, policy);
if (!ops->set_policy(chain, policy, &count,
handle))
xtables_error(OTHER_PROBLEM,
"Can't set policy `%s'"
" on `%s' line %u: %s\n",
policy, chain, line,
ops->strerror(errno));
}
ret = 1;
} else if (in_table) {
int a;
char *ptr = buffer;
char *pcnt = NULL;
char *bcnt = NULL;
char *parsestart;
/* reset the newargv */
newargc = 0;
if (buffer[0] == '[') {
/* we have counters in our input */
ptr = strchr(buffer, ']');
if (!ptr)
xtables_error(PARAMETER_PROBLEM,
"Bad line %u: need ]\n",
line);
pcnt = strtok(buffer+1, ":");
if (!pcnt)
xtables_error(PARAMETER_PROBLEM,
"Bad line %u: need :\n",
line);
bcnt = strtok(NULL, "]");
if (!bcnt)
xtables_error(PARAMETER_PROBLEM,
"Bad line %u: need ]\n",
line);
/* start command parsing after counter */
parsestart = ptr + 1;
} else {
/* start command parsing at start of line */
parsestart = buffer;
}
add_argv(argv[0]);
add_argv("-t");
add_argv(curtable);
if (counters && pcnt && bcnt) {
add_argv("--set-counters");
add_argv((char *) pcnt);
add_argv((char *) bcnt);
}
add_param_to_argv(parsestart);
DEBUGP("calling do_command4(%u, argv, &%s, handle):\n",
newargc, curtable);
for (a = 0; a < newargc; a++)
DEBUGP("argv[%u]: %s\n", a, newargv[a]);
ret = do_command4(newargc, newargv,
&newargv[2], &handle, true);
free_argv();
fflush(stdout);
}
if (tablename && (strcmp(tablename, curtable) != 0))
continue;
if (!ret) {
fprintf(stderr, "%s: line %u failed\n",
xt_params->program_name, line);
exit(1);
}
}
if (in_table) {
fprintf(stderr, "%s: COMMIT expected at line %u\n",
xt_params->program_name, line + 1);
exit(1);
}
fclose(in);
return 0;
}
.TH IPTABLES-SAVE 8 "" "@PACKAGE_STRING@" "@PACKAGE_STRING@"
.\"
.\" Man page written by Harald Welte <laforge@gnumonks.org>
.\" It is based on the iptables man page.
.\"
.\" This program is free software; you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation; either version 2 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program; if not, write to the Free Software
.\" Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
.\"
.\"
.SH NAME
iptables-save \(em dump iptables rules to stdout
.P
ip6tables-save \(em dump iptables rules to stdout
.SH SYNOPSIS
\fBiptables\-save\fP [\fB\-M\fP \fImodprobe\fP] [\fB\-c\fP]
[\fB\-t\fP \fItable\fP]
.P
\fBip6tables\-save\fP [\fB\-M\fP \fImodprobe\fP] [\fB\-c\fP]
[\fB\-t\fP \fItable\fP
.SH DESCRIPTION
.PP
.B iptables-save
and
.B ip6tables-save
are used to dump the contents of IP or IPv6 Table in easily parseable format
to STDOUT. Use I/O-redirection provided by your shell to write to a file.
.TP
\fB\-M\fP \fImodprobe_program\fP
Specify the path to the modprobe program. By default, iptables-save will
inspect /proc/sys/kernel/modprobe to determine the executable's path.
.TP
\fB\-c\fR, \fB\-\-counters\fR
include the current values of all packet and byte counters in the output
.TP
\fB\-t\fR, \fB\-\-table\fR \fItablename\fP
restrict output to only one table. If not specified, output includes all
available tables.
.SH BUGS
None known as of iptables-1.2.1 release
.SH AUTHORS
Harald Welte <laforge@gnumonks.org>
.br
Rusty Russell <rusty@rustcorp.com.au>
.br
Andras Kis-Szabo <kisza@sch.bme.hu> contributed ip6tables-save.
.SH SEE ALSO
\fBiptables\-restore\fP(8), \fBiptables\fP(8)
.PP
The iptables-HOWTO, which details more iptables usage, the NAT-HOWTO,
which details NAT, and the netfilter-hacking-HOWTO which details the
internals.
/* Code to save the iptables state, in human readable-form. */
/* (C) 1999 by Paul 'Rusty' Russell <rusty@rustcorp.com.au> and
* (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
*
* This code is distributed under the terms of GNU GPL v2
*
*/
#include <getopt.h>
#include <sys/errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <netdb.h>
#include "libiptc/libiptc.h"
#include "iptables.h"
#include "iptables-multi.h"
#ifndef NO_SHARED_LIBS
#include <dlfcn.h>
#endif
static int show_counters = 0;
static const struct option options[] = {
{.name = "counters", .has_arg = false, .val = 'c'},
{.name = "dump", .has_arg = false, .val = 'd'},
{.name = "table", .has_arg = true, .val = 't'},
{.name = "modprobe", .has_arg = true, .val = 'M'},
{NULL},
};
/* Debugging prototype. */
static int for_each_table(int (*func)(const char *tablename))
{
int ret = 1;
FILE *procfile = NULL;
char tablename[XT_TABLE_MAXNAMELEN+1];
procfile = fopen("/proc/net/ip_tables_names", "re");
if (!procfile)
return ret;
while (fgets(tablename, sizeof(tablename), procfile)) {
if (tablename[strlen(tablename) - 1] != '\n')
xtables_error(OTHER_PROBLEM,
"Badly formed tablename `%s'\n",
tablename);
tablename[strlen(tablename) - 1] = '\0';
ret &= func(tablename);
}
fclose(procfile);
return ret;
}
static int do_output(const char *tablename)
{
struct xtc_handle *h;
const char *chain = NULL;
if (!tablename)
return for_each_table(&do_output);
h = iptc_init(tablename);
if (h == NULL) {
xtables_load_ko(xtables_modprobe_program, false);
h = iptc_init(tablename);
}
if (!h)
xtables_error(OTHER_PROBLEM, "Cannot initialize: %s\n",
iptc_strerror(errno));
time_t now = time(NULL);
printf("# Generated by iptables-save v%s on %s",
IPTABLES_VERSION, ctime(&now));
printf("*%s\n", tablename);
/* Dump out chain names first,
* thereby preventing dependency conflicts */
for (chain = iptc_first_chain(h);
chain;
chain = iptc_next_chain(h)) {
printf(":%s ", chain);
if (iptc_builtin(chain, h)) {
struct xt_counters count;
printf("%s ",
iptc_get_policy(chain, &count, h));
printf("[%llu:%llu]\n", (unsigned long long)count.pcnt, (unsigned long long)count.bcnt);
} else {
printf("- [0:0]\n");
}
}
for (chain = iptc_first_chain(h);
chain;
chain = iptc_next_chain(h)) {
const struct ipt_entry *e;
/* Dump out rules */
e = iptc_first_rule(chain, h);
while(e) {
print_rule4(e, h, chain, show_counters);
e = iptc_next_rule(e, h);
}
}
now = time(NULL);
printf("COMMIT\n");
printf("# Completed on %s", ctime(&now));
iptc_free(h);
return 1;
}
/* Format:
* :Chain name POLICY packets bytes
* rule
*/
int
iptables_save_main(int argc, char *argv[])
{
const char *tablename = NULL;
int c;
iptables_globals.program_name = "iptables-save";
c = xtables_init_all(&iptables_globals, NFPROTO_IPV4);
if (c < 0) {
fprintf(stderr, "%s/%s Failed to initialize xtables\n",
iptables_globals.program_name,
iptables_globals.program_version);
exit(1);
}
#if defined(ALL_INCLUSIVE) || defined(NO_SHARED_LIBS)
init_extensions();
init_extensions4();
#endif
while ((c = getopt_long(argc, argv, "bcdt:", options, NULL)) != -1) {
switch (c) {
case 'c':
show_counters = 1;
break;
case 't':
/* Select specific table. */
tablename = optarg;
break;
case 'M':
xtables_modprobe_program = optarg;
break;
case 'd':
do_output(tablename);
exit(0);
}
}
if (optind < argc) {
fprintf(stderr, "Unknown arguments found on commandline\n");
exit(1);
}
return !do_output(tablename);
}
/*
* Author: Paul.Russell@rustcorp.com.au and mneuling@radlogic.com.au
*
* Based on the ipchains code by Paul Russell and Michael Neuling
*
* (C) 2000-2002 by the netfilter coreteam <coreteam@netfilter.org>:
* Paul 'Rusty' Russell <rusty@rustcorp.com.au>
* Marc Boucher <marc+nf@mbsi.ca>
* James Morris <jmorris@intercode.com.au>
* Harald Welte <laforge@gnumonks.org>
* Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* iptables -- IP firewall administration for kernels with
* firewall table (aimed for the 2.3 kernels)
*
* See the accompanying manual page iptables(8) for information
* about proper usage of this program.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <iptables.h>
#include "iptables-multi.h"
int
iptables_main(int argc, char *argv[])
{
int ret;
char *table = "filter";
struct xtc_handle *handle = NULL;
iptables_globals.program_name = "iptables";
ret = xtables_init_all(&iptables_globals, NFPROTO_IPV4);
if (ret < 0) {
fprintf(stderr, "%s/%s Failed to initialize xtables\n",
iptables_globals.program_name,
iptables_globals.program_version);
exit(1);
}
#if defined(ALL_INCLUSIVE) || defined(NO_SHARED_LIBS)
init_extensions();
init_extensions4();
#endif
ret = do_command4(argc, argv, &table, &handle, false);
if (ret) {
ret = iptc_commit(handle);
iptc_free(handle);
}
if (!ret) {
if (errno == EINVAL) {
fprintf(stderr, "iptables: %s. "
"Run `dmesg' for more information.\n",
iptc_strerror(errno));
} else {
fprintf(stderr, "iptables: %s.\n",
iptc_strerror(errno));
}
if (errno == EAGAIN) {
exit(RESOURCE_PROBLEM);
}
}
exit(!ret);
}
.TH IPTABLES-XML 1 "" "@PACKAGE_STRING@" "@PACKAGE_STRING@"
.\"
.\" Man page written by Sam Liddicott <azez@ufomechanic.net>
.\" It is based on the iptables-save man page.
.\"
.\" This program is free software; you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation; either version 2 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program; if not, write to the Free Software
.\" Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
.\"
.\"
.SH NAME
iptables-xml \(em Convert iptables-save format to XML
.SH SYNOPSIS
\fBiptables\-xml\fP [\fB\-c\fP] [\fB\-v\fP]
.SH DESCRIPTION
.PP
.B iptables-xml
is used to convert the output of iptables-save into an easily manipulatable
XML format to STDOUT. Use I/O-redirection provided by your shell to write to
a file.
.TP
\fB\-c\fR, \fB\-\-combine\fR
combine consecutive rules with the same matches but different targets. iptables
does not currently support more than one target per match, so this simulates
that by collecting the targets from consecutive iptables rules into one action
tag, but only when the rule matches are identical. Terminating actions like
RETURN, DROP, ACCEPT and QUEUE are not combined with subsequent targets.
.TP
\fB\-v\fR, \fB\-\-verbose\fR
Output xml comments containing the iptables line from which the XML is derived
.PP
iptables-xml does a mechanistic conversion to a very expressive xml
format; the only semantic considerations are for \-g and \-j targets in
order to discriminate between <call> <goto> and <nane-of-target> as it
helps xml processing scripts if they can tell the difference between a
target like SNAT and another chain.
Some sample output is:
<iptables-rules>
<table name="mangle">
<chain name="PREROUTING" policy="ACCEPT" packet-count="63436"
byte-count="7137573">
<rule>
<conditions>
<match>
<p>tcp</p>
</match>
<tcp>
<sport>8443</sport>
</tcp>
</conditions>
<actions>
<call>
<check_ip/>
</call>
<ACCEPT/>
</actions>
</rule>
</chain>
</table>
</iptables-rules>
.PP
Conversion from XML to iptables-save format may be done using the
iptables.xslt script and xsltproc, or a custom program using
libxsltproc or similar; in this fashion:
xsltproc iptables.xslt my-iptables.xml | iptables-restore
.SH BUGS
None known as of iptables-1.3.7 release
.SH AUTHOR
Sam Liddicott <azez@ufomechanic.net>
.SH SEE ALSO
\fBiptables\-save\fP(8), \fBiptables\-restore\fP(8), \fBiptables\fP(8)
/* Code to convert iptables-save format to xml format,
* (C) 2006 Ufo Mechanic <azez@ufomechanic.net>
* based on iptables-restore (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
* based on previous code from Rusty Russell <rusty@linuxcare.com.au>
*
* This code is distributed under the terms of GNU GPL v2
*/
#include <getopt.h>
#include <sys/errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "iptables.h"
#include "libiptc/libiptc.h"
#include "xtables-multi.h"
#include <xtables.h>
#ifdef DEBUG
#define DEBUGP(x, args...) fprintf(stderr, x, ## args)
#else
#define DEBUGP(x, args...)
#endif
struct xtables_globals iptables_xml_globals = {
.option_offset = 0,
.program_version = IPTABLES_VERSION,
.program_name = "iptables-xml",
};
#define prog_name iptables_xml_globals.program_name
#define prog_vers iptables_xml_globals.program_version
static void print_usage(const char *name, const char *version)
__attribute__ ((noreturn));
static int verbose = 0;
/* Whether to combine actions of sequential rules with identical conditions */
static int combine = 0;
/* Keeping track of external matches and targets. */
static struct option options[] = {
{"verbose", 0, NULL, 'v'},
{"combine", 0, NULL, 'c'},
{"help", 0, NULL, 'h'},
{ .name = NULL }
};
static void
print_usage(const char *name, const char *version)
{
fprintf(stderr, "Usage: %s [-c] [-v] [-h]\n"
" [--combine ]\n"
" [ --verbose ]\n" " [ --help ]\n", name);
exit(1);
}
static int
parse_counters(char *string, struct xt_counters *ctr)
{
__u64 *pcnt, *bcnt;
if (string != NULL) {
pcnt = &ctr->pcnt;
bcnt = &ctr->bcnt;
return (sscanf
(string, "[%llu:%llu]",
(unsigned long long *)pcnt,
(unsigned long long *)bcnt) == 2);
} else
return (0 == 2);
}
/* global new argv and argc */
static char *newargv[255];
static unsigned int newargc = 0;
static char *oldargv[255];
static unsigned int oldargc = 0;
/* arg meta data, were they quoted, frinstance */
static int newargvattr[255];
#define XT_CHAIN_MAXNAMELEN XT_TABLE_MAXNAMELEN
static char closeActionTag[XT_TABLE_MAXNAMELEN + 1];
static char closeRuleTag[XT_TABLE_MAXNAMELEN + 1];
static char curTable[XT_TABLE_MAXNAMELEN + 1];
static char curChain[XT_CHAIN_MAXNAMELEN + 1];
struct chain {
char *chain;
char *policy;
struct xt_counters count;
int created;
};
#define maxChains 10240 /* max chains per table */
static struct chain chains[maxChains];
static int nextChain = 0;
/* funCtion adding one argument to newargv, updating newargc
* returns true if argument added, false otherwise */
static int
add_argv(char *what, int quoted)
{
DEBUGP("add_argv: %d %s\n", newargc, what);
if (what && newargc + 1 < ARRAY_SIZE(newargv)) {
newargv[newargc] = strdup(what);
newargvattr[newargc] = quoted;
newargc++;
return 1;
} else
return 0;
}
static void
free_argv(void)
{
unsigned int i;
for (i = 0; i < newargc; i++) {
free(newargv[i]);
newargv[i] = NULL;
}
newargc = 0;
for (i = 0; i < oldargc; i++) {
free(oldargv[i]);
oldargv[i] = NULL;
}
oldargc = 0;
}
/* save parsed rule for comparison with next rule
to perform action agregation on duplicate conditions */
static void
save_argv(void)
{
unsigned int i;
for (i = 0; i < oldargc; i++)
free(oldargv[i]);
oldargc = newargc;
newargc = 0;
for (i = 0; i < oldargc; i++) {
oldargv[i] = newargv[i];
newargv[i] = NULL;
}
}
/* like puts but with xml encoding */
static void
xmlEncode(char *text)
{
while (text && *text) {
if ((unsigned char) (*text) >= 127)
printf("&#%d;", (unsigned char) (*text));
else if (*text == '&')
printf("&amp;");
else if (*text == '<')
printf("&lt;");
else if (*text == '>')
printf("&gt;");
else if (*text == '"')
printf("&quot;");
else
putchar(*text);
text++;
}
}
/* Output text as a comment, avoiding a double hyphen */
static void
xmlCommentEscape(char *comment)
{
int h_count = 0;
while (comment && *comment) {
if (*comment == '-') {
h_count++;
if (h_count >= 2) {
h_count = 0;
putchar(' ');
}
putchar('*');
}
/* strip trailing newline */
if (*comment == '\n' && *(comment + 1) == 0);
else
putchar(*comment);
comment++;
}
}
static void
xmlComment(char *comment)
{
printf("<!-- ");
xmlCommentEscape(comment);
printf(" -->\n");
}
static void
xmlAttrS(char *name, char *value)
{
printf("%s=\"", name);
xmlEncode(value);
printf("\" ");
}
static void
xmlAttrI(char *name, long long int num)
{
printf("%s=\"%lld\" ", name, num);
}
static void
closeChain(void)
{
if (curChain[0] == 0)
return;
if (closeActionTag[0])
printf("%s\n", closeActionTag);
closeActionTag[0] = 0;
if (closeRuleTag[0])
printf("%s\n", closeRuleTag);
closeRuleTag[0] = 0;
if (curChain[0])
printf(" </chain>\n");
curChain[0] = 0;
//lastRule[0]=0;
}
static void
openChain(char *chain, char *policy, struct xt_counters *ctr, char close)
{
closeChain();
strncpy(curChain, chain, XT_CHAIN_MAXNAMELEN);
curChain[XT_CHAIN_MAXNAMELEN] = '\0';
printf(" <chain ");
xmlAttrS("name", curChain);
if (strcmp(policy, "-") != 0)
xmlAttrS("policy", policy);
xmlAttrI("packet-count", (unsigned long long) ctr->pcnt);
xmlAttrI("byte-count", (unsigned long long) ctr->bcnt);
if (close) {
printf("%c", close);
curChain[0] = 0;
}
printf(">\n");
}
static int
existsChain(char *chain)
{
/* open a saved chain */
int c = 0;
if (0 == strcmp(curChain, chain))
return 1;
for (c = 0; c < nextChain; c++)
if (chains[c].chain && strcmp(chains[c].chain, chain) == 0)
return 1;
return 0;
}
static void
needChain(char *chain)
{
/* open a saved chain */
int c = 0;
if (0 == strcmp(curChain, chain))
return;
for (c = 0; c < nextChain; c++)
if (chains[c].chain && strcmp(chains[c].chain, chain) == 0) {
openChain(chains[c].chain, chains[c].policy,
&(chains[c].count), '\0');
/* And, mark it as done so we don't create
an empty chain at table-end time */
chains[c].created = 1;
}
}
static void
saveChain(char *chain, char *policy, struct xt_counters *ctr)
{
if (nextChain >= maxChains) {
xtables_error(PARAMETER_PROBLEM,
"%s: line %u chain name invalid\n",
prog_name, line);
exit(1);
};
chains[nextChain].chain = strdup(chain);
chains[nextChain].policy = strdup(policy);
chains[nextChain].count = *ctr;
chains[nextChain].created = 0;
nextChain++;
}
static void
finishChains(void)
{
int c;
for (c = 0; c < nextChain; c++)
if (!chains[c].created) {
openChain(chains[c].chain, chains[c].policy,
&(chains[c].count), '/');
free(chains[c].chain);
free(chains[c].policy);
}
nextChain = 0;
}
static void
closeTable(void)
{
closeChain();
finishChains();
if (curTable[0])
printf(" </table>\n");
curTable[0] = 0;
}
static void
openTable(char *table)
{
closeTable();
strncpy(curTable, table, XT_TABLE_MAXNAMELEN);
curTable[XT_TABLE_MAXNAMELEN] = '\0';
printf(" <table ");
xmlAttrS("name", curTable);
printf(">\n");
}
// is char* -j --jump -g or --goto
static int
isTarget(char *arg)
{
return ((arg)
&& (strcmp((arg), "-j") == 0 || strcmp((arg), "--jump") == 0
|| strcmp((arg), "-g") == 0
|| strcmp((arg), "--goto") == 0));
}
// is it a terminating target like -j ACCEPT, etc
// (or I guess -j SNAT in nat table, but we don't check for that yet
static int
isTerminatingTarget(char *arg)
{
return ((arg)
&& (strcmp((arg), "ACCEPT") == 0
|| strcmp((arg), "DROP") == 0
|| strcmp((arg), "QUEUE") == 0
|| strcmp((arg), "RETURN") == 0));
}
// part=-1 means do conditions, part=1 means do rules, part=0 means do both
static void
do_rule_part(char *leveltag1, char *leveltag2, int part, int argc,
char *argv[], int argvattr[])
{
int i;
int arg = 2; // ignore leading -A <chain>
char invert_next = 0;
char *spacer = ""; // space when needed to assemble arguments
char *level1 = NULL;
char *level2 = NULL;
char *leveli1 = " ";
char *leveli2 = " ";
#define CLOSE_LEVEL(LEVEL) \
do { \
if (level ## LEVEL) printf("</%s>\n", \
(leveltag ## LEVEL)?(leveltag ## LEVEL):(level ## LEVEL)); \
level ## LEVEL=NULL;\
} while(0)
#define OPEN_LEVEL(LEVEL,TAG) \
do {\
level ## LEVEL=TAG;\
if (leveltag ## LEVEL) {\
printf("%s<%s ", (leveli ## LEVEL), \
(leveltag ## LEVEL));\
xmlAttrS("type", (TAG)); \
} else printf("%s<%s ", (leveli ## LEVEL), (level ## LEVEL)); \
} while(0)
if (part == 1) { /* skip */
/* use argvattr to tell which arguments were quoted
to avoid comparing quoted arguments, like comments, to -j, */
while (arg < argc && (argvattr[arg] || !isTarget(argv[arg])))
arg++;
}
/* Before we start, if the first arg is -[^-] and not -m or -j or -g
* then start a dummy <match> tag for old style built-in matches.
* We would do this in any case, but no need if it would be empty.
* In the case of negation, we need to look at arg+1
*/
if (arg < argc && strcmp(argv[arg], "!") == 0)
i = arg + 1;
else
i = arg;
if (i < argc && argv[i][0] == '-' && !isTarget(argv[i])
&& strcmp(argv[i], "-m") != 0) {
OPEN_LEVEL(1, "match");
printf(">\n");
}
while (arg < argc) {
// If ! is followed by -* then apply to that else output as data
// Stop, if we need to
if (part == -1 && !argvattr[arg] && (isTarget(argv[arg]))) {
break;
} else if (!argvattr[arg] && strcmp(argv[arg], "!") == 0) {
if ((arg + 1) < argc && argv[arg + 1][0] == '-')
invert_next = '!';
else
printf("%s%s", spacer, argv[arg]);
spacer = " ";
} else if (!argvattr[arg] && isTarget(argv[arg])
&& existsChain(argv[arg + 1])
&& (2 + arg >= argc)) {
if (!((1 + arg) < argc))
// no args to -j, -m or -g, ignore & finish loop
break;
CLOSE_LEVEL(2);
if (level1)
printf("%s", leveli1);
CLOSE_LEVEL(1);
spacer = "";
invert_next = 0;
if (strcmp(argv[arg], "-g") == 0
|| strcmp(argv[arg], "--goto") == 0) {
/* goto user chain */
OPEN_LEVEL(1, "goto");
printf(">\n");
arg++;
OPEN_LEVEL(2, argv[arg]);
printf("/>\n");
level2 = NULL;
} else {
/* call user chain */
OPEN_LEVEL(1, "call");
printf(">\n");
arg++;
OPEN_LEVEL(2, argv[arg]);
printf("/>\n");
level2 = NULL;
}
} else if (!argvattr[arg]
&& (isTarget(argv[arg])
|| strcmp(argv[arg], "-m") == 0
|| strcmp(argv[arg], "--module") == 0)) {
if (!((1 + arg) < argc))
// no args to -j, -m or -g, ignore & finish loop
break;
CLOSE_LEVEL(2);
if (level1)
printf("%s", leveli1);
CLOSE_LEVEL(1);
spacer = "";
invert_next = 0;
arg++;
OPEN_LEVEL(1, (argv[arg]));
// Optimize case, can we close this tag already?
if ((arg + 1) >= argc || (!argvattr[arg + 1]
&& (isTarget(argv[arg + 1])
|| strcmp(argv[arg + 1],
"-m") == 0
|| strcmp(argv[arg + 1],
"--module") ==
0))) {
printf(" />\n");
level1 = NULL;
} else {
printf(">\n");
}
} else if (!argvattr[arg] && argv[arg][0] == '-') {
char *tag;
CLOSE_LEVEL(2);
// Skip past any -
tag = argv[arg];
while (*tag == '-' && *tag)
tag++;
spacer = "";
OPEN_LEVEL(2, tag);
if (invert_next)
printf(" invert=\"1\"");
invert_next = 0;
// Optimize case, can we close this tag already?
if (!((arg + 1) < argc)
|| (argv[arg + 1][0] == '-' /* NOT QUOTED */ )) {
printf(" />\n");
level2 = NULL;
} else {
printf(">");
}
} else { // regular data
char *spaces = strchr(argv[arg], ' ');
printf("%s", spacer);
if (spaces || argvattr[arg])
printf("&quot;");
// if argv[arg] contains a space, enclose in quotes
xmlEncode(argv[arg]);
if (spaces || argvattr[arg])
printf("&quot;");
spacer = " ";
}
arg++;
}
CLOSE_LEVEL(2);
if (level1)
printf("%s", leveli1);
CLOSE_LEVEL(1);
}
static int
compareRules(void)
{
/* compare arguments up to -j or -g for match.
NOTE: We don't want to combine actions if there were no criteria
in each rule, or rules didn't have an action
NOTE: Depends on arguments being in some kind of "normal" order which
is the case when processing the ACTUAL output of actual iptables-save
rather than a file merely in a compatable format */
unsigned int old = 0;
unsigned int new = 0;
int compare = 0;
while (new < newargc && old < oldargc) {
if (isTarget(oldargv[old]) && isTarget(newargv[new])) {
/* if oldarg was a terminating action then it makes no sense
* to combine further actions into the same xml */
if (((strcmp((oldargv[old]), "-j") == 0
|| strcmp((oldargv[old]), "--jump") == 0)
&& old+1 < oldargc
&& isTerminatingTarget(oldargv[old+1]) )
|| strcmp((oldargv[old]), "-g") == 0
|| strcmp((oldargv[old]), "--goto") == 0 ) {
/* Previous rule had terminating action */
compare = 0;
} else {
compare = 1;
}
break;
}
// break when old!=new
if (strcmp(oldargv[old], newargv[new]) != 0) {
compare = 0;
break;
}
old++;
new++;
}
// We won't match unless both rules had a target.
// This means we don't combine target-less rules, which is good
return compare == 1;
}
/* has a nice parsed rule starting with -A */
static void
do_rule(char *pcnt, char *bcnt, int argc, char *argv[], int argvattr[])
{
/* are these conditions the same as the previous rule?
* If so, skip arg straight to -j or -g */
if (combine && argc > 2 && !isTarget(argv[2]) && compareRules()) {
xmlComment("Combine action from next rule");
} else {
if (closeActionTag[0]) {
printf("%s\n", closeActionTag);
closeActionTag[0] = 0;
}
if (closeRuleTag[0]) {
printf("%s\n", closeRuleTag);
closeRuleTag[0] = 0;
}
printf(" <rule ");
//xmlAttrS("table",curTable); // not needed in full mode
//xmlAttrS("chain",argv[1]); // not needed in full mode
if (pcnt)
xmlAttrS("packet-count", pcnt);
if (bcnt)
xmlAttrS("byte-count", bcnt);
printf(">\n");
strncpy(closeRuleTag, " </rule>\n", XT_TABLE_MAXNAMELEN);
closeRuleTag[XT_TABLE_MAXNAMELEN] = '\0';
/* no point in writing out condition if there isn't one */
if (argc >= 3 && !isTarget(argv[2])) {
printf(" <conditions>\n");
do_rule_part(NULL, NULL, -1, argc, argv, argvattr);
printf(" </conditions>\n");
}
}
/* Write out the action */
//do_rule_part("action","arg",1,argc,argv,argvattr);
if (!closeActionTag[0]) {
printf(" <actions>\n");
strncpy(closeActionTag, " </actions>\n",
XT_TABLE_MAXNAMELEN);
closeActionTag[XT_TABLE_MAXNAMELEN] = '\0';
}
do_rule_part(NULL, NULL, 1, argc, argv, argvattr);
}
int
iptables_xml_main(int argc, char *argv[])
{
char buffer[10240];
int c;
FILE *in;
line = 0;
xtables_set_params(&iptables_xml_globals);
while ((c = getopt_long(argc, argv, "cvh", options, NULL)) != -1) {
switch (c) {
case 'c':
combine = 1;
break;
case 'v':
printf("xptables-xml\n");
verbose = 1;
break;
case 'h':
print_usage("iptables-xml", IPTABLES_VERSION);
break;
}
}
if (optind == argc - 1) {
in = fopen(argv[optind], "re");
if (!in) {
fprintf(stderr, "Can't open %s: %s", argv[optind],
strerror(errno));
exit(1);
}
} else if (optind < argc) {
fprintf(stderr, "Unknown arguments found on commandline");
exit(1);
} else
in = stdin;
printf("<iptables-rules version=\"1.0\">\n");
/* Grab standard input. */
while (fgets(buffer, sizeof(buffer), in)) {
int ret = 0;
line++;
if (buffer[0] == '\n')
continue;
else if (buffer[0] == '#') {
xmlComment(buffer);
continue;
}
if (verbose) {
printf("<!-- line %d ", line);
xmlCommentEscape(buffer);
printf(" -->\n");
}
if ((strcmp(buffer, "COMMIT\n") == 0) && (curTable[0])) {
DEBUGP("Calling commit\n");
closeTable();
ret = 1;
} else if ((buffer[0] == '*')) {
/* New table */
char *table;
table = strtok(buffer + 1, " \t\n");
DEBUGP("line %u, table '%s'\n", line, table);
if (!table) {
xtables_error(PARAMETER_PROBLEM,
"%s: line %u table name invalid\n",
prog_name, line);
exit(1);
}
openTable(table);
ret = 1;
} else if ((buffer[0] == ':') && (curTable[0])) {
/* New chain. */
char *policy, *chain;
struct xt_counters count;
char *ctrs;
chain = strtok(buffer + 1, " \t\n");
DEBUGP("line %u, chain '%s'\n", line, chain);
if (!chain) {
xtables_error(PARAMETER_PROBLEM,
"%s: line %u chain name invalid\n",
prog_name, line);
exit(1);
}
DEBUGP("Creating new chain '%s'\n", chain);
policy = strtok(NULL, " \t\n");
DEBUGP("line %u, policy '%s'\n", line, policy);
if (!policy) {
xtables_error(PARAMETER_PROBLEM,
"%s: line %u policy invalid\n",
prog_name, line);
exit(1);
}
ctrs = strtok(NULL, " \t\n");
parse_counters(ctrs, &count);
saveChain(chain, policy, &count);
ret = 1;
} else if (curTable[0]) {
unsigned int a;
char *ptr = buffer;
char *pcnt = NULL;
char *bcnt = NULL;
char *parsestart;
char *chain = NULL;
/* the parser */
char *param_start, *curchar;
int quote_open, quoted;
char param_buffer[1024];
/* reset the newargv */
newargc = 0;
if (buffer[0] == '[') {
/* we have counters in our input */
ptr = strchr(buffer, ']');
if (!ptr)
xtables_error(PARAMETER_PROBLEM,
"Bad line %u: need ]\n",
line);
pcnt = strtok(buffer + 1, ":");
if (!pcnt)
xtables_error(PARAMETER_PROBLEM,
"Bad line %u: need :\n",
line);
bcnt = strtok(NULL, "]");
if (!bcnt)
xtables_error(PARAMETER_PROBLEM,
"Bad line %u: need ]\n",
line);
/* start command parsing after counter */
parsestart = ptr + 1;
} else {
/* start command parsing at start of line */
parsestart = buffer;
}
/* This is a 'real' parser crafted in artist mode
* not hacker mode. If the author can live with that
* then so can everyone else */
quote_open = 0;
/* We need to know which args were quoted so we
can preserve quote */
quoted = 0;
param_start = parsestart;
for (curchar = parsestart; *curchar; curchar++) {
if (*curchar == '"') {
/* quote_open cannot be true if there
* was no previous character. Thus,
* curchar-1 has to be within bounds */
if (quote_open &&
*(curchar - 1) != '\\') {
quote_open = 0;
*curchar = ' ';
} else {
quote_open = 1;
quoted = 1;
param_start++;
}
}
if (*curchar == ' '
|| *curchar == '\t' || *curchar == '\n') {
int param_len = curchar - param_start;
if (quote_open)
continue;
if (!param_len) {
/* two spaces? */
param_start++;
continue;
}
/* end of one parameter */
strncpy(param_buffer, param_start,
param_len);
*(param_buffer + param_len) = '\0';
/* check if table name specified */
if (!strncmp(param_buffer, "-t", 3)
|| !strncmp(param_buffer,
"--table", 8)) {
xtables_error(PARAMETER_PROBLEM,
"Line %u seems to have a "
"-t table option.\n",
line);
exit(1);
}
add_argv(param_buffer, quoted);
if (newargc >= 2
&& 0 ==
strcmp(newargv[newargc - 2], "-A"))
chain = newargv[newargc - 1];
quoted = 0;
param_start += param_len + 1;
} else {
/* regular character, skip */
}
}
DEBUGP("calling do_command4(%u, argv, &%s, handle):\n",
newargc, curTable);
for (a = 0; a < newargc; a++)
DEBUGP("argv[%u]: %s\n", a, newargv[a]);
needChain(chain);// Should we explicitly look for -A
do_rule(pcnt, bcnt, newargc, newargv, newargvattr);
save_argv();
ret = 1;
}
if (!ret) {
fprintf(stderr, "%s: line %u failed\n",
prog_name, line);
exit(1);
}
}
if (curTable[0]) {
fprintf(stderr, "%s: COMMIT expected at line %u\n",
prog_name, line + 1);
exit(1);
}
fclose(in);
printf("</iptables-rules>\n");
free_argv();
return 0;
}
.TH IPTABLES 8 "" "@PACKAGE_STRING@" "@PACKAGE_STRING@"
.\"
.\" Man page written by Herve Eychenne <rv@wallfire.org> (May 1999)
.\" It is based on ipchains page.
.\" TODO: add a word for protocol helpers (FTP, IRC, SNMP-ALG)
.\"
.\" ipchains page by Paul ``Rusty'' Russell March 1997
.\" Based on the original ipfwadm man page by Jos Vos <jos@xos.nl>
.\"
.\" This program is free software; you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation; either version 2 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program; if not, write to the Free Software
.\" Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
.\"
.\"
.SH NAME
iptables/ip6tables \(em administration tool for IPv4/IPv6 packet filtering and NAT
.SH SYNOPSIS
\fBiptables\fP [\fB\-t\fP \fItable\fP] {\fB\-A\fP|\fB\-C\fP|\fB\-D\fP}
\fIchain\fP \fIrule-specification\fP
.P
\fBip6tables\fP [\fB\-t\fP \fItable\fP] {\fB\-A\fP|\fB\-C\fP|\fB\-D\fP}
\fIchain rule-specification\fP
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-I\fP \fIchain\fP [\fIrulenum\fP] \fIrule-specification\fP
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-R\fP \fIchain rulenum rule-specification\fP
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-D\fP \fIchain rulenum\fP
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-S\fP [\fIchain\fP [\fIrulenum\fP]]
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] {\fB\-F\fP|\fB\-L\fP|\fB\-Z\fP} [\fIchain\fP [\fIrulenum\fP]] [\fIoptions...\fP]
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-N\fP \fIchain\fP
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-X\fP [\fIchain\fP]
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-P\fP \fIchain target\fP
.PP
\fBiptables\fP [\fB\-t\fP \fItable\fP] \fB\-E\fP \fIold-chain-name new-chain-name\fP
.PP
rule-specification = [\fImatches...\fP] [\fItarget\fP]
.PP
match = \fB\-m\fP \fImatchname\fP [\fIper-match-options\fP]
.PP
target = \fB\-j\fP \fItargetname\fP [\fIper\-target\-options\fP]
.SH DESCRIPTION
\fBIptables\fP and \fBip6tables\fP are used to set up, maintain, and inspect the
tables of IPv4 and IPv6 packet
filter rules in the Linux kernel. Several different tables
may be defined. Each table contains a number of built-in
chains and may also contain user-defined chains.
.PP
Each chain is a list of rules which can match a set of packets. Each
rule specifies what to do with a packet that matches. This is called
a `target', which may be a jump to a user-defined chain in the same
table.
.SH TARGETS
A firewall rule specifies criteria for a packet and a target. If the
packet does not match, the next rule in the chain is examined; if
it does match, then the next rule is specified by the value of the
target, which can be the name of a user-defined chain, one of the targets
described in \fBiptables\-extensions\fP(8), or one of the
special values \fBACCEPT\fP, \fBDROP\fP or \fBRETURN\fP.
.PP
\fBACCEPT\fP means to let the packet through.
\fBDROP\fP means to drop the packet on the floor.
\fBRETURN\fP means stop traversing this chain and resume at the next
rule in the
previous (calling) chain. If the end of a built-in chain is reached
or a rule in a built-in chain with target \fBRETURN\fP
is matched, the target specified by the chain policy determines the
fate of the packet.
.SH TABLES
There are currently five independent tables (which tables are present
at any time depends on the kernel configuration options and which
modules are present).
.TP
\fB\-t\fP, \fB\-\-table\fP \fItable\fP
This option specifies the packet matching table which the command
should operate on. If the kernel is configured with automatic module
loading, an attempt will be made to load the appropriate module for
that table if it is not already there.
The tables are as follows:
.RS
.TP .4i
\fBfilter\fP:
This is the default table (if no \-t option is passed). It contains
the built-in chains \fBINPUT\fP (for packets destined to local sockets),
\fBFORWARD\fP (for packets being routed through the box), and
\fBOUTPUT\fP (for locally-generated packets).
.TP
\fBnat\fP:
This table is consulted when a packet that creates a new
connection is encountered. It consists of three built-ins: \fBPREROUTING\fP
(for altering packets as soon as they come in), \fBOUTPUT\fP
(for altering locally-generated packets before routing), and \fBPOSTROUTING\fP
(for altering packets as they are about to go out).
IPv6 NAT support is available since kernel 3.7.
.TP
\fBmangle\fP:
This table is used for specialized packet alteration. Until kernel
2.4.17 it had two built-in chains: \fBPREROUTING\fP
(for altering incoming packets before routing) and \fBOUTPUT\fP
(for altering locally-generated packets before routing).
Since kernel 2.4.18, three other built-in chains are also supported:
\fBINPUT\fP (for packets coming into the box itself), \fBFORWARD\fP
(for altering packets being routed through the box), and \fBPOSTROUTING\fP
(for altering packets as they are about to go out).
.TP
\fBraw\fP:
This table is used mainly for configuring exemptions from connection
tracking in combination with the NOTRACK target. It registers at the netfilter
hooks with higher priority and is thus called before ip_conntrack, or any other
IP tables. It provides the following built-in chains: \fBPREROUTING\fP
(for packets arriving via any network interface) \fBOUTPUT\fP
(for packets generated by local processes)
.TP
\fBsecurity\fP:
This table is used for Mandatory Access Control (MAC) networking rules, such
as those enabled by the \fBSECMARK\fP and \fBCONNSECMARK\fP targets.
Mandatory Access Control is implemented by Linux Security Modules such as
SELinux. The security table is called after the filter table, allowing any
Discretionary Access Control (DAC) rules in the filter table to take effect
before MAC rules. This table provides the following built-in chains:
\fBINPUT\fP (for packets coming into the box itself),
\fBOUTPUT\fP (for altering locally-generated packets before routing), and
\fBFORWARD\fP (for altering packets being routed through the box).
.RE
.SH OPTIONS
The options that are recognized by
\fBiptables\fP and \fBip6tables\fP can be divided into several different groups.
.SS COMMANDS
These options specify the desired action to perform. Only one of them
can be specified on the command line unless otherwise stated
below. For long versions of the command and option names, you
need to use only enough letters to ensure that
\fBiptables\fP can differentiate it from all other options.
.TP
\fB\-A\fP, \fB\-\-append\fP \fIchain rule-specification\fP
Append one or more rules to the end of the selected chain.
When the source and/or destination names resolve to more than one
address, a rule will be added for each possible address combination.
.TP
\fB\-C\fP, \fB\-\-check\fP \fIchain rule-specification\fP
Check whether a rule matching the specification does exist in the
selected chain. This command uses the same logic as \fB\-D\fP to
find a matching entry, but does not alter the existing iptables
configuration and uses its exit code to indicate success or failure.
.TP
\fB\-D\fP, \fB\-\-delete\fP \fIchain rule-specification\fP
.ns
.TP
\fB\-D\fP, \fB\-\-delete\fP \fIchain rulenum\fP
Delete one or more rules from the selected chain. There are two
versions of this command: the rule can be specified as a number in the
chain (starting at 1 for the first rule) or a rule to match.
.TP
\fB\-I\fP, \fB\-\-insert\fP \fIchain\fP [\fIrulenum\fP] \fIrule-specification\fP
Insert one or more rules in the selected chain as the given rule
number. So, if the rule number is 1, the rule or rules are inserted
at the head of the chain. This is also the default if no rule number
is specified.
.TP
\fB\-R\fP, \fB\-\-replace\fP \fIchain rulenum rule-specification\fP
Replace a rule in the selected chain. If the source and/or
destination names resolve to multiple addresses, the command will
fail. Rules are numbered starting at 1.
.TP
\fB\-L\fP, \fB\-\-list\fP [\fIchain\fP]
List all rules in the selected chain. If no chain is selected, all
chains are listed. Like every other iptables command, it applies to the
specified table (filter is the default), so NAT rules get listed by
.nf
iptables \-t nat \-n \-L
.fi
Please note that it is often used with the \fB\-n\fP
option, in order to avoid long reverse DNS lookups.
It is legal to specify the \fB\-Z\fP
(zero) option as well, in which case the chain(s) will be atomically
listed and zeroed. The exact output is affected by the other
arguments given. The exact rules are suppressed until you use
.nf
iptables \-L \-v
.fi
.TP
\fB\-S\fP, \fB\-\-list\-rules\fP [\fIchain\fP]
Print all rules in the selected chain. If no chain is selected, all
chains are printed like iptables-save. Like every other iptables command,
it applies to the specified table (filter is the default).
.TP
\fB\-F\fP, \fB\-\-flush\fP [\fIchain\fP]
Flush the selected chain (all the chains in the table if none is given).
This is equivalent to deleting all the rules one by one.
.TP
\fB\-Z\fP, \fB\-\-zero\fP [\fIchain\fP [\fIrulenum\fP]]
Zero the packet and byte counters in all chains, or only the given chain,
or only the given rule in a chain. It is legal to
specify the
\fB\-L\fP, \fB\-\-list\fP
(list) option as well, to see the counters immediately before they are
cleared. (See above.)
.TP
\fB\-N\fP, \fB\-\-new\-chain\fP \fIchain\fP
Create a new user-defined chain by the given name. There must be no
target of that name already.
.TP
\fB\-X\fP, \fB\-\-delete\-chain\fP [\fIchain\fP]
Delete the optional user-defined chain specified. There must be no references
to the chain. If there are, you must delete or replace the referring rules
before the chain can be deleted. The chain must be empty, i.e. not contain
any rules. If no argument is given, it will attempt to delete every
non-builtin chain in the table.
.TP
\fB\-P\fP, \fB\-\-policy\fP \fIchain target\fP
Set the policy for the chain to the given target. See the section \fBTARGETS\fP
for the legal targets. Only built-in (non-user-defined) chains can have
policies, and neither built-in nor user-defined chains can be policy
targets.
.TP
\fB\-E\fP, \fB\-\-rename\-chain\fP \fIold\-chain new\-chain\fP
Rename the user specified chain to the user supplied name. This is
cosmetic, and has no effect on the structure of the table.
.TP
\fB\-h\fP
Help.
Give a (currently very brief) description of the command syntax.
.SS PARAMETERS
The following parameters make up a rule specification (as used in the
add, delete, insert, replace and append commands).
.TP
\fB\-4\fP, \fB\-\-ipv4\fP
This option has no effect in iptables and iptables-restore.
If a rule using the \fB\-4\fP option is inserted with (and only with)
ip6tables-restore, it will be silently ignored. Any other uses will throw an
error. This option allows to put both IPv4 and IPv6 rules in a single rule file
for use with both iptables-restore and ip6tables-restore.
.TP
\fB\-6\fP, \fB\-\-ipv6\fP
If a rule using the \fB\-6\fP option is inserted with (and only with)
iptables-restore, it will be silently ignored. Any other uses will throw an
error. This option allows to put both IPv4 and IPv6 rules in a single rule file
for use with both iptables-restore and ip6tables-restore.
This option has no effect in ip6tables and ip6tables-restore.
.TP
[\fB!\fP] \fB\-p\fP, \fB\-\-protocol\fP \fIprotocol\fP
The protocol of the rule or of the packet to check.
The specified protocol can be one of \fBtcp\fP, \fBudp\fP, \fBudplite\fP,
\fBicmp\fP, \fBicmpv6\fP,\fBesp\fP, \fBah\fP, \fBsctp\fP, \fBmh\fP or the special keyword "\fBall\fP",
or it can be a numeric value, representing one of these protocols or a
different one. A protocol name from /etc/protocols is also allowed.
A "!" argument before the protocol inverts the
test. The number zero is equivalent to \fBall\fP. "\fBall\fP"
will match with all protocols and is taken as default when this
option is omitted.
Note that, in ip6tables, IPv6 extension headers except \fBesp\fP are not allowed.
\fBesp\fP and \fBipv6\-nonext\fP
can be used with Kernel version 2.6.11 or later.
The number zero is equivalent to \fBall\fP, which means that you cannot
test the protocol field for the value 0 directly. To match on a HBH header,
even if it were the last, you cannot use \fB\-p 0\fP, but always need
\fB\-m hbh\fP.
.TP
[\fB!\fP] \fB\-s\fP, \fB\-\-source\fP \fIaddress\fP[\fB/\fP\fImask\fP][\fB,\fP\fI...\fP]
Source specification. \fIAddress\fP
can be either a network name, a hostname, a network IP address (with
\fB/\fP\fImask\fP), or a plain IP address. Hostnames will
be resolved once only, before the rule is submitted to the kernel.
Please note that specifying any name to be resolved with a remote query such as
DNS is a really bad idea.
The \fImask\fP
can be either an ipv4 network mask (for iptables) or a plain number,
specifying the number of 1's at the left side of the network mask.
Thus, an iptables mask of \fI24\fP is equivalent to \fI255.255.255.0\fP.
A "!" argument before the address specification inverts the sense of
the address. The flag \fB\-\-src\fP is an alias for this option.
Multiple addresses can be specified, but this will \fBexpand to multiple
rules\fP (when adding with \-A), or will cause multiple rules to be
deleted (with \-D).
.TP
[\fB!\fP] \fB\-d\fP, \fB\-\-destination\fP \fIaddress\fP[\fB/\fP\fImask\fP][\fB,\fP\fI...\fP]
Destination specification.
See the description of the \fB\-s\fP
(source) flag for a detailed description of the syntax. The flag
\fB\-\-dst\fP is an alias for this option.
.TP
\fB\-m\fP, \fB\-\-match\fP \fImatch\fP
Specifies a match to use, that is, an extension module that tests for a
specific property. The set of matches make up the condition under which a
target is invoked. Matches are evaluated first to last as specified on the
command line and work in short-circuit fashion, i.e. if one extension yields
false, evaluation will stop.
.TP
\fB\-j\fP, \fB\-\-jump\fP \fItarget\fP
This specifies the target of the rule; i.e., what to do if the packet
matches it. The target can be a user-defined chain (other than the
one this rule is in), one of the special builtin targets which decide
the fate of the packet immediately, or an extension (see \fBEXTENSIONS\fP
below). If this
option is omitted in a rule (and \fB\-g\fP
is not used), then matching the rule will have no
effect on the packet's fate, but the counters on the rule will be
incremented.
.TP
\fB\-g\fP, \fB\-\-goto\fP \fIchain\fP
This specifies that the processing should continue in a user
specified chain. Unlike the \-\-jump option return will not continue
processing in this chain but instead in the chain that called us via
\-\-jump.
.TP
[\fB!\fP] \fB\-i\fP, \fB\-\-in\-interface\fP \fIname\fP
Name of an interface via which a packet was received (only for
packets entering the \fBINPUT\fP, \fBFORWARD\fP and \fBPREROUTING\fP
chains). When the "!" argument is used before the interface name, the
sense is inverted. If the interface name ends in a "+", then any
interface which begins with this name will match. If this option is
omitted, any interface name will match.
.TP
[\fB!\fP] \fB\-o\fP, \fB\-\-out\-interface\fP \fIname\fP
Name of an interface via which a packet is going to be sent (for packets
entering the \fBFORWARD\fP, \fBOUTPUT\fP and \fBPOSTROUTING\fP
chains). When the "!" argument is used before the interface name, the
sense is inverted. If the interface name ends in a "+", then any
interface which begins with this name will match. If this option is
omitted, any interface name will match.
.TP
[\fB!\fP] \fB\-f\fP, \fB\-\-fragment\fP
This means that the rule only refers to second and further IPv4 fragments
of fragmented packets. Since there is no way to tell the source or
destination ports of such a packet (or ICMP type), such a packet will
not match any rules which specify them. When the "!" argument
precedes the "\-f" flag, the rule will only match head fragments, or
unfragmented packets. This option is IPv4 specific, it is not available
in ip6tables.
.TP
\fB\-c\fP, \fB\-\-set\-counters\fP \fIpackets bytes\fP
This enables the administrator to initialize the packet and byte
counters of a rule (during \fBINSERT\fP, \fBAPPEND\fP, \fBREPLACE\fP
operations).
.SS "OTHER OPTIONS"
The following additional options can be specified:
.TP
\fB\-v\fP, \fB\-\-verbose\fP
Verbose output. This option makes the list command show the interface
name, the rule options (if any), and the TOS masks. The packet and
byte counters are also listed, with the suffix 'K', 'M' or 'G' for
1000, 1,000,000 and 1,000,000,000 multipliers respectively (but see
the \fB\-x\fP flag to change this).
For appending, insertion, deletion and replacement, this causes
detailed information on the rule or rules to be printed. \fB\-v\fP may be
specified multiple times to possibly emit more detailed debug statements.
.TP
\fB\-w\fP, \fB\-\-wait\fP
Wait for the xtables lock.
To prevent multiple instances of the program from running concurrently,
an attempt will be made to obtain an exclusive lock at launch. By default,
the program will exit if the lock cannot be obtained. This option will
make the program wait until the exclusive lock can be obtained.
.TP
\fB\-n\fP, \fB\-\-numeric\fP
Numeric output.
IP addresses and port numbers will be printed in numeric format.
By default, the program will try to display them as host names,
network names, or services (whenever applicable).
.TP
\fB\-x\fP, \fB\-\-exact\fP
Expand numbers.
Display the exact value of the packet and byte counters,
instead of only the rounded number in K's (multiples of 1000)
M's (multiples of 1000K) or G's (multiples of 1000M). This option is
only relevant for the \fB\-L\fP command.
.TP
\fB\-\-line\-numbers\fP
When listing rules, add line numbers to the beginning of each rule,
corresponding to that rule's position in the chain.
.TP
\fB\-\-modprobe=\fP\fIcommand\fP
When adding or inserting rules into a chain, use \fIcommand\fP
to load any necessary modules (targets, match extensions, etc).
.SH MATCH AND TARGET EXTENSIONS
.PP
iptables can use extended packet matching and target modules.
A list of these is available in the \fBiptables\-extensions\fP(8) manpage.
.SH DIAGNOSTICS
Various error messages are printed to standard error. The exit code
is 0 for correct functioning. Errors which appear to be caused by
invalid or abused command line parameters cause an exit code of 2, and
other errors cause an exit code of 1.
.SH BUGS
Bugs? What's this? ;-)
Well, you might want to have a look at http://bugzilla.netfilter.org/
.SH COMPATIBILITY WITH IPCHAINS
This \fBiptables\fP
is very similar to ipchains by Rusty Russell. The main difference is
that the chains \fBINPUT\fP and \fBOUTPUT\fP
are only traversed for packets coming into the local host and
originating from the local host respectively. Hence every packet only
passes through one of the three chains (except loopback traffic, which
involves both INPUT and OUTPUT chains); previously a forwarded packet
would pass through all three.
.PP
The other main difference is that \fB\-i\fP refers to the input interface;
\fB\-o\fP refers to the output interface, and both are available for packets
entering the \fBFORWARD\fP chain.
.PP
The various forms of NAT have been separated out; \fBiptables\fP
is a pure packet filter when using the default `filter' table, with
optional extension modules. This should simplify much of the previous
confusion over the combination of IP masquerading and packet filtering
seen previously. So the following options are handled differently:
.nf
\-j MASQ
\-M \-S
\-M \-L
.fi
There are several other changes in iptables.
.SH SEE ALSO
\fBiptables\-apply\fP(8),
\fBiptables\-save\fP(8),
\fBiptables\-restore\fP(8),
\fBiptables\-extensions\fP(8),
.PP
The packet-filtering-HOWTO details iptables usage for
packet filtering, the NAT-HOWTO details NAT,
the netfilter-extensions-HOWTO details the extensions that are
not in the standard distribution,
and the netfilter-hacking-HOWTO details the netfilter internals.
.br
See
.BR "http://www.netfilter.org/" .
.SH AUTHORS
Rusty Russell originally wrote iptables, in early consultation with Michael
Neuling.
.PP
Marc Boucher made Rusty abandon ipnatctl by lobbying for a generic packet
selection framework in iptables, then wrote the mangle table, the owner match,
the mark stuff, and ran around doing cool stuff everywhere.
.PP
James Morris wrote the TOS target, and tos match.
.PP
Jozsef Kadlecsik wrote the REJECT target.
.PP
Harald Welte wrote the ULOG and NFQUEUE target, the new libiptc, as well as the TTL, DSCP, ECN matches and targets.
.PP
The Netfilter Core Team is: Marc Boucher, Martin Josefsson, Yasuyuki Kozakai,
Jozsef Kadlecsik, Patrick McHardy, James Morris, Pablo Neira Ayuso,
Harald Welte and Rusty Russell.
.PP
Man page originally written by Herve Eychenne <rv@wallfire.org>.
.\" .. and did I mention that we are incredibly cool people?
.\" .. sexy, too ..
.\" .. witty, charming, powerful ..
.\" .. and most of all, modest ..
.SH VERSION
.PP
This manual page applies to iptables/ip6tables @PACKAGE_AND_VERSION@.
/* Code to take an iptables-style command line and do it. */
/*
* Author: Paul.Russell@rustcorp.com.au and mneuling@radlogic.com.au
*
* (C) 2000-2002 by the netfilter coreteam <coreteam@netfilter.org>:
* Paul 'Rusty' Russell <rusty@rustcorp.com.au>
* Marc Boucher <marc+nf@mbsi.ca>
* James Morris <jmorris@intercode.com.au>
* Harald Welte <laforge@gnumonks.org>
* Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <getopt.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <limits.h>
#include <unistd.h>
#include <iptables.h>
#include <xtables.h>
#include <fcntl.h>
#include "xshared.h"
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define CMD_NONE 0x0000U
#define CMD_INSERT 0x0001U
#define CMD_DELETE 0x0002U
#define CMD_DELETE_NUM 0x0004U
#define CMD_REPLACE 0x0008U
#define CMD_APPEND 0x0010U
#define CMD_LIST 0x0020U
#define CMD_FLUSH 0x0040U
#define CMD_ZERO 0x0080U
#define CMD_NEW_CHAIN 0x0100U
#define CMD_DELETE_CHAIN 0x0200U
#define CMD_SET_POLICY 0x0400U
#define CMD_RENAME_CHAIN 0x0800U
#define CMD_LIST_RULES 0x1000U
#define CMD_ZERO_NUM 0x2000U
#define CMD_CHECK 0x4000U
#define NUMBER_OF_CMD 16
static const char cmdflags[] = { 'I', 'D', 'D', 'R', 'A', 'L', 'F', 'Z',
'N', 'X', 'P', 'E', 'S', 'Z', 'C' };
#define OPT_FRAGMENT 0x00800U
#define NUMBER_OF_OPT ARRAY_SIZE(optflags)
static const char optflags[]
= { 'n', 's', 'd', 'p', 'j', 'v', 'x', 'i', 'o', '0', 'c', 'f'};
static struct option original_opts[] = {
{.name = "append", .has_arg = 1, .val = 'A'},
{.name = "delete", .has_arg = 1, .val = 'D'},
{.name = "check", .has_arg = 1, .val = 'C'},
{.name = "insert", .has_arg = 1, .val = 'I'},
{.name = "replace", .has_arg = 1, .val = 'R'},
{.name = "list", .has_arg = 2, .val = 'L'},
{.name = "list-rules", .has_arg = 2, .val = 'S'},
{.name = "flush", .has_arg = 2, .val = 'F'},
{.name = "zero", .has_arg = 2, .val = 'Z'},
{.name = "new-chain", .has_arg = 1, .val = 'N'},
{.name = "delete-chain", .has_arg = 2, .val = 'X'},
{.name = "rename-chain", .has_arg = 1, .val = 'E'},
{.name = "policy", .has_arg = 1, .val = 'P'},
{.name = "source", .has_arg = 1, .val = 's'},
{.name = "destination", .has_arg = 1, .val = 'd'},
{.name = "src", .has_arg = 1, .val = 's'}, /* synonym */
{.name = "dst", .has_arg = 1, .val = 'd'}, /* synonym */
{.name = "protocol", .has_arg = 1, .val = 'p'},
{.name = "in-interface", .has_arg = 1, .val = 'i'},
{.name = "jump", .has_arg = 1, .val = 'j'},
{.name = "table", .has_arg = 1, .val = 't'},
{.name = "match", .has_arg = 1, .val = 'm'},
{.name = "numeric", .has_arg = 0, .val = 'n'},
{.name = "out-interface", .has_arg = 1, .val = 'o'},
{.name = "verbose", .has_arg = 0, .val = 'v'},
{.name = "wait", .has_arg = 0, .val = 'w'},
{.name = "exact", .has_arg = 0, .val = 'x'},
{.name = "fragments", .has_arg = 0, .val = 'f'},
{.name = "version", .has_arg = 0, .val = 'V'},
{.name = "help", .has_arg = 2, .val = 'h'},
{.name = "line-numbers", .has_arg = 0, .val = '0'},
{.name = "modprobe", .has_arg = 1, .val = 'M'},
{.name = "set-counters", .has_arg = 1, .val = 'c'},
{.name = "goto", .has_arg = 1, .val = 'g'},
{.name = "ipv4", .has_arg = 0, .val = '4'},
{.name = "ipv6", .has_arg = 0, .val = '6'},
{NULL},
};
void iptables_exit_error(enum xtables_exittype status, const char *msg, ...) __attribute__((noreturn, format(printf,2,3)));
struct xtables_globals iptables_globals = {
.option_offset = 0,
.program_version = IPTABLES_VERSION,
.orig_opts = original_opts,
.exit_err = iptables_exit_error,
};
/* Table of legal combinations of commands and options. If any of the
* given commands make an option legal, that option is legal (applies to
* CMD_LIST and CMD_ZERO only).
* Key:
* + compulsory
* x illegal
* optional
*/
static const char commands_v_options[NUMBER_OF_CMD][NUMBER_OF_OPT] =
/* Well, it's better than "Re: Linux vs FreeBSD" */
{
/* -n -s -d -p -j -v -x -i -o --line -c -f */
/*INSERT*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' ',' '},
/*DELETE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x','x',' '},
/*DELETE_NUM*/{'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*REPLACE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' ',' '},
/*APPEND*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' ',' '},
/*LIST*/ {' ','x','x','x','x',' ',' ','x','x',' ','x','x'},
/*FLUSH*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*ZERO*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*NEW_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*DEL_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*SET_POLICY*/{'x','x','x','x','x',' ','x','x','x','x',' ','x'},
/*RENAME*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*LIST_RULES*/{'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*ZERO_NUM*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
/*CHECK*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x','x',' '},
};
static const int inverse_for_options[NUMBER_OF_OPT] =
{
/* -n */ 0,
/* -s */ IPT_INV_SRCIP,
/* -d */ IPT_INV_DSTIP,
/* -p */ XT_INV_PROTO,
/* -j */ 0,
/* -v */ 0,
/* -x */ 0,
/* -i */ IPT_INV_VIA_IN,
/* -o */ IPT_INV_VIA_OUT,
/*--line*/ 0,
/* -c */ 0,
/* -f */ IPT_INV_FRAG,
};
#define opts iptables_globals.opts
#define prog_name iptables_globals.program_name
#define prog_vers iptables_globals.program_version
static void __attribute__((noreturn))
exit_tryhelp(int status)
{
if (line != -1)
fprintf(stderr, "Error occurred at line: %d\n", line);
fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
prog_name, prog_name);
xtables_free_opts(1);
exit(status);
}
static void
exit_printhelp(const struct xtables_rule_match *matches)
{
printf("%s v%s\n\n"
"Usage: %s -[ACD] chain rule-specification [options]\n"
" %s -I chain [rulenum] rule-specification [options]\n"
" %s -R chain rulenum rule-specification [options]\n"
" %s -D chain rulenum [options]\n"
" %s -[LS] [chain [rulenum]] [options]\n"
" %s -[FZ] [chain] [options]\n"
" %s -[NX] chain\n"
" %s -E old-chain-name new-chain-name\n"
" %s -P chain target [options]\n"
" %s -h (print this help information)\n\n",
prog_name, prog_vers, prog_name, prog_name,
prog_name, prog_name, prog_name, prog_name,
prog_name, prog_name, prog_name, prog_name);
printf(
"Commands:\n"
"Either long or short options are allowed.\n"
" --append -A chain Append to chain\n"
" --check -C chain Check for the existence of a rule\n"
" --delete -D chain Delete matching rule from chain\n"
" --delete -D chain rulenum\n"
" Delete rule rulenum (1 = first) from chain\n"
" --insert -I chain [rulenum]\n"
" Insert in chain as rulenum (default 1=first)\n"
" --replace -R chain rulenum\n"
" Replace rule rulenum (1 = first) in chain\n"
" --list -L [chain [rulenum]]\n"
" List the rules in a chain or all chains\n"
" --list-rules -S [chain [rulenum]]\n"
" Print the rules in a chain or all chains\n"
" --flush -F [chain] Delete all rules in chain or all chains\n"
" --zero -Z [chain [rulenum]]\n"
" Zero counters in chain or all chains\n"
" --new -N chain Create a new user-defined chain\n"
" --delete-chain\n"
" -X [chain] Delete a user-defined chain\n"
" --policy -P chain target\n"
" Change policy on chain to target\n"
" --rename-chain\n"
" -E old-chain new-chain\n"
" Change chain name, (moving any references)\n"
"Options:\n"
" --ipv4 -4 Nothing (line is ignored by ip6tables-restore)\n"
" --ipv6 -6 Error (line is ignored by iptables-restore)\n"
"[!] --protocol -p proto protocol: by number or name, eg. `tcp'\n"
"[!] --source -s address[/mask][...]\n"
" source specification\n"
"[!] --destination -d address[/mask][...]\n"
" destination specification\n"
"[!] --in-interface -i input name[+]\n"
" network interface name ([+] for wildcard)\n"
" --jump -j target\n"
" target for rule (may load target extension)\n"
#ifdef IPT_F_GOTO
" --goto -g chain\n"
" jump to chain with no return\n"
#endif
" --match -m match\n"
" extended match (may load extension)\n"
" --numeric -n numeric output of addresses and ports\n"
"[!] --out-interface -o output name[+]\n"
" network interface name ([+] for wildcard)\n"
" --table -t table table to manipulate (default: `filter')\n"
" --verbose -v verbose mode\n"
" --wait -w wait for the xtables lock\n"
" --line-numbers print line numbers when listing\n"
" --exact -x expand numbers (display exact values)\n"
"[!] --fragment -f match second or further fragments only\n"
" --modprobe=<command> try to insert modules using this command\n"
" --set-counters PKTS BYTES set the counter during insert/append\n"
"[!] --version -V print package version.\n");
print_extension_helps(xtables_targets, matches);
exit(0);
}
void
iptables_exit_error(enum xtables_exittype status, const char *msg, ...)
{
va_list args;
va_start(args, msg);
fprintf(stderr, "%s v%s: ", prog_name, prog_vers);
vfprintf(stderr, msg, args);
va_end(args);
fprintf(stderr, "\n");
if (status == PARAMETER_PROBLEM)
exit_tryhelp(status);
if (status == VERSION_PROBLEM)
fprintf(stderr,
"Perhaps iptables or your kernel needs to be upgraded.\n");
/* On error paths, make sure that we don't leak memory */
xtables_free_opts(1);
exit(status);
}
static void
generic_opt_check(int command, int options)
{
int i, j, legal = 0;
/* Check that commands are valid with options. Complicated by the
* fact that if an option is legal with *any* command given, it is
* legal overall (ie. -z and -l).
*/
for (i = 0; i < NUMBER_OF_OPT; i++) {
legal = 0; /* -1 => illegal, 1 => legal, 0 => undecided. */
for (j = 0; j < NUMBER_OF_CMD; j++) {
if (!(command & (1<<j)))
continue;
if (!(options & (1<<i))) {
if (commands_v_options[j][i] == '+')
xtables_error(PARAMETER_PROBLEM,
"You need to supply the `-%c' "
"option for this command\n",
optflags[i]);
} else {
if (commands_v_options[j][i] != 'x')
legal = 1;
else if (legal == 0)
legal = -1;
}
}
if (legal == -1)
xtables_error(PARAMETER_PROBLEM,
"Illegal option `-%c' with this command\n",
optflags[i]);
}
}
static char
opt2char(int option)
{
const char *ptr;
for (ptr = optflags; option > 1; option >>= 1, ptr++);
return *ptr;
}
static char
cmd2char(int option)
{
const char *ptr;
for (ptr = cmdflags; option > 1; option >>= 1, ptr++);
return *ptr;
}
static void
add_command(unsigned int *cmd, const int newcmd, const int othercmds,
int invert)
{
if (invert)
xtables_error(PARAMETER_PROBLEM, "unexpected ! flag");
if (*cmd & (~othercmds))
xtables_error(PARAMETER_PROBLEM, "Cannot use -%c with -%c\n",
cmd2char(newcmd), cmd2char(*cmd & (~othercmds)));
*cmd |= newcmd;
}
/*
* All functions starting with "parse" should succeed, otherwise
* the program fails.
* Most routines return pointers to static data that may change
* between calls to the same or other routines with a few exceptions:
* "host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
* return global static data.
*/
/* Christophe Burki wants `-p 6' to imply `-m tcp'. */
/* Can't be zero. */
static int
parse_rulenumber(const char *rule)
{
unsigned int rulenum;
if (!xtables_strtoui(rule, NULL, &rulenum, 1, INT_MAX))
xtables_error(PARAMETER_PROBLEM,
"Invalid rule number `%s'", rule);
return rulenum;
}
static void
parse_chain(const char *chainname)
{
const char *ptr;
if (strlen(chainname) >= XT_EXTENSION_MAXNAMELEN)
xtables_error(PARAMETER_PROBLEM,
"chain name `%s' too long (must be under %u chars)",
chainname, XT_EXTENSION_MAXNAMELEN);
if (*chainname == '-' || *chainname == '!')
xtables_error(PARAMETER_PROBLEM,
"chain name not allowed to start "
"with `%c'\n", *chainname);
if (xtables_find_target(chainname, XTF_TRY_LOAD))
xtables_error(PARAMETER_PROBLEM,
"chain name may not clash "
"with target name\n");
for (ptr = chainname; *ptr; ptr++)
if (isspace(*ptr))
xtables_error(PARAMETER_PROBLEM,
"Invalid chain name `%s'", chainname);
}
static const char *
parse_target(const char *targetname)
{
const char *ptr;
if (strlen(targetname) < 1)
xtables_error(PARAMETER_PROBLEM,
"Invalid target name (too short)");
if (strlen(targetname) >= XT_EXTENSION_MAXNAMELEN)
xtables_error(PARAMETER_PROBLEM,
"Invalid target name `%s' (%u chars max)",
targetname, XT_EXTENSION_MAXNAMELEN - 1);
for (ptr = targetname; *ptr; ptr++)
if (isspace(*ptr))
xtables_error(PARAMETER_PROBLEM,
"Invalid target name `%s'", targetname);
return targetname;
}
static void
set_option(unsigned int *options, unsigned int option, uint8_t *invflg,
int invert)
{
if (*options & option)
xtables_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
opt2char(option));
*options |= option;
if (invert) {
unsigned int i;
for (i = 0; 1 << i != option; i++);
if (!inverse_for_options[i])
xtables_error(PARAMETER_PROBLEM,
"cannot have ! before -%c",
opt2char(option));
*invflg |= inverse_for_options[i];
}
}
static void
print_header(unsigned int format, const char *chain, struct xtc_handle *handle)
{
struct xt_counters counters;
const char *pol = iptc_get_policy(chain, &counters, handle);
printf("Chain %s", chain);
if (pol) {
printf(" (policy %s", pol);
if (!(format & FMT_NOCOUNTS)) {
fputc(' ', stdout);
xtables_print_num(counters.pcnt, (format|FMT_NOTABLE));
fputs("packets, ", stdout);
xtables_print_num(counters.bcnt, (format|FMT_NOTABLE));
fputs("bytes", stdout);
}
printf(")\n");
} else {
unsigned int refs;
if (!iptc_get_references(&refs, chain, handle))
printf(" (ERROR obtaining refs)\n");
else
printf(" (%u references)\n", refs);
}
if (format & FMT_LINENUMBERS)
printf(FMT("%-4s ", "%s "), "num");
if (!(format & FMT_NOCOUNTS)) {
if (format & FMT_KILOMEGAGIGA) {
printf(FMT("%5s ","%s "), "pkts");
printf(FMT("%5s ","%s "), "bytes");
} else {
printf(FMT("%8s ","%s "), "pkts");
printf(FMT("%10s ","%s "), "bytes");
}
}
if (!(format & FMT_NOTARGET))
printf(FMT("%-9s ","%s "), "target");
fputs(" prot ", stdout);
if (format & FMT_OPTIONS)
fputs("opt", stdout);
if (format & FMT_VIA) {
printf(FMT(" %-6s ","%s "), "in");
printf(FMT("%-6s ","%s "), "out");
}
printf(FMT(" %-19s ","%s "), "source");
printf(FMT(" %-19s "," %s "), "destination");
printf("\n");
}
static int
print_match(const struct xt_entry_match *m,
const struct ipt_ip *ip,
int numeric)
{
const struct xtables_match *match =
xtables_find_match(m->u.user.name, XTF_TRY_LOAD, NULL);
if (match) {
if (match->print)
match->print(ip, m, numeric);
else
printf("%s ", match->name);
} else {
if (m->u.user.name[0])
printf("UNKNOWN match `%s' ", m->u.user.name);
}
/* Don't stop iterating. */
return 0;
}
/* e is called `fw' here for historical reasons */
static void
print_firewall(const struct ipt_entry *fw,
const char *targname,
unsigned int num,
unsigned int format,
struct xtc_handle *const handle)
{
const struct xtables_target *target = NULL;
const struct xt_entry_target *t;
uint8_t flags;
char buf[BUFSIZ];
if (!iptc_is_chain(targname, handle))
target = xtables_find_target(targname, XTF_TRY_LOAD);
else
target = xtables_find_target(XT_STANDARD_TARGET,
XTF_LOAD_MUST_SUCCEED);
t = ipt_get_target((struct ipt_entry *)fw);
flags = fw->ip.flags;
if (format & FMT_LINENUMBERS)
printf(FMT("%-4u ", "%u "), num);
if (!(format & FMT_NOCOUNTS)) {
xtables_print_num(fw->counters.pcnt, format);
xtables_print_num(fw->counters.bcnt, format);
}
if (!(format & FMT_NOTARGET))
printf(FMT("%-9s ", "%s "), targname);
fputc(fw->ip.invflags & XT_INV_PROTO ? '!' : ' ', stdout);
{
const char *pname = proto_to_name(fw->ip.proto, format&FMT_NUMERIC);
if (pname)
printf(FMT("%-5s", "%s "), pname);
else
printf(FMT("%-5hu", "%hu "), fw->ip.proto);
}
if (format & FMT_OPTIONS) {
if (format & FMT_NOTABLE)
fputs("opt ", stdout);
fputc(fw->ip.invflags & IPT_INV_FRAG ? '!' : '-', stdout);
fputc(flags & IPT_F_FRAG ? 'f' : '-', stdout);
fputc(' ', stdout);
}
if (format & FMT_VIA) {
char iface[IFNAMSIZ+2];
if (fw->ip.invflags & IPT_INV_VIA_IN) {
iface[0] = '!';
iface[1] = '\0';
}
else iface[0] = '\0';
if (fw->ip.iniface[0] != '\0') {
strcat(iface, fw->ip.iniface);
}
else if (format & FMT_NUMERIC) strcat(iface, "*");
else strcat(iface, "any");
printf(FMT(" %-6s ","in %s "), iface);
if (fw->ip.invflags & IPT_INV_VIA_OUT) {
iface[0] = '!';
iface[1] = '\0';
}
else iface[0] = '\0';
if (fw->ip.outiface[0] != '\0') {
strcat(iface, fw->ip.outiface);
}
else if (format & FMT_NUMERIC) strcat(iface, "*");
else strcat(iface, "any");
printf(FMT("%-6s ","out %s "), iface);
}
fputc(fw->ip.invflags & IPT_INV_SRCIP ? '!' : ' ', stdout);
if (fw->ip.smsk.s_addr == 0L && !(format & FMT_NUMERIC))
printf(FMT("%-19s ","%s "), "anywhere");
else {
if (format & FMT_NUMERIC)
strcpy(buf, xtables_ipaddr_to_numeric(&fw->ip.src));
else
strcpy(buf, xtables_ipaddr_to_anyname(&fw->ip.src));
strcat(buf, xtables_ipmask_to_numeric(&fw->ip.smsk));
printf(FMT("%-19s ","%s "), buf);
}
fputc(fw->ip.invflags & IPT_INV_DSTIP ? '!' : ' ', stdout);
if (fw->ip.dmsk.s_addr == 0L && !(format & FMT_NUMERIC))
printf(FMT("%-19s ","-> %s"), "anywhere");
else {
if (format & FMT_NUMERIC)
strcpy(buf, xtables_ipaddr_to_numeric(&fw->ip.dst));
else
strcpy(buf, xtables_ipaddr_to_anyname(&fw->ip.dst));
strcat(buf, xtables_ipmask_to_numeric(&fw->ip.dmsk));
printf(FMT("%-19s ","-> %s"), buf);
}
if (format & FMT_NOTABLE)
fputs(" ", stdout);
#ifdef IPT_F_GOTO
if(fw->ip.flags & IPT_F_GOTO)
printf("[goto] ");
#endif
IPT_MATCH_ITERATE(fw, print_match, &fw->ip, format & FMT_NUMERIC);
if (target) {
if (target->print)
/* Print the target information. */
target->print(&fw->ip, t, format & FMT_NUMERIC);
} else if (t->u.target_size != sizeof(*t))
printf("[%u bytes of unknown target data] ",
(unsigned int)(t->u.target_size - sizeof(*t)));
if (!(format & FMT_NONEWLINE))
fputc('\n', stdout);
}
static void
print_firewall_line(const struct ipt_entry *fw,
struct xtc_handle *const h)
{
struct xt_entry_target *t;
t = ipt_get_target((struct ipt_entry *)fw);
print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
}
static int
append_entry(const xt_chainlabel chain,
struct ipt_entry *fw,
unsigned int nsaddrs,
const struct in_addr saddrs[],
const struct in_addr smasks[],
unsigned int ndaddrs,
const struct in_addr daddrs[],
const struct in_addr dmasks[],
int verbose,
struct xtc_handle *handle)
{
unsigned int i, j;
int ret = 1;
for (i = 0; i < nsaddrs; i++) {
fw->ip.src.s_addr = saddrs[i].s_addr;
fw->ip.smsk.s_addr = smasks[i].s_addr;
for (j = 0; j < ndaddrs; j++) {
fw->ip.dst.s_addr = daddrs[j].s_addr;
fw->ip.dmsk.s_addr = dmasks[j].s_addr;
if (verbose)
print_firewall_line(fw, handle);
ret &= iptc_append_entry(chain, fw, handle);
}
}
return ret;
}
static int
replace_entry(const xt_chainlabel chain,
struct ipt_entry *fw,
unsigned int rulenum,
const struct in_addr *saddr, const struct in_addr *smask,
const struct in_addr *daddr, const struct in_addr *dmask,
int verbose,
struct xtc_handle *handle)
{
fw->ip.src.s_addr = saddr->s_addr;
fw->ip.dst.s_addr = daddr->s_addr;
fw->ip.smsk.s_addr = smask->s_addr;
fw->ip.dmsk.s_addr = dmask->s_addr;
if (verbose)
print_firewall_line(fw, handle);
return iptc_replace_entry(chain, fw, rulenum, handle);
}
static int
insert_entry(const xt_chainlabel chain,
struct ipt_entry *fw,
unsigned int rulenum,
unsigned int nsaddrs,
const struct in_addr saddrs[],
const struct in_addr smasks[],
unsigned int ndaddrs,
const struct in_addr daddrs[],
const struct in_addr dmasks[],
int verbose,
struct xtc_handle *handle)
{
unsigned int i, j;
int ret = 1;
for (i = 0; i < nsaddrs; i++) {
fw->ip.src.s_addr = saddrs[i].s_addr;
fw->ip.smsk.s_addr = smasks[i].s_addr;
for (j = 0; j < ndaddrs; j++) {
fw->ip.dst.s_addr = daddrs[j].s_addr;
fw->ip.dmsk.s_addr = dmasks[j].s_addr;
if (verbose)
print_firewall_line(fw, handle);
ret &= iptc_insert_entry(chain, fw, rulenum, handle);
}
}
return ret;
}
static unsigned char *
make_delete_mask(const struct xtables_rule_match *matches,
const struct xtables_target *target)
{
/* Establish mask for comparison */
unsigned int size;
const struct xtables_rule_match *matchp;
unsigned char *mask, *mptr;
size = sizeof(struct ipt_entry);
for (matchp = matches; matchp; matchp = matchp->next)
size += XT_ALIGN(sizeof(struct xt_entry_match)) + matchp->match->size;
mask = xtables_calloc(1, size
+ XT_ALIGN(sizeof(struct xt_entry_target))
+ target->size);
memset(mask, 0xFF, sizeof(struct ipt_entry));
mptr = mask + sizeof(struct ipt_entry);
for (matchp = matches; matchp; matchp = matchp->next) {
memset(mptr, 0xFF,
XT_ALIGN(sizeof(struct xt_entry_match))
+ matchp->match->userspacesize);
mptr += XT_ALIGN(sizeof(struct xt_entry_match)) + matchp->match->size;
}
memset(mptr, 0xFF,
XT_ALIGN(sizeof(struct xt_entry_target))
+ target->userspacesize);
return mask;
}
static int
delete_entry(const xt_chainlabel chain,
struct ipt_entry *fw,
unsigned int nsaddrs,
const struct in_addr saddrs[],
const struct in_addr smasks[],
unsigned int ndaddrs,
const struct in_addr daddrs[],
const struct in_addr dmasks[],
int verbose,
struct xtc_handle *handle,
struct xtables_rule_match *matches,
const struct xtables_target *target)
{
unsigned int i, j;
int ret = 1;
unsigned char *mask;
mask = make_delete_mask(matches, target);
for (i = 0; i < nsaddrs; i++) {
fw->ip.src.s_addr = saddrs[i].s_addr;
fw->ip.smsk.s_addr = smasks[i].s_addr;
for (j = 0; j < ndaddrs; j++) {
fw->ip.dst.s_addr = daddrs[j].s_addr;
fw->ip.dmsk.s_addr = dmasks[j].s_addr;
if (verbose)
print_firewall_line(fw, handle);
ret &= iptc_delete_entry(chain, fw, mask, handle);
}
}
free(mask);
return ret;
}
static int
check_entry(const xt_chainlabel chain, struct ipt_entry *fw,
unsigned int nsaddrs, const struct in_addr *saddrs,
const struct in_addr *smasks, unsigned int ndaddrs,
const struct in_addr *daddrs, const struct in_addr *dmasks,
bool verbose, struct xtc_handle *handle,
struct xtables_rule_match *matches,
const struct xtables_target *target)
{
unsigned int i, j;
int ret = 1;
unsigned char *mask;
mask = make_delete_mask(matches, target);
for (i = 0; i < nsaddrs; i++) {
fw->ip.src.s_addr = saddrs[i].s_addr;
fw->ip.smsk.s_addr = smasks[i].s_addr;
for (j = 0; j < ndaddrs; j++) {
fw->ip.dst.s_addr = daddrs[j].s_addr;
fw->ip.dmsk.s_addr = dmasks[j].s_addr;
if (verbose)
print_firewall_line(fw, handle);
ret &= iptc_check_entry(chain, fw, mask, handle);
}
}
free(mask);
return ret;
}
int
for_each_chain4(int (*fn)(const xt_chainlabel, int, struct xtc_handle *),
int verbose, int builtinstoo, struct xtc_handle *handle)
{
int ret = 1;
const char *chain;
char *chains;
unsigned int i, chaincount = 0;
chain = iptc_first_chain(handle);
while (chain) {
chaincount++;
chain = iptc_next_chain(handle);
}
chains = xtables_malloc(sizeof(xt_chainlabel) * chaincount);
i = 0;
chain = iptc_first_chain(handle);
while (chain) {
strcpy(chains + i*sizeof(xt_chainlabel), chain);
i++;
chain = iptc_next_chain(handle);
}
for (i = 0; i < chaincount; i++) {
if (!builtinstoo
&& iptc_builtin(chains + i*sizeof(xt_chainlabel),
handle) == 1)
continue;
ret &= fn(chains + i*sizeof(xt_chainlabel), verbose, handle);
}
free(chains);
return ret;
}
int
flush_entries4(const xt_chainlabel chain, int verbose,
struct xtc_handle *handle)
{
if (!chain)
return for_each_chain4(flush_entries4, verbose, 1, handle);
if (verbose)
fprintf(stdout, "Flushing chain `%s'\n", chain);
return iptc_flush_entries(chain, handle);
}
static int
zero_entries(const xt_chainlabel chain, int verbose,
struct xtc_handle *handle)
{
if (!chain)
return for_each_chain4(zero_entries, verbose, 1, handle);
if (verbose)
fprintf(stdout, "Zeroing chain `%s'\n", chain);
return iptc_zero_entries(chain, handle);
}
int
delete_chain4(const xt_chainlabel chain, int verbose,
struct xtc_handle *handle)
{
if (!chain)
return for_each_chain4(delete_chain4, verbose, 0, handle);
if (verbose)
fprintf(stdout, "Deleting chain `%s'\n", chain);
return iptc_delete_chain(chain, handle);
}
static int
list_entries(const xt_chainlabel chain, int rulenum, int verbose, int numeric,
int expanded, int linenumbers, struct xtc_handle *handle)
{
int found = 0;
unsigned int format;
const char *this;
format = FMT_OPTIONS;
if (!verbose)
format |= FMT_NOCOUNTS;
else
format |= FMT_VIA;
if (numeric)
format |= FMT_NUMERIC;
if (!expanded)
format |= FMT_KILOMEGAGIGA;
if (linenumbers)
format |= FMT_LINENUMBERS;
for (this = iptc_first_chain(handle);
this;
this = iptc_next_chain(handle)) {
const struct ipt_entry *i;
unsigned int num;
if (chain && strcmp(chain, this) != 0)
continue;
if (found) printf("\n");
if (!rulenum)
print_header(format, this, handle);
i = iptc_first_rule(this, handle);
num = 0;
while (i) {
num++;
if (!rulenum || num == rulenum)
print_firewall(i,
iptc_get_target(i, handle),
num,
format,
handle);
i = iptc_next_rule(i, handle);
}
found = 1;
}
errno = ENOENT;
return found;
}
static void print_proto(uint16_t proto, int invert)
{
if (proto) {
unsigned int i;
const char *invertstr = invert ? " !" : "";
const struct protoent *pent = getprotobynumber(proto);
if (pent) {
printf("%s -p %s", invertstr, pent->p_name);
return;
}
for (i = 0; xtables_chain_protos[i].name != NULL; ++i)
if (xtables_chain_protos[i].num == proto) {
printf("%s -p %s",
invertstr, xtables_chain_protos[i].name);
return;
}
printf("%s -p %u", invertstr, proto);
}
}
#define IP_PARTS_NATIVE(n) \
(unsigned int)((n)>>24)&0xFF, \
(unsigned int)((n)>>16)&0xFF, \
(unsigned int)((n)>>8)&0xFF, \
(unsigned int)((n)&0xFF)
#define IP_PARTS(n) IP_PARTS_NATIVE(ntohl(n))
/* This assumes that mask is contiguous, and byte-bounded. */
static void
print_iface(char letter, const char *iface, const unsigned char *mask,
int invert)
{
unsigned int i;
if (mask[0] == 0)
return;
printf("%s -%c ", invert ? " !" : "", letter);
for (i = 0; i < IFNAMSIZ; i++) {
if (mask[i] != 0) {
if (iface[i] != '\0')
printf("%c", iface[i]);
} else {
/* we can access iface[i-1] here, because
* a few lines above we make sure that mask[0] != 0 */
if (iface[i-1] != '\0')
printf("+");
break;
}
}
}
static int print_match_save(const struct xt_entry_match *e,
const struct ipt_ip *ip)
{
const struct xtables_match *match =
xtables_find_match(e->u.user.name, XTF_TRY_LOAD, NULL);
if (match) {
printf(" -m %s",
match->alias ? match->alias(e) : e->u.user.name);
/* some matches don't provide a save function */
if (match->save)
match->save(ip, e);
} else {
if (e->u.match_size) {
fprintf(stderr,
"Can't find library for match `%s'\n",
e->u.user.name);
exit(1);
}
}
return 0;
}
/* print a given ip including mask if neccessary */
static void print_ip(const char *prefix, uint32_t ip,
uint32_t mask, int invert)
{
uint32_t bits, hmask = ntohl(mask);
int i;
if (!mask && !ip && !invert)
return;
printf("%s %s %u.%u.%u.%u",
invert ? " !" : "",
prefix,
IP_PARTS(ip));
if (mask == 0xFFFFFFFFU) {
printf("/32");
return;
}
i = 32;
bits = 0xFFFFFFFEU;
while (--i >= 0 && hmask != bits)
bits <<= 1;
if (i >= 0)
printf("/%u", i);
else
printf("/%u.%u.%u.%u", IP_PARTS(mask));
}
/* We want this to be readable, so only print out neccessary fields.
* Because that's the kind of world I want to live in. */
void print_rule4(const struct ipt_entry *e,
struct xtc_handle *h, const char *chain, int counters)
{
const struct xt_entry_target *t;
const char *target_name;
/* print counters for iptables-save */
if (counters > 0)
printf("[%llu:%llu] ", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
/* print chain name */
printf("-A %s", chain);
/* Print IP part. */
print_ip("-s", e->ip.src.s_addr,e->ip.smsk.s_addr,
e->ip.invflags & IPT_INV_SRCIP);
print_ip("-d", e->ip.dst.s_addr, e->ip.dmsk.s_addr,
e->ip.invflags & IPT_INV_DSTIP);
print_iface('i', e->ip.iniface, e->ip.iniface_mask,
e->ip.invflags & IPT_INV_VIA_IN);
print_iface('o', e->ip.outiface, e->ip.outiface_mask,
e->ip.invflags & IPT_INV_VIA_OUT);
print_proto(e->ip.proto, e->ip.invflags & XT_INV_PROTO);
if (e->ip.flags & IPT_F_FRAG)
printf("%s -f",
e->ip.invflags & IPT_INV_FRAG ? " !" : "");
/* Print matchinfo part */
if (e->target_offset) {
IPT_MATCH_ITERATE(e, print_match_save, &e->ip);
}
/* print counters for iptables -R */
if (counters < 0)
printf(" -c %llu %llu", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
/* Print target name and targinfo part */
target_name = iptc_get_target(e, h);
t = ipt_get_target((struct ipt_entry *)e);
if (t->u.user.name[0]) {
const struct xtables_target *target =
xtables_find_target(t->u.user.name, XTF_TRY_LOAD);
if (!target) {
fprintf(stderr, "Can't find library for target `%s'\n",
t->u.user.name);
exit(1);
}
printf(" -j %s", target->alias ? target->alias(t) : target_name);
if (target->save)
target->save(&e->ip, t);
else {
/* If the target size is greater than xt_entry_target
* there is something to be saved, we just don't know
* how to print it */
if (t->u.target_size !=
sizeof(struct xt_entry_target)) {
fprintf(stderr, "Target `%s' is missing "
"save function\n",
t->u.user.name);
exit(1);
}
}
} else if (target_name && (*target_name != '\0'))
#ifdef IPT_F_GOTO
printf(" -%c %s", e->ip.flags & IPT_F_GOTO ? 'g' : 'j', target_name);
#else
printf(" -j %s", target_name);
#endif
printf("\n");
}
static int
list_rules(const xt_chainlabel chain, int rulenum, int counters,
struct xtc_handle *handle)
{
const char *this = NULL;
int found = 0;
if (counters)
counters = -1; /* iptables -c format */
/* Dump out chain names first,
* thereby preventing dependency conflicts */
if (!rulenum) for (this = iptc_first_chain(handle);
this;
this = iptc_next_chain(handle)) {
if (chain && strcmp(this, chain) != 0)
continue;
if (iptc_builtin(this, handle)) {
struct xt_counters count;
printf("-P %s %s", this, iptc_get_policy(this, &count, handle));
if (counters)
printf(" -c %llu %llu", (unsigned long long)count.pcnt, (unsigned long long)count.bcnt);
printf("\n");
} else {
printf("-N %s\n", this);
}
}
for (this = iptc_first_chain(handle);
this;
this = iptc_next_chain(handle)) {
const struct ipt_entry *e;
int num = 0;
if (chain && strcmp(this, chain) != 0)
continue;
/* Dump out rules */
e = iptc_first_rule(this, handle);
while(e) {
num++;
if (!rulenum || num == rulenum)
print_rule4(e, handle, this, counters);
e = iptc_next_rule(e, handle);
}
found = 1;
}
errno = ENOENT;
return found;
}
static struct ipt_entry *
generate_entry(const struct ipt_entry *fw,
struct xtables_rule_match *matches,
struct xt_entry_target *target)
{
unsigned int size;
struct xtables_rule_match *matchp;
struct ipt_entry *e;
size = sizeof(struct ipt_entry);
for (matchp = matches; matchp; matchp = matchp->next)
size += matchp->match->m->u.match_size;
e = xtables_malloc(size + target->u.target_size);
*e = *fw;
e->target_offset = size;
e->next_offset = size + target->u.target_size;
size = 0;
for (matchp = matches; matchp; matchp = matchp->next) {
memcpy(e->elems + size, matchp->match->m, matchp->match->m->u.match_size);
size += matchp->match->m->u.match_size;
}
memcpy(e->elems + size, target, target->u.target_size);
return e;
}
static void command_jump(struct iptables_command_state *cs)
{
size_t size;
set_option(&cs->options, OPT_JUMP, &cs->fw.ip.invflags, cs->invert);
cs->jumpto = parse_target(optarg);
/* TRY_LOAD (may be chain name) */
cs->target = xtables_find_target(cs->jumpto, XTF_TRY_LOAD);
if (cs->target == NULL)
return;
size = XT_ALIGN(sizeof(struct xt_entry_target))
+ cs->target->size;
cs->target->t = xtables_calloc(1, size);
cs->target->t->u.target_size = size;
if (cs->target->real_name == NULL) {
strcpy(cs->target->t->u.user.name, cs->jumpto);
} else {
/* Alias support for userspace side */
strcpy(cs->target->t->u.user.name, cs->target->real_name);
if (!(cs->target->ext_flags & XTABLES_EXT_ALIAS))
fprintf(stderr, "Notice: The %s target is converted into %s target "
"in rule listing and saving.\n",
cs->jumpto, cs->target->real_name);
}
cs->target->t->u.user.revision = cs->target->revision;
xs_init_target(cs->target);
if (cs->target->x6_options != NULL)
opts = xtables_options_xfrm(iptables_globals.orig_opts, opts,
cs->target->x6_options,
&cs->target->option_offset);
else
opts = xtables_merge_options(iptables_globals.orig_opts, opts,
cs->target->extra_opts,
&cs->target->option_offset);
if (opts == NULL)
xtables_error(OTHER_PROBLEM, "can't alloc memory!");
}
static void command_match(struct iptables_command_state *cs)
{
struct xtables_match *m;
size_t size;
if (cs->invert)
xtables_error(PARAMETER_PROBLEM,
"unexpected ! flag before --match");
m = xtables_find_match(optarg, XTF_LOAD_MUST_SUCCEED, &cs->matches);
size = XT_ALIGN(sizeof(struct xt_entry_match)) + m->size;
m->m = xtables_calloc(1, size);
m->m->u.match_size = size;
if (m->real_name == NULL) {
strcpy(m->m->u.user.name, m->name);
} else {
strcpy(m->m->u.user.name, m->real_name);
if (!(m->ext_flags & XTABLES_EXT_ALIAS))
fprintf(stderr, "Notice: the %s match is converted into %s match "
"in rule listing and saving.\n", m->name, m->real_name);
}
m->m->u.user.revision = m->revision;
xs_init_match(m);
if (m == m->next)
return;
/* Merge options for non-cloned matches */
if (m->x6_options != NULL)
opts = xtables_options_xfrm(iptables_globals.orig_opts, opts,
m->x6_options, &m->option_offset);
else if (m->extra_opts != NULL)
opts = xtables_merge_options(iptables_globals.orig_opts, opts,
m->extra_opts, &m->option_offset);
if (opts == NULL)
xtables_error(OTHER_PROBLEM, "can't alloc memory!");
}
int do_command4(int argc, char *argv[], char **table,
struct xtc_handle **handle, bool restore)
{
struct iptables_command_state cs;
struct ipt_entry *e = NULL;
unsigned int nsaddrs = 0, ndaddrs = 0;
struct in_addr *saddrs = NULL, *smasks = NULL;
struct in_addr *daddrs = NULL, *dmasks = NULL;
int verbose = 0;
bool wait = false;
const char *chain = NULL;
const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
const char *policy = NULL, *newname = NULL;
unsigned int rulenum = 0, command = 0;
const char *pcnt = NULL, *bcnt = NULL;
int ret = 1;
struct xtables_match *m;
struct xtables_rule_match *matchp;
struct xtables_target *t;
unsigned long long cnt;
memset(&cs, 0, sizeof(cs));
cs.jumpto = "";
cs.argv = argv;
/* re-set optind to 0 in case do_command4 gets called
* a second time */
optind = 0;
/* clear mflags in case do_command4 gets called a second time
* (we clear the global list of all matches for security)*/
for (m = xtables_matches; m; m = m->next)
m->mflags = 0;
for (t = xtables_targets; t; t = t->next) {
t->tflags = 0;
t->used = 0;
}
/* Suppress error messages: we may add new options if we
demand-load a protocol. */
opterr = 0;
opts = xt_params->orig_opts;
while ((cs.c = getopt_long(argc, argv,
"-:A:C:D:R:I:L::S::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:fbvwnt:m:xc:g:46",
opts, NULL)) != -1) {
switch (cs.c) {
/*
* Command selection
*/
case 'A':
add_command(&command, CMD_APPEND, CMD_NONE,
cs.invert);
chain = optarg;
break;
case 'C':
add_command(&command, CMD_CHECK, CMD_NONE,
cs.invert);
chain = optarg;
break;
case 'D':
add_command(&command, CMD_DELETE, CMD_NONE,
cs.invert);
chain = optarg;
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!') {
rulenum = parse_rulenumber(argv[optind++]);
command = CMD_DELETE_NUM;
}
break;
case 'R':
add_command(&command, CMD_REPLACE, CMD_NONE,
cs.invert);
chain = optarg;
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
rulenum = parse_rulenumber(argv[optind++]);
else
xtables_error(PARAMETER_PROBLEM,
"-%c requires a rule number",
cmd2char(CMD_REPLACE));
break;
case 'I':
add_command(&command, CMD_INSERT, CMD_NONE,
cs.invert);
chain = optarg;
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
rulenum = parse_rulenumber(argv[optind++]);
else rulenum = 1;
break;
case 'L':
add_command(&command, CMD_LIST,
CMD_ZERO | CMD_ZERO_NUM, cs.invert);
if (optarg) chain = optarg;
else if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
chain = argv[optind++];
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
rulenum = parse_rulenumber(argv[optind++]);
break;
case 'S':
add_command(&command, CMD_LIST_RULES,
CMD_ZERO|CMD_ZERO_NUM, cs.invert);
if (optarg) chain = optarg;
else if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
chain = argv[optind++];
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
rulenum = parse_rulenumber(argv[optind++]);
break;
case 'F':
add_command(&command, CMD_FLUSH, CMD_NONE,
cs.invert);
if (optarg) chain = optarg;
else if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
chain = argv[optind++];
break;
case 'Z':
add_command(&command, CMD_ZERO, CMD_LIST|CMD_LIST_RULES,
cs.invert);
if (optarg) chain = optarg;
else if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
chain = argv[optind++];
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!') {
rulenum = parse_rulenumber(argv[optind++]);
command = CMD_ZERO_NUM;
}
break;
case 'N':
parse_chain(optarg);
add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
cs.invert);
chain = optarg;
break;
case 'X':
add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
cs.invert);
if (optarg) chain = optarg;
else if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
chain = argv[optind++];
break;
case 'E':
add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
cs.invert);
chain = optarg;
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
newname = argv[optind++];
else
xtables_error(PARAMETER_PROBLEM,
"-%c requires old-chain-name and "
"new-chain-name",
cmd2char(CMD_RENAME_CHAIN));
break;
case 'P':
add_command(&command, CMD_SET_POLICY, CMD_NONE,
cs.invert);
chain = optarg;
if (optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
policy = argv[optind++];
else
xtables_error(PARAMETER_PROBLEM,
"-%c requires a chain and a policy",
cmd2char(CMD_SET_POLICY));
break;
case 'h':
if (!optarg)
optarg = argv[optind];
/* iptables -p icmp -h */
if (!cs.matches && cs.protocol)
xtables_find_match(cs.protocol,
XTF_TRY_LOAD, &cs.matches);
exit_printhelp(cs.matches);
/*
* Option selection
*/
case 'p':
set_option(&cs.options, OPT_PROTOCOL, &cs.fw.ip.invflags,
cs.invert);
/* Canonicalize into lower case */
for (cs.protocol = optarg; *cs.protocol; cs.protocol++)
*cs.protocol = tolower(*cs.protocol);
cs.protocol = optarg;
cs.fw.ip.proto = xtables_parse_protocol(cs.protocol);
if (cs.fw.ip.proto == 0
&& (cs.fw.ip.invflags & XT_INV_PROTO))
xtables_error(PARAMETER_PROBLEM,
"rule would never match protocol");
break;
case 's':
set_option(&cs.options, OPT_SOURCE, &cs.fw.ip.invflags,
cs.invert);
shostnetworkmask = optarg;
break;
case 'd':
set_option(&cs.options, OPT_DESTINATION, &cs.fw.ip.invflags,
cs.invert);
dhostnetworkmask = optarg;
break;
#ifdef IPT_F_GOTO
case 'g':
set_option(&cs.options, OPT_JUMP, &cs.fw.ip.invflags,
cs.invert);
cs.fw.ip.flags |= IPT_F_GOTO;
cs.jumpto = parse_target(optarg);
break;
#endif
case 'j':
command_jump(&cs);
break;
case 'i':
if (*optarg == '\0')
xtables_error(PARAMETER_PROBLEM,
"Empty interface is likely to be "
"undesired");
set_option(&cs.options, OPT_VIANAMEIN, &cs.fw.ip.invflags,
cs.invert);
xtables_parse_interface(optarg,
cs.fw.ip.iniface,
cs.fw.ip.iniface_mask);
break;
case 'o':
if (*optarg == '\0')
xtables_error(PARAMETER_PROBLEM,
"Empty interface is likely to be "
"undesired");
set_option(&cs.options, OPT_VIANAMEOUT, &cs.fw.ip.invflags,
cs.invert);
xtables_parse_interface(optarg,
cs.fw.ip.outiface,
cs.fw.ip.outiface_mask);
break;
case 'f':
set_option(&cs.options, OPT_FRAGMENT, &cs.fw.ip.invflags,
cs.invert);
cs.fw.ip.flags |= IPT_F_FRAG;
break;
case 'v':
if (!verbose)
set_option(&cs.options, OPT_VERBOSE,
&cs.fw.ip.invflags, cs.invert);
verbose++;
break;
case 'w':
if (restore) {
xtables_error(PARAMETER_PROBLEM,
"You cannot use `-w' from "
"iptables-restore");
}
wait = true;
break;
case 'm':
command_match(&cs);
break;
case 'n':
set_option(&cs.options, OPT_NUMERIC, &cs.fw.ip.invflags,
cs.invert);
break;
case 't':
if (cs.invert)
xtables_error(PARAMETER_PROBLEM,
"unexpected ! flag before --table");
*table = optarg;
break;
case 'x':
set_option(&cs.options, OPT_EXPANDED, &cs.fw.ip.invflags,
cs.invert);
break;
case 'V':
if (cs.invert)
printf("Not %s ;-)\n", prog_vers);
else
printf("%s v%s\n",
prog_name, prog_vers);
exit(0);
case '0':
set_option(&cs.options, OPT_LINENUMBERS, &cs.fw.ip.invflags,
cs.invert);
break;
case 'M':
xtables_modprobe_program = optarg;
break;
case 'c':
set_option(&cs.options, OPT_COUNTERS, &cs.fw.ip.invflags,
cs.invert);
pcnt = optarg;
bcnt = strchr(pcnt + 1, ',');
if (bcnt)
bcnt++;
if (!bcnt && optind < argc && argv[optind][0] != '-'
&& argv[optind][0] != '!')
bcnt = argv[optind++];
if (!bcnt)
xtables_error(PARAMETER_PROBLEM,
"-%c requires packet and byte counter",
opt2char(OPT_COUNTERS));
if (sscanf(pcnt, "%llu", &cnt) != 1)
xtables_error(PARAMETER_PROBLEM,
"-%c packet counter not numeric",
opt2char(OPT_COUNTERS));
cs.fw.counters.pcnt = cnt;
if (sscanf(bcnt, "%llu", &cnt) != 1)
xtables_error(PARAMETER_PROBLEM,
"-%c byte counter not numeric",
opt2char(OPT_COUNTERS));
cs.fw.counters.bcnt = cnt;
break;
case '4':
/* This is indeed the IPv4 iptables */
break;
case '6':
/* This is not the IPv6 ip6tables */
if (line != -1)
return 1; /* success: line ignored */
fprintf(stderr, "This is the IPv4 version of iptables.\n");
exit_tryhelp(2);
case 1: /* non option */
if (optarg[0] == '!' && optarg[1] == '\0') {
if (cs.invert)
xtables_error(PARAMETER_PROBLEM,
"multiple consecutive ! not"
" allowed");
cs.invert = TRUE;
optarg[0] = '\0';
continue;
}
fprintf(stderr, "Bad argument `%s'\n", optarg);
exit_tryhelp(2);
default:
if (command_default(&cs, &iptables_globals) == 1)
/* cf. ip6tables.c */
continue;
break;
}
cs.invert = FALSE;
}
if (strcmp(*table, "nat") == 0 &&
((policy != NULL && strcmp(policy, "DROP") == 0) ||
(cs.jumpto != NULL && strcmp(cs.jumpto, "DROP") == 0)))
xtables_error(PARAMETER_PROBLEM,
"\nThe \"nat\" table is not intended for filtering, "
"the use of DROP is therefore inhibited.\n\n");
for (matchp = cs.matches; matchp; matchp = matchp->next)
xtables_option_mfcall(matchp->match);
if (cs.target != NULL)
xtables_option_tfcall(cs.target);
/* Fix me: must put inverse options checking here --MN */
if (optind < argc)
xtables_error(PARAMETER_PROBLEM,
"unknown arguments found on commandline");
if (!command)
xtables_error(PARAMETER_PROBLEM, "no command specified");
if (cs.invert)
xtables_error(PARAMETER_PROBLEM,
"nothing appropriate following !");
if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND | CMD_CHECK)) {
if (!(cs.options & OPT_DESTINATION))
dhostnetworkmask = "0.0.0.0/0";
if (!(cs.options & OPT_SOURCE))
shostnetworkmask = "0.0.0.0/0";
}
if (shostnetworkmask)
xtables_ipparse_multiple(shostnetworkmask, &saddrs,
&smasks, &nsaddrs);
if (dhostnetworkmask)
xtables_ipparse_multiple(dhostnetworkmask, &daddrs,
&dmasks, &ndaddrs);
if ((nsaddrs > 1 || ndaddrs > 1) &&
(cs.fw.ip.invflags & (IPT_INV_SRCIP | IPT_INV_DSTIP)))
xtables_error(PARAMETER_PROBLEM, "! not allowed with multiple"
" source or destination IP addresses");
if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
xtables_error(PARAMETER_PROBLEM, "Replacement rule does not "
"specify a unique address");
generic_opt_check(command, cs.options);
/* Attempt to acquire the xtables lock */
if (!restore && !xtables_lock(wait)) {
fprintf(stderr, "Another app is currently holding the xtables lock. "
"Perhaps you want to use the -w option?\n");
xtables_free_opts(1);
exit(RESOURCE_PROBLEM);
}
/* only allocate handle if we weren't called with a handle */
if (!*handle)
*handle = iptc_init(*table);
/* try to insmod the module if iptc_init failed */
if (!*handle && xtables_load_ko(xtables_modprobe_program, false) != -1)
*handle = iptc_init(*table);
if (!*handle)
xtables_error(VERSION_PROBLEM,
"can't initialize iptables table `%s': %s",
*table, iptc_strerror(errno));
if (command == CMD_APPEND
|| command == CMD_DELETE
|| command == CMD_CHECK
|| command == CMD_INSERT
|| command == CMD_REPLACE) {
if (strcmp(chain, "PREROUTING") == 0
|| strcmp(chain, "INPUT") == 0) {
/* -o not valid with incoming packets. */
if (cs.options & OPT_VIANAMEOUT)
xtables_error(PARAMETER_PROBLEM,
"Can't use -%c with %s\n",
opt2char(OPT_VIANAMEOUT),
chain);
}
if (strcmp(chain, "POSTROUTING") == 0
|| strcmp(chain, "OUTPUT") == 0) {
/* -i not valid with outgoing packets */
if (cs.options & OPT_VIANAMEIN)
xtables_error(PARAMETER_PROBLEM,
"Can't use -%c with %s\n",
opt2char(OPT_VIANAMEIN),
chain);
}
if (cs.target && iptc_is_chain(cs.jumpto, *handle)) {
fprintf(stderr,
"Warning: using chain %s, not extension\n",
cs.jumpto);
if (cs.target->t)
free(cs.target->t);
cs.target = NULL;
}
/* If they didn't specify a target, or it's a chain
name, use standard. */
if (!cs.target
&& (strlen(cs.jumpto) == 0
|| iptc_is_chain(cs.jumpto, *handle))) {
size_t size;
cs.target = xtables_find_target(XT_STANDARD_TARGET,
XTF_LOAD_MUST_SUCCEED);
size = sizeof(struct xt_entry_target)
+ cs.target->size;
cs.target->t = xtables_calloc(1, size);
cs.target->t->u.target_size = size;
strcpy(cs.target->t->u.user.name, cs.jumpto);
if (!iptc_is_chain(cs.jumpto, *handle))
cs.target->t->u.user.revision = cs.target->revision;
xs_init_target(cs.target);
}
if (!cs.target) {
/* it is no chain, and we can't load a plugin.
* We cannot know if the plugin is corrupt, non
* existant OR if the user just misspelled a
* chain. */
#ifdef IPT_F_GOTO
if (cs.fw.ip.flags & IPT_F_GOTO)
xtables_error(PARAMETER_PROBLEM,
"goto '%s' is not a chain\n",
cs.jumpto);
#endif
xtables_find_target(cs.jumpto, XTF_LOAD_MUST_SUCCEED);
} else {
e = generate_entry(&cs.fw, cs.matches, cs.target->t);
free(cs.target->t);
}
}
switch (command) {
case CMD_APPEND:
ret = append_entry(chain, e,
nsaddrs, saddrs, smasks,
ndaddrs, daddrs, dmasks,
cs.options&OPT_VERBOSE,
*handle);
break;
case CMD_DELETE:
ret = delete_entry(chain, e,
nsaddrs, saddrs, smasks,
ndaddrs, daddrs, dmasks,
cs.options&OPT_VERBOSE,
*handle, cs.matches, cs.target);
break;
case CMD_DELETE_NUM:
ret = iptc_delete_num_entry(chain, rulenum - 1, *handle);
break;
case CMD_CHECK:
ret = check_entry(chain, e,
nsaddrs, saddrs, smasks,
ndaddrs, daddrs, dmasks,
cs.options&OPT_VERBOSE,
*handle, cs.matches, cs.target);
break;
case CMD_REPLACE:
ret = replace_entry(chain, e, rulenum - 1,
saddrs, smasks, daddrs, dmasks,
cs.options&OPT_VERBOSE, *handle);
break;
case CMD_INSERT:
ret = insert_entry(chain, e, rulenum - 1,
nsaddrs, saddrs, smasks,
ndaddrs, daddrs, dmasks,
cs.options&OPT_VERBOSE,
*handle);
break;
case CMD_FLUSH:
ret = flush_entries4(chain, cs.options&OPT_VERBOSE, *handle);
break;
case CMD_ZERO:
ret = zero_entries(chain, cs.options&OPT_VERBOSE, *handle);
break;
case CMD_ZERO_NUM:
ret = iptc_zero_counter(chain, rulenum, *handle);
break;
case CMD_LIST:
case CMD_LIST|CMD_ZERO:
case CMD_LIST|CMD_ZERO_NUM:
ret = list_entries(chain,
rulenum,
cs.options&OPT_VERBOSE,
cs.options&OPT_NUMERIC,
cs.options&OPT_EXPANDED,
cs.options&OPT_LINENUMBERS,
*handle);
if (ret && (command & CMD_ZERO))
ret = zero_entries(chain,
cs.options&OPT_VERBOSE, *handle);
if (ret && (command & CMD_ZERO_NUM))
ret = iptc_zero_counter(chain, rulenum, *handle);
break;
case CMD_LIST_RULES:
case CMD_LIST_RULES|CMD_ZERO:
case CMD_LIST_RULES|CMD_ZERO_NUM:
ret = list_rules(chain,
rulenum,
cs.options&OPT_VERBOSE,
*handle);
if (ret && (command & CMD_ZERO))
ret = zero_entries(chain,
cs.options&OPT_VERBOSE, *handle);
if (ret && (command & CMD_ZERO_NUM))
ret = iptc_zero_counter(chain, rulenum, *handle);
break;
case CMD_NEW_CHAIN:
ret = iptc_create_chain(chain, *handle);
break;
case CMD_DELETE_CHAIN:
ret = delete_chain4(chain, cs.options&OPT_VERBOSE, *handle);
break;
case CMD_RENAME_CHAIN:
ret = iptc_rename_chain(chain, newname, *handle);
break;
case CMD_SET_POLICY:
ret = iptc_set_policy(chain, policy, cs.options&OPT_COUNTERS ? &cs.fw.counters : NULL, *handle);
break;
default:
/* We should never reach this... */
exit_tryhelp(2);
}
if (verbose > 1)
dump_entries(*handle);
xtables_rule_matches_free(&cs.matches);
if (e != NULL) {
free(e);
e = NULL;
}
free(saddrs);
free(smasks);
free(daddrs);
free(dmasks);
xtables_free_opts(1);
return ret;
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Converts from simple xml iptables format to iptables-save format
Copyright 2006 UfoMechanic
Author: azez@ufomechanic.net
This code is distributed and licensed under the terms of GNU GPL v2
This sample usage outputs roughly want goes in
iptables-save | iptables-xml -c | xsltproc iptables.xslt -
-->
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method = "text" />
<xsl:strip-space elements="*" />
<!-- output conditions of a rule but not an action -->
<xsl:template match="iptables-rules/table/chain/rule/conditions/*">
<!-- <match> is the psuedo module when a match module doesn't need to be loaded
and when -m does not need to be inserted -->
<xsl:if test="name() != 'match'">
<xsl:text> -m </xsl:text><xsl:value-of select="name()"/>
</xsl:if>
<xsl:apply-templates select="node()"/>
</xsl:template>
<!-- delete the actions or conditions containers, and process child nodes -->
<xsl:template match="iptables-rules/table/chain/rule/actions|table/chain/rule/conditions">
<xsl:apply-templates select="*"/>
</xsl:template>
<xsl:template match="iptables-rules/table/chain/rule/actions/goto">
<xsl:text> -g </xsl:text>
<xsl:apply-templates select="*"/>
<xsl:text>&#xA;</xsl:text>
</xsl:template>
<xsl:template match="iptables-rules/table/chain/rule/actions/call">
<xsl:text> -j </xsl:text>
<xsl:apply-templates select="*"/>
<xsl:text>&#xA;</xsl:text>
</xsl:template>
<!-- all other actions are module actions -->
<xsl:template match="iptables-rules/table/chain/rule/actions/*">
<xsl:text> -j </xsl:text><xsl:value-of select="name()"/>
<xsl:apply-templates select="*"/>
<xsl:text>&#xA;</xsl:text>
</xsl:template>
<!-- all child action nodes -->
<xsl:template match="iptables-rules/table/chain/rule/actions//*|iptables-rules/table/chain/rule/conditions//*" priority="0">
<xsl:if test="@invert=1"><xsl:text> !</xsl:text></xsl:if>
<xsl:text> -</xsl:text>
<!-- if length of name is 1 character, then only do 1 - not 2 -->
<xsl:if test="string-length(name())&gt;1">
<xsl:text>-</xsl:text>
</xsl:if>
<xsl:value-of select="name()"/>
<xsl:text> </xsl:text>
<xsl:apply-templates select="node()"/>
</xsl:template>
<xsl:template match="iptables-rules/table/chain/rule/actions/call/*|iptables-rules/table/chain/rule/actions/goto/*">
<xsl:value-of select="name()"/>
<!-- I bet there are no child nodes, should we risk it? -->
<xsl:apply-templates select="node()"/>
</xsl:template>
<!-- output the head of the rule, and any conditions -->
<xsl:template name="rule-head">
<xsl:if test="string-length(@packet-count)+string-length(@byte-count)">
<xsl:call-template name="counters"><xsl:with-param name="node" select="."/></xsl:call-template>
<xsl:text> </xsl:text>
</xsl:if>
<xsl:text>-A </xsl:text><!-- a rule must be under a chain -->
<xsl:value-of select="../@name" />
<xsl:apply-templates select="conditions"/>
</xsl:template>
<!-- Output a single rule, perhaps as multiple rules if we have more than one action -->
<xsl:template match="iptables-rules/table/chain/rule">
<xsl:choose>
<xsl:when test="count(actions/*)&gt;0">
<xsl:for-each select="actions/*">
<!-- and a for-each to re-select the rule as the current node, to write the rule-head -->
<xsl:for-each select="../..">
<xsl:call-template name="rule-head"/>
</xsl:for-each>
<!-- now write the this action -->
<xsl:apply-templates select="."/>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<!-- no need to loop if there are no actions, just output conditions -->
<xsl:call-template name="rule-head"/>
<xsl:text>&#xA;</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="iptables-rules/table">
<xsl:text># Generated by iptables.xslt&#xA;</xsl:text>
<xsl:text>*</xsl:text><xsl:value-of select="@name"/><xsl:text>&#xA;</xsl:text>
<!-- Loop through each chain and output the chain header -->
<xsl:for-each select="chain">
<xsl:text>:</xsl:text>
<xsl:value-of select="@name"/>
<xsl:text> </xsl:text>
<xsl:choose>
<xsl:when test="not(string-length(@policy))"><xsl:text>-</xsl:text></xsl:when>
<xsl:otherwise><xsl:value-of select="@policy"/></xsl:otherwise>
</xsl:choose>
<xsl:text> </xsl:text>
<xsl:call-template name="counters"><xsl:with-param name="node" select="."/></xsl:call-template>
<xsl:text>&#xA;</xsl:text>
</xsl:for-each>
<!-- Loop through each chain and output the rules -->
<xsl:apply-templates select="node()"/>
<xsl:text>COMMIT&#xA;# Completed&#xA;</xsl:text>
</xsl:template>
<xsl:template name="counters">
<xsl:param name="node"/>
<xsl:text>[</xsl:text>
<xsl:if test="string-length($node/@packet-count)"><xsl:value-of select="$node/@packet-count"/></xsl:if>
<xsl:if test="string-length($node/@packet-count)=0">0</xsl:if>
<xsl:text>:</xsl:text>
<xsl:if test="string-length($node/@byte-count)"><xsl:value-of select="$node/@byte-count"/></xsl:if>
<xsl:if test="string-length($node/@byte-count)=0">0</xsl:if>
<xsl:text>]</xsl:text>
</xsl:template>
<!-- the bit that automatically recurses for us, NOTE: we use * not node(), we don't want to copy every white space text -->
<xsl:template match="@*|node()">
<xsl:copy>
<!-- with libxslt xsltproc we can't do @*|node() or the nodes may get processed before the attributes -->
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:transform>
#include <getopt.h>
#include <libgen.h>
#include <netdb.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <xtables.h>
#include "xshared.h"
#define XT_SOCKET_NAME "xtables"
#define XT_SOCKET_LEN 8
/*
* Print out any special helps. A user might like to be able to add a --help
* to the commandline, and see expected results. So we call help for all
* specified matches and targets.
*/
void print_extension_helps(const struct xtables_target *t,
const struct xtables_rule_match *m)
{
for (; t != NULL; t = t->next) {
if (t->used) {
printf("\n");
if (t->help == NULL)
printf("%s does not take any options\n",
t->name);
else
t->help();
}
}
for (; m != NULL; m = m->next) {
printf("\n");
if (m->match->help == NULL)
printf("%s does not take any options\n",
m->match->name);
else
m->match->help();
}
}
const char *
proto_to_name(uint8_t proto, int nolookup)
{
unsigned int i;
if (proto && !nolookup) {
struct protoent *pent = getprotobynumber(proto);
if (pent)
return pent->p_name;
}
for (i = 0; xtables_chain_protos[i].name != NULL; ++i)
if (xtables_chain_protos[i].num == proto)
return xtables_chain_protos[i].name;
return NULL;
}
static struct xtables_match *
find_proto(const char *pname, enum xtables_tryload tryload,
int nolookup, struct xtables_rule_match **matches)
{
unsigned int proto;
if (xtables_strtoui(pname, NULL, &proto, 0, UINT8_MAX)) {
const char *protoname = proto_to_name(proto, nolookup);
if (protoname)
return xtables_find_match(protoname, tryload, matches);
} else
return xtables_find_match(pname, tryload, matches);
return NULL;
}
/*
* Some explanations (after four different bugs in 3 different releases): If
* we encounter a parameter, that has not been parsed yet, it's not an option
* of an explicitly loaded match or a target. However, we support implicit
* loading of the protocol match extension. '-p tcp' means 'l4 proto 6' and at
* the same time 'load tcp protocol match on demand if we specify --dport'.
*
* To make this work, we need to make sure:
* - the parameter has not been parsed by a match (m above)
* - a protocol has been specified
* - the protocol extension has not been loaded yet, or is loaded and unused
* [think of ip6tables-restore!]
* - the protocol extension can be successively loaded
*/
static bool should_load_proto(struct iptables_command_state *cs)
{
if (cs->protocol == NULL)
return false;
if (find_proto(cs->protocol, XTF_DONT_LOAD,
cs->options & OPT_NUMERIC, NULL) == NULL)
return true;
return !cs->proto_used;
}
struct xtables_match *load_proto(struct iptables_command_state *cs)
{
if (!should_load_proto(cs))
return NULL;
return find_proto(cs->protocol, XTF_TRY_LOAD,
cs->options & OPT_NUMERIC, &cs->matches);
}
int command_default(struct iptables_command_state *cs,
struct xtables_globals *gl)
{
struct xtables_rule_match *matchp;
struct xtables_match *m;
if (cs->target != NULL &&
(cs->target->parse != NULL || cs->target->x6_parse != NULL) &&
cs->c >= cs->target->option_offset &&
cs->c < cs->target->option_offset + XT_OPTION_OFFSET_SCALE) {
xtables_option_tpcall(cs->c, cs->argv, cs->invert,
cs->target, &cs->fw);
return 0;
}
for (matchp = cs->matches; matchp; matchp = matchp->next) {
m = matchp->match;
if (matchp->completed ||
(m->x6_parse == NULL && m->parse == NULL))
continue;
if (cs->c < matchp->match->option_offset ||
cs->c >= matchp->match->option_offset + XT_OPTION_OFFSET_SCALE)
continue;
xtables_option_mpcall(cs->c, cs->argv, cs->invert, m, &cs->fw);
return 0;
}
/* Try loading protocol */
m = load_proto(cs);
if (m != NULL) {
size_t size;
cs->proto_used = 1;
size = XT_ALIGN(sizeof(struct xt_entry_match)) + m->size;
m->m = xtables_calloc(1, size);
m->m->u.match_size = size;
strcpy(m->m->u.user.name, m->name);
m->m->u.user.revision = m->revision;
xs_init_match(m);
if (m->x6_options != NULL)
gl->opts = xtables_options_xfrm(gl->orig_opts,
gl->opts,
m->x6_options,
&m->option_offset);
else
gl->opts = xtables_merge_options(gl->orig_opts,
gl->opts,
m->extra_opts,
&m->option_offset);
if (gl->opts == NULL)
xtables_error(OTHER_PROBLEM, "can't alloc memory!");
optind--;
/* Indicate to rerun getopt *immediately* */
return 1;
}
if (cs->c == ':')
xtables_error(PARAMETER_PROBLEM, "option \"%s\" "
"requires an argument", cs->argv[optind-1]);
if (cs->c == '?')
xtables_error(PARAMETER_PROBLEM, "unknown option "
"\"%s\"", cs->argv[optind-1]);
xtables_error(PARAMETER_PROBLEM, "Unknown arg \"%s\"", optarg);
return 0;
}
static mainfunc_t subcmd_get(const char *cmd, const struct subcommand *cb)
{
for (; cb->name != NULL; ++cb)
if (strcmp(cb->name, cmd) == 0)
return cb->main;
return NULL;
}
int subcmd_main(int argc, char **argv, const struct subcommand *cb)
{
const char *cmd = basename(*argv);
mainfunc_t f = subcmd_get(cmd, cb);
if (f == NULL && argc > 1) {
/*
* Unable to find a main method for our command name?
* Let's try again with the first argument!
*/
++argv;
--argc;
f = subcmd_get(*argv, cb);
}
/* now we should have a valid function pointer */
if (f != NULL)
return f(argc, argv);
fprintf(stderr, "ERROR: No valid subcommand given.\nValid subcommands:\n");
for (; cb->name != NULL; ++cb)
fprintf(stderr, " * %s\n", cb->name);
exit(EXIT_FAILURE);
}
void xs_init_target(struct xtables_target *target)
{
if (target->udata_size != 0) {
free(target->udata);
target->udata = calloc(1, target->udata_size);
if (target->udata == NULL)
xtables_error(RESOURCE_PROBLEM, "malloc");
}
if (target->init != NULL)
target->init(target->t);
}
void xs_init_match(struct xtables_match *match)
{
if (match->udata_size != 0) {
/*
* As soon as a subsequent instance of the same match
* is used, e.g. "-m time -m time", the first instance
* is no longer reachable anyway, so we can free udata.
* Same goes for target.
*/
free(match->udata);
match->udata = calloc(1, match->udata_size);
if (match->udata == NULL)
xtables_error(RESOURCE_PROBLEM, "malloc");
}
if (match->init != NULL)
match->init(match->m);
}
bool xtables_lock(bool wait)
{
int i = 0, ret, xt_socket;
struct sockaddr_un xt_addr;
memset(&xt_addr, 0, sizeof(xt_addr));
xt_addr.sun_family = AF_UNIX;
strcpy(xt_addr.sun_path+1, XT_SOCKET_NAME);
xt_socket = socket(AF_UNIX, SOCK_STREAM, 0);
/* If we can't even create a socket, fall back to prior (lockless) behavior */
if (xt_socket < 0)
return true;
while (1) {
ret = bind(xt_socket, (struct sockaddr*)&xt_addr,
offsetof(struct sockaddr_un, sun_path)+XT_SOCKET_LEN);
if (ret == 0)
return true;
else if (wait == false)
return false;
if (++i % 2 == 0)
fprintf(stderr, "Another app is currently holding the xtables lock; "
"waiting for it to exit...\n");
sleep(1);
}
}
#ifndef IPTABLES_XSHARED_H
#define IPTABLES_XSHARED_H 1
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <netinet/in.h>
#include <net/if.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
enum {
OPT_NONE = 0,
OPT_NUMERIC = 1 << 0,
OPT_SOURCE = 1 << 1,
OPT_DESTINATION = 1 << 2,
OPT_PROTOCOL = 1 << 3,
OPT_JUMP = 1 << 4,
OPT_VERBOSE = 1 << 5,
OPT_EXPANDED = 1 << 6,
OPT_VIANAMEIN = 1 << 7,
OPT_VIANAMEOUT = 1 << 8,
OPT_LINENUMBERS = 1 << 9,
OPT_COUNTERS = 1 << 10,
};
struct xtables_globals;
struct xtables_rule_match;
struct xtables_target;
/**
* xtables_afinfo - protocol family dependent information
* @kmod: kernel module basename (e.g. "ip_tables")
* @proc_exists: file which exists in procfs when module already loaded
* @libprefix: prefix of .so library name (e.g. "libipt_")
* @family: nfproto family
* @ipproto: used by setsockopt (e.g. IPPROTO_IP)
* @so_rev_match: optname to check revision support of match
* @so_rev_target: optname to check revision support of target
*/
struct xtables_afinfo {
const char *kmod;
const char *proc_exists;
const char *libprefix;
uint8_t family;
uint8_t ipproto;
int so_rev_match;
int so_rev_target;
};
struct iptables_command_state {
union {
struct ipt_entry fw;
struct ip6t_entry fw6;
};
int invert;
int c;
unsigned int options;
struct xtables_rule_match *matches;
struct xtables_target *target;
char *protocol;
int proto_used;
const char *jumpto;
char **argv;
};
typedef int (*mainfunc_t)(int, char **);
struct subcommand {
const char *name;
mainfunc_t main;
};
enum {
XT_OPTION_OFFSET_SCALE = 256,
};
extern void print_extension_helps(const struct xtables_target *,
const struct xtables_rule_match *);
extern const char *proto_to_name(uint8_t, int);
extern int command_default(struct iptables_command_state *,
struct xtables_globals *);
extern struct xtables_match *load_proto(struct iptables_command_state *);
extern int subcmd_main(int, char **, const struct subcommand *);
extern void xs_init_target(struct xtables_target *);
extern void xs_init_match(struct xtables_match *);
extern bool xtables_lock(bool wait);
extern const struct xtables_afinfo *afinfo;
#endif /* IPTABLES_XSHARED_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "xshared.h"
#include "xtables-multi.h"
#ifdef ENABLE_IPV4
#include "iptables-multi.h"
#endif
#ifdef ENABLE_IPV6
#include "ip6tables-multi.h"
#endif
static const struct subcommand multi_subcommands[] = {
#ifdef ENABLE_IPV4
{"iptables", iptables_main},
{"main4", iptables_main},
{"iptables-save", iptables_save_main},
{"save4", iptables_save_main},
{"iptables-restore", iptables_restore_main},
{"restore4", iptables_restore_main},
#endif
{"iptables-xml", iptables_xml_main},
{"xml", iptables_xml_main},
#ifdef ENABLE_IPV6
{"ip6tables", ip6tables_main},
{"main6", ip6tables_main},
{"ip6tables-save", ip6tables_save_main},
{"save6", ip6tables_save_main},
{"ip6tables-restore", ip6tables_restore_main},
{"restore6", ip6tables_restore_main},
#endif
{NULL},
};
int main(int argc, char **argv)
{
return subcmd_main(argc, argv, multi_subcommands);
}
#ifndef _XTABLES_MULTI_H
#define _XTABLES_MULTI_H 1
extern int iptables_xml_main(int, char **);
#endif /* _XTABLES_MULTI_H */
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
xtlibdir=@xtlibdir@
includedir=@includedir@
Name: xtables
Description: Shared Xtables code for extensions and iproute2
Version: @PACKAGE_VERSION@
Cflags: -I${includedir}
Libs: -L${libdir} -lxtables
Libs.private: -ldl
# -*- Makefile -*-
AM_CFLAGS = ${regular_CFLAGS}
AM_CPPFLAGS = ${regular_CPPFLAGS} -I${top_builddir}/include -I${top_srcdir}/include
libipq_la_SOURCES = libipq.c
lib_LTLIBRARIES = libipq.la
man_MANS = ipq_create_handle.3 ipq_destroy_handle.3 ipq_errstr.3 \
ipq_get_msgerr.3 ipq_get_packet.3 ipq_message_type.3 \
ipq_perror.3 ipq_read.3 ipq_set_mode.3 ipq_set_verdict.3 \
libipq.3
pkgconfig_DATA = libipq.pc
# Makefile.in generated by automake 1.11.6 from Makefile.am.
# @configure_input@
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
# Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
# -*- Makefile -*-
VPATH = @srcdir@
am__make_dryrun = \
{ \
am__dry=no; \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \
| grep '^AM OK$$' >/dev/null || am__dry=yes;; \
*) \
for am__flg in $$MAKEFLAGS; do \
case $$am__flg in \
*=*|--*) ;; \
*n*) am__dry=yes; break;; \
esac; \
done;; \
esac; \
test $$am__dry = yes; \
}
pkgincludedir = $(includedir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkglibexecdir = $(libexecdir)/@PACKAGE@
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
subdir = libipq
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
$(srcdir)/libipq.pc.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_linker_flags.m4 \
$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES = libipq.pc
CONFIG_CLEAN_VPATH_FILES =
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
am__install_max = 40
am__nobase_strip_setup = \
srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
am__nobase_strip = \
for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
am__nobase_list = $(am__nobase_strip_setup); \
for p in $$list; do echo "$$p $$p"; done | \
sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
$(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
if (++n[$$2] == $(am__install_max)) \
{ print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
END { for (dir in files) print dir, files[dir] }'
am__base_list = \
sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
am__uninstall_files_from_dir = { \
test -z "$$files" \
|| { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
|| { echo " ( cd '$$dir' && rm -f" $$files ")"; \
$(am__cd) "$$dir" && rm -f $$files; }; \
}
am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(man3dir)" \
"$(DESTDIR)$(pkgconfigdir)"
LTLIBRARIES = $(lib_LTLIBRARIES)
libipq_la_LIBADD =
am_libipq_la_OBJECTS = libipq.lo
libipq_la_OBJECTS = $(am_libipq_la_OBJECTS)
DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp
am__depfiles_maybe = depfiles
am__mv = mv -f
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
--mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
$(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
CCLD = $(CC)
LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
--mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
$(LDFLAGS) -o $@
SOURCES = $(libipq_la_SOURCES)
DIST_SOURCES = $(libipq_la_SOURCES)
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
man3dir = $(mandir)/man3
NROFF = nroff
MANS = $(man_MANS)
DATA = $(pkgconfig_DATA)
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
pkgdatadir = @pkgdatadir@
ACLOCAL = @ACLOCAL@
AMTAR = @AMTAR@
AR = @AR@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
CFLAGS = @CFLAGS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CYGPATH_W = @CYGPATH_W@
DEFS = @DEFS@
DEPDIR = @DEPDIR@
DLLTOOL = @DLLTOOL@
DSYMUTIL = @DSYMUTIL@
DUMPBIN = @DUMPBIN@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
EXEEXT = @EXEEXT@
FGREP = @FGREP@
GREP = @GREP@
INSTALL = @INSTALL@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
LD = @LD@
LDFLAGS = @LDFLAGS@
LIBOBJS = @LIBOBJS@
LIBS = @LIBS@
LIBTOOL = @LIBTOOL@
LIPO = @LIPO@
LN_S = @LN_S@
LTLIBOBJS = @LTLIBOBJS@
MAKEINFO = @MAKEINFO@
MANIFEST_TOOL = @MANIFEST_TOOL@
MKDIR_P = @MKDIR_P@
NM = @NM@
NMEDIT = @NMEDIT@
OBJDUMP = @OBJDUMP@
OBJEXT = @OBJEXT@
OTOOL = @OTOOL@
OTOOL64 = @OTOOL64@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_URL = @PACKAGE_URL@
PACKAGE_VERSION = @PACKAGE_VERSION@
PATH_SEPARATOR = @PATH_SEPARATOR@
PKG_CONFIG = @PKG_CONFIG@
PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
RANLIB = @RANLIB@
SED = @SED@
SET_MAKE = @SET_MAKE@
SHELL = @SHELL@
STRIP = @STRIP@
VERSION = @VERSION@
abs_builddir = @abs_builddir@
abs_srcdir = @abs_srcdir@
abs_top_builddir = @abs_top_builddir@
abs_top_srcdir = @abs_top_srcdir@
ac_ct_AR = @ac_ct_AR@
ac_ct_CC = @ac_ct_CC@
ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
am__tar = @am__tar@
am__untar = @am__untar@
bindir = @bindir@
blacklist_modules = @blacklist_modules@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
builddir = @builddir@
datadir = @datadir@
datarootdir = @datarootdir@
docdir = @docdir@
dvidir = @dvidir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
htmldir = @htmldir@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
kbuilddir = @kbuilddir@
kinclude_CPPFLAGS = @kinclude_CPPFLAGS@
ksourcedir = @ksourcedir@
libdir = @libdir@
libexecdir = @libexecdir@
libiptc_LDFLAGS2 = @libiptc_LDFLAGS2@
libnetfilter_conntrack_CFLAGS = @libnetfilter_conntrack_CFLAGS@
libnetfilter_conntrack_LIBS = @libnetfilter_conntrack_LIBS@
libnfnetlink_CFLAGS = @libnfnetlink_CFLAGS@
libnfnetlink_LIBS = @libnfnetlink_LIBS@
libxtables_vage = @libxtables_vage@
libxtables_vcurrent = @libxtables_vcurrent@
libxtables_vmajor = @libxtables_vmajor@
localedir = @localedir@
localstatedir = @localstatedir@
mandir = @mandir@
mkdir_p = @mkdir_p@
noundef_LDFLAGS = @noundef_LDFLAGS@
oldincludedir = @oldincludedir@
pdfdir = @pdfdir@
pkgconfigdir = @pkgconfigdir@
prefix = @prefix@
program_transform_name = @program_transform_name@
psdir = @psdir@
regular_CFLAGS = @regular_CFLAGS@
regular_CPPFLAGS = @regular_CPPFLAGS@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
srcdir = @srcdir@
sysconfdir = @sysconfdir@
target_alias = @target_alias@
top_build_prefix = @top_build_prefix@
top_builddir = @top_builddir@
top_srcdir = @top_srcdir@
xtlibdir = @xtlibdir@
AM_CFLAGS = ${regular_CFLAGS}
AM_CPPFLAGS = ${regular_CPPFLAGS} -I${top_builddir}/include -I${top_srcdir}/include
libipq_la_SOURCES = libipq.c
lib_LTLIBRARIES = libipq.la
man_MANS = ipq_create_handle.3 ipq_destroy_handle.3 ipq_errstr.3 \
ipq_get_msgerr.3 ipq_get_packet.3 ipq_message_type.3 \
ipq_perror.3 ipq_read.3 ipq_set_mode.3 ipq_set_verdict.3 \
libipq.3
pkgconfig_DATA = libipq.pc
all: all-am
.SUFFIXES:
.SUFFIXES: .c .lo .o .obj
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu libipq/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --gnu libipq/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
libipq.pc: $(top_builddir)/config.status $(srcdir)/libipq.pc.in
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
install-libLTLIBRARIES: $(lib_LTLIBRARIES)
@$(NORMAL_INSTALL)
@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
list2=; for p in $$list; do \
if test -f $$p; then \
list2="$$list2 $$p"; \
else :; fi; \
done; \
test -z "$$list2" || { \
echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \
$(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \
echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
$(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
}
uninstall-libLTLIBRARIES:
@$(NORMAL_UNINSTALL)
@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
for p in $$list; do \
$(am__strip_dir) \
echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \
$(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \
done
clean-libLTLIBRARIES:
-test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
@list='$(lib_LTLIBRARIES)'; for p in $$list; do \
dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
test "$$dir" != "$$p" || dir=.; \
echo "rm -f \"$${dir}/so_locations\""; \
rm -f "$${dir}/so_locations"; \
done
libipq.la: $(libipq_la_OBJECTS) $(libipq_la_DEPENDENCIES) $(EXTRA_libipq_la_DEPENDENCIES)
$(LINK) -rpath $(libdir) $(libipq_la_OBJECTS) $(libipq_la_LIBADD) $(LIBS)
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libipq.Plo@am__quote@
.c.o:
@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(COMPILE) -c $<
.c.obj:
@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
.c.lo:
@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
install-man3: $(man_MANS)
@$(NORMAL_INSTALL)
@list1=''; \
list2='$(man_MANS)'; \
test -n "$(man3dir)" \
&& test -n "`echo $$list1$$list2`" \
|| exit 0; \
echo " $(MKDIR_P) '$(DESTDIR)$(man3dir)'"; \
$(MKDIR_P) "$(DESTDIR)$(man3dir)" || exit 1; \
{ for i in $$list1; do echo "$$i"; done; \
if test -n "$$list2"; then \
for i in $$list2; do echo "$$i"; done \
| sed -n '/\.3[a-z]*$$/p'; \
fi; \
} | while read p; do \
if test -f $$p; then d=; else d="$(srcdir)/"; fi; \
echo "$$d$$p"; echo "$$p"; \
done | \
sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
-e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
sed 'N;N;s,\n, ,g' | { \
list=; while read file base inst; do \
if test "$$base" = "$$inst"; then list="$$list $$file"; else \
echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
$(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \
fi; \
done; \
for i in $$list; do echo "$$i"; done | $(am__base_list) | \
while read files; do \
test -z "$$files" || { \
echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \
$(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \
done; }
uninstall-man3:
@$(NORMAL_UNINSTALL)
@list=''; test -n "$(man3dir)" || exit 0; \
files=`{ for i in $$list; do echo "$$i"; done; \
l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
sed -n '/\.3[a-z]*$$/p'; \
} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
-e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
dir='$(DESTDIR)$(man3dir)'; $(am__uninstall_files_from_dir)
install-pkgconfigDATA: $(pkgconfig_DATA)
@$(NORMAL_INSTALL)
@list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$(DESTDIR)$(pkgconfigdir)'"; \
$(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)" || exit 1; \
fi; \
for p in $$list; do \
if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
echo "$$d$$p"; \
done | $(am__base_list) | \
while read files; do \
echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pkgconfigdir)'"; \
$(INSTALL_DATA) $$files "$(DESTDIR)$(pkgconfigdir)" || exit $$?; \
done
uninstall-pkgconfigDATA:
@$(NORMAL_UNINSTALL)
@list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \
files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
dir='$(DESTDIR)$(pkgconfigdir)'; $(am__uninstall_files_from_dir)
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
set x; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: CTAGS
CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@list='$(MANS)'; if test -n "$$list"; then \
list=`for p in $$list; do \
if test -f $$p; then d=; else d="$(srcdir)/"; fi; \
if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
if test -n "$$list" && \
grep 'ab help2man is required to generate this page' $$list >/dev/null; then \
echo "error: found man pages containing the \`missing help2man' replacement text:" >&2; \
grep -l 'ab help2man is required to generate this page' $$list | sed 's/^/ /' >&2; \
echo " to fix them, install help2man, remove and regenerate the man pages;" >&2; \
echo " typically \`make maintainer-clean' will remove them" >&2; \
exit 1; \
else :; fi; \
else :; fi
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(LTLIBRARIES) $(MANS) $(DATA)
installdirs:
for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(man3dir)" "$(DESTDIR)$(pkgconfigdir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \
mostlyclean-am
distclean: distclean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am: install-man install-pkgconfigDATA
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am: install-libLTLIBRARIES
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man: install-man3
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-libLTLIBRARIES uninstall-man \
uninstall-pkgconfigDATA
uninstall-man: uninstall-man3
.MAKE: install-am install-strip
.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
clean-libLTLIBRARIES clean-libtool ctags distclean \
distclean-compile distclean-generic distclean-libtool \
distclean-tags distdir dvi dvi-am html html-am info info-am \
install install-am install-data install-data-am install-dvi \
install-dvi-am install-exec install-exec-am install-html \
install-html-am install-info install-info-am \
install-libLTLIBRARIES install-man install-man3 install-pdf \
install-pdf-am install-pkgconfigDATA install-ps install-ps-am \
install-strip installcheck installcheck-am installdirs \
maintainer-clean maintainer-clean-generic mostlyclean \
mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
pdf pdf-am ps ps-am tags uninstall uninstall-am \
uninstall-libLTLIBRARIES uninstall-man uninstall-man3 \
uninstall-pkgconfigDATA
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment