1 /* Code to save the iptables state, in human readable-form. */
2 /* (C) 1999 by Paul 'Rusty' Russell <rusty@rustcorp.com.au> and
3 * (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
5 * This code is distributed under the terms of GNU GPL v2
16 #include "libiptc/libiptc.h"
18 #include "iptables-multi.h"
20 #ifndef NO_SHARED_LIBS
24 static int show_binary = 0, show_counters = 0;
26 static const struct option options[] = {
27 {.name = "binary", .has_arg = false, .val = 'b'},
28 {.name = "counters", .has_arg = false, .val = 'c'},
29 {.name = "dump", .has_arg = false, .val = 'd'},
30 {.name = "table", .has_arg = true, .val = 't'},
34 /* Debugging prototype. */
35 static int for_each_table(int (*func)(const char *tablename))
38 FILE *procfile = NULL;
39 char tablename[IPT_TABLE_MAXNAMELEN+1];
41 procfile = fopen("/proc/net/ip_tables_names", "r");
43 exit_error(OTHER_PROBLEM,
44 "Unable to open /proc/net/ip_tables_names: %s\n",
47 while (fgets(tablename, sizeof(tablename), procfile)) {
48 if (tablename[strlen(tablename) - 1] != '\n')
49 exit_error(OTHER_PROBLEM,
50 "Badly formed tablename `%s'\n",
52 tablename[strlen(tablename) - 1] = '\0';
53 ret &= func(tablename);
60 static int do_output(const char *tablename)
63 const char *chain = NULL;
66 return for_each_table(&do_output);
68 h = iptc_init(tablename);
70 exit_error(OTHER_PROBLEM, "Can't initialize: %s\n",
71 iptc_strerror(errno));
74 time_t now = time(NULL);
76 printf("# Generated by iptables-save v%s on %s",
77 XTABLES_VERSION, ctime(&now));
78 printf("*%s\n", tablename);
80 /* Dump out chain names first,
81 * thereby preventing dependency conflicts */
82 for (chain = iptc_first_chain(&h);
84 chain = iptc_next_chain(&h)) {
86 printf(":%s ", chain);
87 if (iptc_builtin(chain, h)) {
88 struct ipt_counters count;
90 iptc_get_policy(chain, &count, &h));
91 printf("[%llu:%llu]\n", (unsigned long long)count.pcnt, (unsigned long long)count.bcnt);
98 for (chain = iptc_first_chain(&h);
100 chain = iptc_next_chain(&h)) {
101 const struct ipt_entry *e;
104 e = iptc_first_rule(chain, &h);
106 print_rule(e, &h, chain, show_counters);
107 e = iptc_next_rule(e, &h);
113 printf("# Completed on %s", ctime(&now));
115 /* Binary, huh? OK. */
116 exit_error(OTHER_PROBLEM, "Binary NYI\n");
125 * :Chain name POLICY packets bytes
128 #ifdef IPTABLES_MULTI
130 iptables_save_main(int argc, char *argv[])
133 main(int argc, char *argv[])
136 const char *tablename = NULL;
139 program_name = "iptables-save";
140 program_version = XTABLES_VERSION;
142 lib_dir = getenv("XTABLES_LIBDIR");
143 if (lib_dir == NULL) {
144 lib_dir = getenv("IPTABLES_LIB_DIR");
146 fprintf(stderr, "IPTABLES_LIB_DIR is deprecated\n");
149 lib_dir = XTABLES_LIBDIR;
151 #ifdef NO_SHARED_LIBS
155 while ((c = getopt_long(argc, argv, "bcdt:", options, NULL)) != -1) {
166 /* Select specific table. */
170 do_output(tablename);
176 fprintf(stderr, "Unknown arguments found on commandline\n");
180 return !do_output(tablename);