1 /* Code to convert iptables-save format to xml format,
2 * (C) 2006 Ufo Mechanic <azez@ufomechanic.net>
3 * based on iptables-restor (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
4 * based on previous code from Rusty Russell <rusty@linuxcare.com.au>
6 * This code is distributed under the terms of GNU GPL v2
8 * $Id: iptables-xml.c,v 1.4 2006/11/09 12:02:17 azez Exp $
12 #include <sys/errno.h>
18 #include "libiptc/libiptc.h"
21 #define DEBUGP(x, args...) fprintf(stderr, x, ## args)
23 #define DEBUGP(x, args...)
26 /* no need to link with iptables.o */
27 const char *program_name
;
28 const char *program_version
;
30 #ifndef IPTABLES_MULTI
32 void exit_error(enum exittype status
, char *msg
, ...)
37 fprintf(stderr
, "%s v%s: ", program_name
, program_version
);
38 vfprintf(stderr
, msg
, args
);
40 fprintf(stderr
, "\n");
41 /* On error paths, make sure that we don't leak memory */
46 static void print_usage(const char *name
, const char *version
)
47 __attribute__ ((noreturn
));
49 static int verbose
= 0;
50 /* Whether to combine actions of sequential rules with identical conditions */
51 static int combine
= 0;
52 /* Keeping track of external matches and targets. */
53 static struct option options
[] = {
54 {"verbose", 0, 0, 'v'},
55 {"combine", 0, 0, 'c'},
61 print_usage(const char *name
, const char *version
)
63 fprintf(stderr
, "Usage: %s [-c] [-v] [-h]\n"
65 " [ --verbose ]\n" " [ --help ]\n", name
);
71 parse_counters(char *string
, struct ipt_counters
*ctr
)
75 (string
, "[%llu:%llu]",
76 (unsigned long long *) &ctr
->pcnt
,
77 (unsigned long long *) &ctr
->bcnt
) == 2);
82 /* global new argv and argc */
83 static char *newargv
[255];
84 static int newargc
= 0;
86 static char *oldargv
[255];
87 static int oldargc
= 0;
89 /* arg meta data, were they quoted, frinstance */
90 static int newargvattr
[255];
92 #define IPT_CHAIN_MAXNAMELEN IPT_TABLE_MAXNAMELEN
93 char closeActionTag
[IPT_TABLE_MAXNAMELEN
+ 1];
94 char closeRuleTag
[IPT_TABLE_MAXNAMELEN
+ 1];
95 char curTable
[IPT_TABLE_MAXNAMELEN
+ 1];
96 char curChain
[IPT_CHAIN_MAXNAMELEN
+ 1];
102 struct ipt_counters count
;
106 #define maxChains 10240 /* max chains per table */
107 static chain chains
[maxChains
];
108 static int nextChain
= 0;
110 /* funCtion adding one argument to newargv, updating newargc
111 * returns true if argument added, false otherwise */
113 add_argv(char *what
, int quoted
)
115 DEBUGP("add_argv: %d %s\n", newargc
, what
);
116 if (what
&& ((newargc
+ 1) < sizeof(newargv
) / sizeof(char *))) {
117 newargv
[newargc
] = strdup(what
);
118 newargvattr
[newargc
] = quoted
;
130 for (i
= 0; i
< newargc
; i
++) {
136 for (i
= 0; i
< oldargc
; i
++) {
143 /* save parsed rule for comparison with next rule
144 to perform action agregation on duplicate conditions */
150 for (i
= 0; i
< oldargc
; i
++)
154 for (i
= 0; i
< oldargc
; i
++) {
155 oldargv
[i
] = newargv
[i
];
160 /* like puts but with xml encoding */
162 xmlEncode(char *text
)
164 while (text
&& *text
) {
165 if ((unsigned char) (*text
) >= 127)
166 printf("&#%d;", (unsigned char) (*text
));
167 else if (*text
== '&')
169 else if (*text
== '<')
171 else if (*text
== '>')
173 else if (*text
== '"')
181 /* Output text as a comment, avoiding a double hyphen */
183 xmlCommentEscape(char *comment
)
187 while (comment
&& *comment
) {
188 if (*comment
== '-') {
196 /* strip trailing newline */
197 if (*comment
== '\n' && *(comment
+ 1) == 0);
205 xmlComment(char *comment
)
208 xmlCommentEscape(comment
);
213 xmlAttrS(char *name
, char *value
)
215 printf("%s=\"", name
);
221 xmlAttrI(char *name
, long long int num
)
223 printf("%s=\"%lld\" ", name
, num
);
229 if (curChain
[0] == 0)
232 if (closeActionTag
[0])
233 printf("%s\n", closeActionTag
);
234 closeActionTag
[0] = 0;
236 printf("%s\n", closeRuleTag
);
239 printf(" </chain>\n");
245 openChain(char *chain
, char *policy
, struct ipt_counters
*ctr
, char close
)
249 strncpy(curChain
, chain
, IPT_CHAIN_MAXNAMELEN
);
250 curChain
[IPT_CHAIN_MAXNAMELEN
] = '\0';
253 xmlAttrS("name", curChain
);
254 if (strcmp(policy
, "-") != 0)
255 xmlAttrS("policy", policy
);
256 xmlAttrI("packet-count", (unsigned long long) ctr
->pcnt
);
257 xmlAttrI("byte-count", (unsigned long long) ctr
->bcnt
);
266 existsChain(char *chain
)
268 /* open a saved chain */
271 if (0 == strcmp(curChain
, chain
))
273 for (c
= 0; c
< nextChain
; c
++)
274 if (chains
[c
].chain
&& strcmp(chains
[c
].chain
, chain
) == 0)
280 needChain(char *chain
)
282 /* open a saved chain */
285 if (0 == strcmp(curChain
, chain
))
288 for (c
= 0; c
< nextChain
; c
++)
289 if (chains
[c
].chain
&& strcmp(chains
[c
].chain
, chain
) == 0) {
290 openChain(chains
[c
].chain
, chains
[c
].policy
,
291 &(chains
[c
].count
), '\0');
292 /* And, mark it as done so we don't create
293 an empty chain at table-end time */
294 chains
[c
].created
= 1;
299 saveChain(char *chain
, char *policy
, struct ipt_counters
*ctr
)
301 if (nextChain
>= maxChains
) {
302 exit_error(PARAMETER_PROBLEM
,
303 "%s: line %u chain name invalid\n",
307 chains
[nextChain
].chain
= strdup(chain
);
308 chains
[nextChain
].policy
= strdup(policy
);
309 chains
[nextChain
].count
= *ctr
;
310 chains
[nextChain
].created
= 0;
319 for (c
= 0; c
< nextChain
; c
++)
320 if (!chains
[c
].created
) {
321 openChain(chains
[c
].chain
, chains
[c
].policy
,
322 &(chains
[c
].count
), '/');
323 free(chains
[c
].chain
);
324 free(chains
[c
].policy
);
335 printf(" </table>\n");
340 openTable(char *table
)
344 strncpy(curTable
, table
, IPT_TABLE_MAXNAMELEN
);
345 curTable
[IPT_TABLE_MAXNAMELEN
] = '\0';
348 xmlAttrS("name", curTable
);
352 // is char* -j --jump -g or --goto
357 && (strcmp((arg
), "-j") == 0 || strcmp((arg
), "--jump") == 0
358 || strcmp((arg
), "-g") == 0
359 || strcmp((arg
), "--goto") == 0));
362 // part=-1 means do conditions, part=1 means do rules, part=0 means do both
364 do_rule_part(char *leveltag1
, char *leveltag2
, int part
, int argc
,
365 char *argv
[], int argvattr
[])
367 int arg
= 1; // ignore leading -A
368 char invert_next
= 0;
369 char *thisChain
= NULL
;
370 char *spacer
= ""; // space when needed to assemble arguments
376 #define CLOSE_LEVEL(LEVEL) \
378 if (level ## LEVEL) printf("</%s>\n", \
379 (leveltag ## LEVEL)?(leveltag ## LEVEL):(level ## LEVEL)); \
380 level ## LEVEL=NULL;\
383 #define OPEN_LEVEL(LEVEL,TAG) \
386 if (leveltag ## LEVEL) {\
387 printf("%s<%s ", (leveli ## LEVEL), \
388 (leveltag ## LEVEL));\
389 xmlAttrS("type", (TAG)); \
390 } else printf("%s<%s ", (leveli ## LEVEL), (level ## LEVEL)); \
393 thisChain
= argv
[arg
++];
395 if (part
== 1) { /* skip */
396 /* use argvattr to tell which arguments were quoted
397 to avoid comparing quoted arguments, like comments, to -j, */
398 while (arg
< argc
&& (argvattr
[arg
] || !isTarget(argv
[arg
])))
402 /* Before we start, if the first arg is -[^-] and not -m or -j or -g
403 then start a dummy <match> tag for old style built-in matches.
404 We would do this in any case, but no need if it would be empty */
405 if (arg
< argc
&& argv
[arg
][0] == '-' && !isTarget(argv
[arg
])
406 && strcmp(argv
[arg
], "-m") != 0) {
407 OPEN_LEVEL(1, "match");
411 // If ! is followed by -* then apply to that else output as data
412 // Stop, if we need to
413 if (part
== -1 && !argvattr
[arg
] && (isTarget(argv
[arg
]))) {
415 } else if (!argvattr
[arg
] && strcmp(argv
[arg
], "!") == 0) {
416 if ((arg
+ 1) < argc
&& argv
[arg
+ 1][0] == '-')
419 printf("%s%s", spacer
, argv
[arg
]);
421 } else if (!argvattr
[arg
] && isTarget(argv
[arg
])
422 && existsChain(argv
[arg
+ 1])
423 && (2 + arg
>= argc
)) {
424 if (!((1 + arg
) < argc
))
425 // no args to -j, -m or -g, ignore & finish loop
429 printf("%s", leveli1
);
433 if (strcmp(argv
[arg
], "-g") == 0
434 || strcmp(argv
[arg
], "--goto") == 0) {
435 /* goto user chain */
436 OPEN_LEVEL(1, "goto");
439 OPEN_LEVEL(2, argv
[arg
]);
443 /* call user chain */
444 OPEN_LEVEL(1, "call");
447 OPEN_LEVEL(2, argv
[arg
]);
451 } else if (!argvattr
[arg
]
452 && (isTarget(argv
[arg
])
453 || strcmp(argv
[arg
], "-m") == 0
454 || strcmp(argv
[arg
], "--module") == 0)) {
455 if (!((1 + arg
) < argc
))
456 // no args to -j, -m or -g, ignore & finish loop
460 printf("%s", leveli1
);
465 OPEN_LEVEL(1, (argv
[arg
]));
466 // Optimize case, can we close this tag already?
467 if ((arg
+ 1) >= argc
|| (!argvattr
[arg
+ 1]
468 && (isTarget(argv
[arg
+ 1])
469 || strcmp(argv
[arg
+ 1],
471 || strcmp(argv
[arg
+ 1],
479 } else if (!argvattr
[arg
] && argv
[arg
][0] == '-') {
484 while (*tag
== '-' && *tag
)
490 printf(" invert=\"1\"");
493 // Optimize case, can we close this tag already?
494 if (!((arg
+ 1) < argc
)
495 || (argv
[arg
+ 1][0] == '-' /* NOT QUOTED */ )) {
501 } else { // regular data
502 char *spaces
= strchr(argv
[arg
], ' ');
503 printf("%s", spacer
);
504 if (spaces
|| argvattr
[arg
])
506 // if argv[arg] contains a space, enclose in quotes
507 xmlEncode(argv
[arg
]);
508 if (spaces
|| argvattr
[arg
])
516 printf("%s", leveli1
);
525 /* compare arguments up to -j or -g for match.
526 NOTE: We don't want to combine actions if there were no criteria
527 in each rule, or rules didn't have an action
528 NOTE: Depends on arguments being in some kind of "normal" order which
529 is the case when processing the ACTUAL output of actual iptables-save
530 rather than a file merely in a compatable format */
537 while (new < newargc
&& old
< oldargc
) {
538 if (isTarget(oldargv
[old
]) && isTarget(newargv
[new])) {
542 // break when old!=new
543 if (strcmp(oldargv
[old
], newargv
[new]) != 0) {
551 // We won't match unless both rules had a target.
552 // This means we don't combine target-less rules, which is good
557 /* has a nice parsed rule starting with -A */
559 do_rule(char *pcnt
, char *bcnt
, int argc
, char *argv
[], int argvattr
[])
561 /* are these conditions the same as the previous rule?
562 * If so, skip arg straight to -j or -g */
563 if (combine
&& argc
> 2 && !isTarget(argv
[2]) && compareRules()) {
564 xmlComment("Combine action from next rule");
567 if (closeActionTag
[0]) {
568 printf("%s\n", closeActionTag
);
569 closeActionTag
[0] = 0;
571 if (closeRuleTag
[0]) {
572 printf("%s\n", closeRuleTag
);
577 //xmlAttrS("table",curTable); // not needed in full mode
578 //xmlAttrS("chain",argv[1]); // not needed in full mode
580 xmlAttrS("packet-count", pcnt
);
582 xmlAttrS("byte-count", bcnt
);
585 strncpy(closeRuleTag
, " </rule>\n", IPT_TABLE_MAXNAMELEN
);
586 closeRuleTag
[IPT_TABLE_MAXNAMELEN
] = '\0';
588 /* no point in writing out condition if there isn't one */
589 if (argc
>= 3 && !isTarget(argv
[2])) {
590 printf(" <conditions>\n");
591 do_rule_part(NULL
, NULL
, -1, argc
, argv
, argvattr
);
592 printf(" </conditions>\n");
595 /* Write out the action */
596 //do_rule_part("action","arg",1,argc,argv,argvattr);
597 if (!closeActionTag
[0]) {
598 printf(" <actions>\n");
599 strncpy(closeActionTag
, " </actions>\n",
600 IPT_TABLE_MAXNAMELEN
);
601 closeActionTag
[IPT_TABLE_MAXNAMELEN
] = '\0';
603 do_rule_part(NULL
, NULL
, 1, argc
, argv
, argvattr
);
607 #ifdef IPTABLES_MULTI
609 iptables_xml_main(int argc
, char *argv
[])
612 main(int argc
, char *argv
[])
619 program_name
= "iptables-xml";
620 program_version
= IPTABLES_VERSION
;
623 while ((c
= getopt_long(argc
, argv
, "cvh", options
, NULL
)) != -1) {
629 printf("xptables-xml\n");
633 print_usage("iptables-xml", IPTABLES_VERSION
);
638 if (optind
== argc
- 1) {
639 in
= fopen(argv
[optind
], "r");
641 fprintf(stderr
, "Can't open %s: %s", argv
[optind
],
645 } else if (optind
< argc
) {
646 fprintf(stderr
, "Unknown arguments found on commandline");
651 printf("<iptables-rules version=\"1.0\">\n");
653 /* Grab standard input. */
654 while (fgets(buffer
, sizeof(buffer
), in
)) {
659 if (buffer
[0] == '\n')
661 else if (buffer
[0] == '#') {
667 printf("<!-- line %d ", line
);
668 xmlCommentEscape(buffer
);
672 if ((strcmp(buffer
, "COMMIT\n") == 0) && (curTable
[0])) {
673 DEBUGP("Calling commit\n");
676 } else if ((buffer
[0] == '*')) {
680 table
= strtok(buffer
+ 1, " \t\n");
681 DEBUGP("line %u, table '%s'\n", line
, table
);
683 exit_error(PARAMETER_PROBLEM
,
684 "%s: line %u table name invalid\n",
691 } else if ((buffer
[0] == ':') && (curTable
[0])) {
693 char *policy
, *chain
;
694 struct ipt_counters count
;
697 chain
= strtok(buffer
+ 1, " \t\n");
698 DEBUGP("line %u, chain '%s'\n", line
, chain
);
700 exit_error(PARAMETER_PROBLEM
,
701 "%s: line %u chain name invalid\n",
706 DEBUGP("Creating new chain '%s'\n", chain
);
708 policy
= strtok(NULL
, " \t\n");
709 DEBUGP("line %u, policy '%s'\n", line
, policy
);
711 exit_error(PARAMETER_PROBLEM
,
712 "%s: line %u policy invalid\n",
717 ctrs
= strtok(NULL
, " \t\n");
718 parse_counters(ctrs
, &count
);
719 saveChain(chain
, policy
, &count
);
722 } else if (curTable
[0]) {
731 char *param_start
, *curchar
;
732 int quote_open
, quoted
;
734 /* reset the newargv */
737 if (buffer
[0] == '[') {
738 /* we have counters in our input */
739 ptr
= strchr(buffer
, ']');
741 exit_error(PARAMETER_PROBLEM
,
742 "Bad line %u: need ]\n",
745 pcnt
= strtok(buffer
+ 1, ":");
747 exit_error(PARAMETER_PROBLEM
,
748 "Bad line %u: need :\n",
751 bcnt
= strtok(NULL
, "]");
753 exit_error(PARAMETER_PROBLEM
,
754 "Bad line %u: need ]\n",
757 /* start command parsing after counter */
758 parsestart
= ptr
+ 1;
760 /* start command parsing at start of line */
765 /* This is a 'real' parser crafted in artist mode
766 * not hacker mode. If the author can live with that
767 * then so can everyone else */
770 /* We need to know which args were quoted so we
771 can preserve quote */
773 param_start
= parsestart
;
775 for (curchar
= parsestart
; *curchar
; curchar
++) {
776 if (*curchar
== '"') {
777 /* quote_open cannot be true if there
778 * was no previous character. Thus,
779 * curchar-1 has to be within bounds */
781 *(curchar
- 1) != '\\') {
791 || *curchar
== '\t' || *curchar
== '\n') {
792 char param_buffer
[1024];
793 int param_len
= curchar
- param_start
;
804 /* end of one parameter */
805 strncpy(param_buffer
, param_start
,
807 *(param_buffer
+ param_len
) = '\0';
809 /* check if table name specified */
810 if (!strncmp(param_buffer
, "-t", 3)
811 || !strncmp(param_buffer
,
813 exit_error(PARAMETER_PROBLEM
,
814 "Line %u seems to have a "
815 "-t table option.\n",
820 add_argv(param_buffer
, quoted
);
823 strcmp(newargv
[newargc
- 2], "-A"))
824 chain
= newargv
[newargc
- 1];
826 param_start
+= param_len
+ 1;
828 /* regular character, skip */
832 DEBUGP("calling do_command(%u, argv, &%s, handle):\n",
835 for (a
= 0; a
< newargc
; a
++)
836 DEBUGP("argv[%u]: %s\n", a
, newargv
[a
]);
838 needChain(chain
);// Should we explicitly look for -A
839 do_rule(pcnt
, bcnt
, newargc
, newargv
, newargvattr
);
845 fprintf(stderr
, "%s: line %u failed\n",
851 fprintf(stderr
, "%s: COMMIT expected at line %u\n",
852 program_name
, line
+ 1);
856 printf("</iptables-rules>\n");