iptables: Update the hook entries correctly in iptables_delete_rule()
[platform/upstream/connman.git] / src / iptables.c
index a20e70c..83612b9 100644 (file)
@@ -175,14 +175,13 @@ struct connman_iptables {
 };
 
 static GHashTable *table_hash = NULL;
+static gboolean debug_enabled = FALSE;
 
-typedef int (*iterate_entries_cb_t)(struct connman_iptables *table,
-                                       struct ipt_entry *entry, int builtin,
-                                       unsigned int hook, unsigned int offset,
-                                       void *user_data);
+typedef int (*iterate_entries_cb_t)(struct ipt_entry *entry, int builtin,
+                                       unsigned int hook,size_t size,
+                                       unsigned int offset, void *user_data);
 
-static int iterate_entries(struct connman_iptables *table,
-                               struct ipt_entry *entries,
+static int iterate_entries(struct ipt_entry *entries,
                                unsigned int valid_hooks,
                                unsigned int *hook_entry,
                                size_t size, iterate_entries_cb_t cb,
@@ -220,7 +219,7 @@ static int iterate_entries(struct connman_iptables *table,
                                builtin = h;
                }
 
-               err = cb(table, entry, builtin, h, i, user_data);
+               err = cb(entry, builtin, h, size, i, user_data);
                if (err < 0)
                        return err;
 
@@ -229,10 +228,16 @@ static int iterate_entries(struct connman_iptables *table,
        return 0;
 }
 
-static unsigned long entry_to_offset(struct connman_iptables *table,
-                                       struct ipt_entry *entry)
+static int print_entry(struct ipt_entry *entry, int builtin, unsigned int hook,
+                                       size_t size, unsigned int offset,
+                                       void *user_data)
 {
-       return (void *)entry - (void *)table->blob_entries->entrytable;
+       iterate_entries_cb_t cb = user_data;
+
+       DBG("entry %p  hook %d  offset %d  size %d", entry, hook,
+                       offset, entry->next_offset);
+
+       return cb(entry, builtin, hook, size, offset, NULL);
 }
 
 static int target_to_verdict(const char *target_name)
@@ -290,6 +295,17 @@ static gboolean is_jump(struct connman_iptables_entry *e)
        return false;
 }
 
+static gboolean is_fallthrough(struct connman_iptables_entry *e)
+{
+       struct xt_entry_target *target;
+
+       target = ipt_get_target(e->entry);
+       if (!strcmp(target->u.user.name, ""))
+               return true;
+
+       return false;
+}
+
 static gboolean is_chain(struct connman_iptables *table,
                                struct connman_iptables_entry *e)
 {
@@ -408,6 +424,16 @@ static void update_targets_reference(struct connman_iptables *table,
                                t->verdict += offset;
                }
        }
+
+       if (is_fallthrough(modified_entry)) {
+               t = (struct xt_standard_target *) ipt_get_target(modified_entry->entry);
+
+               t->verdict = entry_before->offset +
+                       modified_entry->entry->target_offset +
+                       ALIGN(sizeof(struct xt_standard_target));
+               t->target.u.target_size =
+                       ALIGN(sizeof(struct xt_standard_target));
+       }
 }
 
 static int iptables_add_entry(struct connman_iptables *table,
@@ -747,33 +773,6 @@ static struct ipt_entry *prepare_rule_inclusion(struct connman_iptables *table,
        return new_entry;
 }
 
-static int iptables_append_rule(struct connman_iptables *table,
-                               struct ipt_ip *ip, char *chain_name,
-                               char *target_name, struct xtables_target *xt_t,
-                               struct xtables_rule_match *xt_rm)
-{
-       GList *chain_tail;
-       struct ipt_entry *new_entry;
-       int builtin = -1, ret;
-
-       DBG("");
-
-       chain_tail = find_chain_tail(table, chain_name);
-       if (chain_tail == NULL)
-               return -EINVAL;
-
-       new_entry = prepare_rule_inclusion(table, ip, chain_name,
-                                       target_name, xt_t, &builtin, xt_rm);
-       if (new_entry == NULL)
-               return -EINVAL;
-
-       ret = iptables_add_entry(table, new_entry, chain_tail->prev, builtin);
-       if (ret < 0)
-               g_free(new_entry);
-
-       return ret;
-}
-
 static int iptables_insert_rule(struct connman_iptables *table,
                                struct ipt_ip *ip, const char *chain_name,
                                const char *target_name,
@@ -821,10 +820,16 @@ static gboolean is_same_ipt_entry(struct ipt_entry *i_e1,
 static gboolean is_same_target(struct xt_entry_target *xt_e_t1,
                                        struct xt_entry_target *xt_e_t2)
 {
+       unsigned int i;
+
        if (xt_e_t1 == NULL || xt_e_t2 == NULL)
                return FALSE;
 
-       if (strcmp(xt_e_t1->u.user.name, IPT_STANDARD_TARGET) == 0) {
+       if (strcmp(xt_e_t1->u.user.name, "") == 0 &&
+                       strcmp(xt_e_t2->u.user.name, "") == 0) {
+               /* fallthrough */
+               return TRUE;
+       } else if (strcmp(xt_e_t1->u.user.name, IPT_STANDARD_TARGET) == 0) {
                struct xt_standard_target *xt_s_t1;
                struct xt_standard_target *xt_s_t2;
 
@@ -839,6 +844,12 @@ static gboolean is_same_target(struct xt_entry_target *xt_e_t1,
 
                if (strcmp(xt_e_t1->u.user.name, xt_e_t2->u.user.name) != 0)
                        return FALSE;
+
+               for (i = 0; i < xt_e_t1->u.target_size -
+                               sizeof(struct xt_standard_target); i++) {
+                       if ((xt_e_t1->data[i] ^ xt_e_t2->data[i]) != 0)
+                               return FALSE;
+               }
        }
 
        return TRUE;
@@ -847,6 +858,8 @@ static gboolean is_same_target(struct xt_entry_target *xt_e_t1,
 static gboolean is_same_match(struct xt_entry_match *xt_e_m1,
                                struct xt_entry_match *xt_e_m2)
 {
+       unsigned int i;
+
        if (xt_e_m1 == NULL || xt_e_m2 == NULL)
                return FALSE;
 
@@ -859,6 +872,12 @@ static gboolean is_same_match(struct xt_entry_match *xt_e_m1,
        if (strcmp(xt_e_m1->u.user.name, xt_e_m2->u.user.name) != 0)
                return FALSE;
 
+       for (i = 0; i < xt_e_m1->u.match_size - sizeof(struct xt_entry_match);
+                       i++) {
+               if ((xt_e_m1->data[i] ^ xt_e_m2->data[i]) != 0)
+                       return FALSE;
+       }
+
        return TRUE;
 }
 
@@ -951,11 +970,15 @@ static int iptables_delete_rule(struct connman_iptables *table,
                                struct xtables_rule_match *xt_rm)
 {
        struct connman_iptables_entry *entry;
-       GList *chain_tail, *list;
+       GList *chain_head, *chain_tail, *list;
        int builtin, removed;
 
        removed = 0;
 
+       chain_head = find_chain_head(table, chain_name);
+       if (chain_head == NULL)
+               return -EINVAL;
+
        chain_tail = find_chain_tail(table, chain_name);
        if (chain_tail == NULL)
                return -EINVAL;
@@ -965,12 +988,13 @@ static int iptables_delete_rule(struct connman_iptables *table,
        if (list == NULL)
                return -EINVAL;
 
+       entry = chain_head->data;
+       builtin = entry->builtin;
+
        entry = list->data;
        if (entry == NULL)
                return -EINVAL;
 
-       builtin = entry->builtin;
-
        /* We have deleted a rule,
         * all references should be bumped accordingly */
        if (list->next != NULL)
@@ -1004,29 +1028,6 @@ static int iptables_delete_rule(struct connman_iptables *table,
        return 0;
 }
 
-static int iptables_compare_rule(struct connman_iptables *table,
-                               struct ipt_ip *ip, const char *chain_name,
-                               const char *target_name,
-                               struct xtables_target *xt_t,
-                               struct xtables_match *xt_m,
-                               struct xtables_rule_match *xt_rm)
-{
-       struct connman_iptables_entry *entry;
-       GList *found;
-
-       found = find_existing_rule(table, ip, chain_name, target_name,
-                                                       xt_t, xt_m, xt_rm);
-       if (found == NULL)
-               return -EINVAL;
-
-       entry = found->data;
-       if (entry == NULL)
-               return -EINVAL;
-
-       return 0;
-}
-
-
 static int iptables_change_policy(struct connman_iptables *table,
                                const char *chain_name, const char *policy)
 {
@@ -1104,20 +1105,20 @@ static void dump_ip(struct ipt_entry *entry)
        char ip_mask[INET6_ADDRSTRLEN];
 
        if (strlen(ip->iniface))
-               connman_info("\tin %s", ip->iniface);
+               DBG("\tin %s", ip->iniface);
 
        if (strlen(ip->outiface))
-               connman_info("\tout %s", ip->outiface);
+               DBG("\tout %s", ip->outiface);
 
        if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
                        inet_ntop(AF_INET, &ip->smsk,
                                        ip_mask, INET6_ADDRSTRLEN) != NULL)
-               connman_info("\tsrc %s/%s", ip_string, ip_mask);
+               DBG("\tsrc %s/%s", ip_string, ip_mask);
 
        if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
                        inet_ntop(AF_INET, &ip->dmsk,
                                        ip_mask, INET6_ADDRSTRLEN) != NULL)
-               connman_info("\tdst %s/%s", ip_string, ip_mask);
+               DBG("\tdst %s/%s", ip_string, ip_mask);
 }
 
 static void dump_target(struct ipt_entry *entry)
@@ -1135,27 +1136,27 @@ static void dump_target(struct ipt_entry *entry)
 
                switch (t->verdict) {
                case XT_RETURN:
-                       connman_info("\ttarget RETURN");
+                       DBG("\ttarget RETURN");
                        break;
 
                case -NF_ACCEPT - 1:
-                       connman_info("\ttarget ACCEPT");
+                       DBG("\ttarget ACCEPT");
                        break;
 
                case -NF_DROP - 1:
-                       connman_info("\ttarget DROP");
+                       DBG("\ttarget DROP");
                        break;
 
                case -NF_QUEUE - 1:
-                       connman_info("\ttarget QUEUE");
+                       DBG("\ttarget QUEUE");
                        break;
 
                case -NF_STOP - 1:
-                       connman_info("\ttarget STOP");
+                       DBG("\ttarget STOP");
                        break;
 
                default:
-                       connman_info("\tJUMP (0x%x)", t->verdict);
+                       DBG("\tJUMP %u", t->verdict);
                        break;
                }
 
@@ -1167,12 +1168,12 @@ static void dump_target(struct ipt_entry *entry)
        } else {
                xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
                if (xt_t == NULL) {
-                       connman_info("\ttarget %s", target->u.user.name);
+                       DBG("\ttarget %s", target->u.user.name);
                        return;
                }
 
                if(xt_t->print != NULL) {
-                       connman_info("\ttarget ");
+                       DBG("\ttarget ");
                        xt_t->print(NULL, target, 1);
                }
        }
@@ -1196,49 +1197,44 @@ static void dump_match(struct ipt_entry *entry)
                goto out;
 
        if(xt_m->print != NULL) {
-               connman_info("\tmatch ");
+               DBG("\tmatch ");
                xt_m->print(NULL, match, 1);
 
                return;
        }
 
 out:
-       connman_info("\tmatch %s", match->u.user.name);
+       DBG("\tmatch %s", match->u.user.name);
 
 }
 
-static int dump_entry(struct connman_iptables *table,
-                       struct ipt_entry *entry, int builtin,
-                       unsigned int hook, unsigned int offset,
+static int dump_entry(struct ipt_entry *entry, int builtin,
+                       unsigned int hook, size_t size, unsigned int offset,
                        void *user_data)
 {
        struct xt_entry_target *target;
 
        target = ipt_get_target(entry);
 
-       if (entry_to_offset(table, entry) + entry->next_offset ==
-                                       table->blob_entries->size) {
-               connman_info("End of CHAIN 0x%x", offset);
+       if (offset + entry->next_offset == size) {
+               DBG("\tEnd of CHAIN");
                return 0;
        }
 
        if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
-               connman_info("USER CHAIN (%s) %p  match %p  target %p  size %d",
-                       target->data, entry, entry->elems,
-                       (char *)entry + entry->target_offset,
-                               entry->next_offset);
+               DBG("\tUSER CHAIN (%s) match %p  target %p",
+                       target->data, entry->elems,
+                       (char *)entry + entry->target_offset);
 
                return 0;
        } else if (builtin >= 0) {
-               connman_info("CHAIN (%s) %p  match %p  target %p  size %d",
-                       hooknames[builtin], entry, entry->elems,
-                       (char *)entry + entry->target_offset,
-                               entry->next_offset);
+               DBG("\tCHAIN (%s) match %p  target %p",
+                       hooknames[builtin], entry->elems,
+                       (char *)entry + entry->target_offset);
        } else {
-               connman_info("RULE %p  match %p  target %p  size %d", entry,
+               DBG("\tRULE  match %p  target %p",
                        entry->elems,
-                       (char *)entry + entry->target_offset,
-                               entry->next_offset);
+                       (char *)entry + entry->target_offset);
        }
 
        dump_match(entry);
@@ -1248,19 +1244,54 @@ static int dump_entry(struct connman_iptables *table,
        return 0;
 }
 
-static void iptables_dump(struct connman_iptables *table)
+static void dump_table(struct connman_iptables *table)
 {
-       connman_info("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
+       DBG("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
                        table->info->name,
                        table->info->valid_hooks, table->info->num_entries,
                                table->info->size);
 
-       iterate_entries(table, table->blob_entries->entrytable,
+       DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
+               table->info->hook_entry[NF_IP_PRE_ROUTING],
+               table->info->hook_entry[NF_IP_LOCAL_IN],
+               table->info->hook_entry[NF_IP_FORWARD],
+               table->info->hook_entry[NF_IP_LOCAL_OUT],
+               table->info->hook_entry[NF_IP_POST_ROUTING]);
+       DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
+               table->info->underflow[NF_IP_PRE_ROUTING],
+               table->info->underflow[NF_IP_LOCAL_IN],
+               table->info->underflow[NF_IP_FORWARD],
+               table->info->underflow[NF_IP_LOCAL_OUT],
+               table->info->underflow[NF_IP_POST_ROUTING]);
+
+       iterate_entries(table->blob_entries->entrytable,
                        table->info->valid_hooks,
                        table->info->hook_entry,
                        table->blob_entries->size,
-                       dump_entry, NULL);
+                       print_entry, dump_entry);
+}
 
+static void dump_ipt_replace(struct ipt_replace *repl)
+{
+       DBG("%s valid_hooks 0x%08x  num_entries %u  size %u",
+                       repl->name, repl->valid_hooks, repl->num_entries,
+                       repl->size);
+
+       DBG("entry hook: pre/in/fwd/out/post %d/%d/%d/%d/%d",
+               repl->hook_entry[NF_IP_PRE_ROUTING],
+               repl->hook_entry[NF_IP_LOCAL_IN],
+               repl->hook_entry[NF_IP_FORWARD],
+               repl->hook_entry[NF_IP_LOCAL_OUT],
+               repl->hook_entry[NF_IP_POST_ROUTING]);
+       DBG("underflow:  pre/in/fwd/out/post %d/%d/%d/%d/%d",
+               repl->underflow[NF_IP_PRE_ROUTING],
+               repl->underflow[NF_IP_LOCAL_IN],
+               repl->underflow[NF_IP_FORWARD],
+               repl->underflow[NF_IP_LOCAL_OUT],
+               repl->underflow[NF_IP_POST_ROUTING]);
+
+       iterate_entries(repl->entries, repl->valid_hooks,
+                       repl->hook_entry, repl->size, print_entry, dump_entry);
 }
 
 static int iptables_get_entries(struct connman_iptables *table)
@@ -1280,10 +1311,10 @@ static int iptables_replace(struct connman_iptables *table,
                         sizeof(*r) + r->size);
 }
 
-static int add_entry(struct connman_iptables *table, struct ipt_entry *entry,
-                       int builtin, unsigned int hook, unsigned offset,
-                       void *user_data)
+static int add_entry(struct ipt_entry *entry, int builtin, unsigned int hook,
+                       size_t size, unsigned offset, void *user_data)
 {
+       struct connman_iptables *table = user_data;
        struct ipt_entry *new_entry;
 
        new_entry = g_try_malloc0(entry->next_offset);
@@ -1387,12 +1418,15 @@ static struct connman_iptables *iptables_init(const char *table_name)
        memcpy(table->hook_entry, table->info->hook_entry,
                                sizeof(table->info->hook_entry));
 
-       iterate_entries(table, table->blob_entries->entrytable,
+       iterate_entries(table->blob_entries->entrytable,
                        table->info->valid_hooks, table->info->hook_entry,
-                       table->blob_entries->size, add_entry, NULL);
+                       table->blob_entries->size, add_entry, table);
 
        g_hash_table_insert(table_hash, g_strdup(table_name), table);
 
+       if (debug_enabled == TRUE)
+               dump_table(table);
+
        return table;
 
 err:
@@ -1635,419 +1669,518 @@ static void clear_tables_flags(void)
        }
 }
 
-static int iptables_command(int argc, char *argv[])
-{
-       struct connman_iptables *table;
-       struct xtables_rule_match *xt_rm, *tmp_xt_rm;
-       struct xtables_match *xt_m, *xt_m_t;
+struct parse_context {
+       int argc;
+       char **argv;
+       struct ipt_ip *ip;
        struct xtables_target *xt_t;
-       struct ipt_ip ip;
-       char *table_name, *chain, *new_chain, *match_name, *target_name;
-       char *flush_chain, *delete_chain, *policy;
-       int c, ret, in_len, out_len;
-       gboolean dump, invert, insert, delete, compare;
+       struct xtables_match *xt_m;
+       struct xtables_rule_match *xt_rm;
+};
 
-       if (argc == 0)
-               return -EINVAL;
+static int prepare_getopt_args(const char *str, struct parse_context *ctx)
+{
+       char **tokens;
+       int i;
 
-       dump = FALSE;
-       invert = FALSE;
-       insert = FALSE;
-       delete = FALSE;
-       compare = FALSE;
-       chain = new_chain = match_name = target_name = NULL;
-       flush_chain = delete_chain = policy = table_name = NULL;
-       memset(&ip, 0, sizeof(struct ipt_ip));
-       table = NULL;
-       xt_rm = NULL;
-       xt_m = NULL;
-       xt_t = NULL;
-       /* Default code for options parsing */
-       ret = -EINVAL;
+       tokens = g_strsplit_set(str, " ", -1);
 
-       clear_tables_flags();
+       for (i = 0; tokens[i]; i++);
 
-       /* extension's options will generate false-positives errors */
-       opterr = 0;
+       /* Add space for the argv[0] value */
+       ctx->argc = i + 1;
 
-       optind = 0;
+       /* Don't forget the last NULL entry */
+       ctx->argv = g_try_malloc0((ctx->argc + 1) * sizeof(char *));
+       if (ctx->argv == NULL) {
+               g_strfreev(tokens);
+               return -ENOMEM;
+       }
 
-       while ((c = getopt_long(argc, argv,
-                                       "-A:C:D:F:I:L::N:P:X:d:j:i:m:o:s:t:",
-                                       iptables_globals.opts, NULL)) != -1) {
-               switch (c) {
-               case 'A':
-                       /* It is either -A, -C, -D or -I at once */
-                       if (chain)
-                               goto out;
+       /*
+        * getopt_long() jumps over the first token; we need to add some
+        * random argv[0] entry.
+        */
+       ctx->argv[0] = g_strdup("argh");
+       for (i = 1; i < ctx->argc; i++)
+               ctx->argv[i] = tokens[i - 1];
 
-                       chain = optarg;
-                       break;
+       return 0;
+}
 
-               case 'C':
-                       /* It is either -A, -C, -D or -I at once */
-                       if (chain)
-                               goto out;
+#if XTABLES_VERSION_CODE > 5
 
-                       chain = optarg;
-                       compare = TRUE;
-                       break;
+static int parse_xt_modules(int c, connman_bool_t invert,
+                               struct parse_context *ctx)
+{
+       struct xtables_match *m;
+       struct xtables_rule_match *rm;
 
-               case 'D':
-                       /* It is either -A, -C, -D or -I at once */
-                       if (chain)
-                               goto out;
+       DBG("xtables version code > 5");
 
-                       chain = optarg;
-                       delete = TRUE;
-                       break;
+       for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
+               if (rm->completed != 0)
+                       continue;
 
-               case 'F':
-                       flush_chain = optarg;
-                       break;
+               m = rm->match;
 
-               case 'I':
-                       /* It is either -A, -C, -D or -I at once */
-                       if (chain)
-                               goto out;
+               if (m->x6_parse == NULL && m->parse == NULL)
+                       continue;
 
-                       chain = optarg;
-                       insert = TRUE;
-                       break;
+               if (c < (int) m->option_offset ||
+                               c >= (int) m->option_offset
+                                       + XT_OPTION_OFFSET_SCALE)
+                       continue;
 
-               case 'L':
-                       dump = TRUE;
-                       break;
+               xtables_option_mpcall(c, ctx->argv, invert, m, NULL);
+       }
 
-               case 'N':
-                       new_chain = optarg;
-                       break;
+       if (ctx->xt_t == NULL)
+               return 0;
 
-               case 'P':
-                       chain = optarg;
-                       if (optind < argc)
-                               policy = argv[optind++];
-                       else
-                               goto out;
+       if (ctx->xt_t->x6_parse == NULL && ctx->xt_t->parse == NULL)
+               return 0;
 
-                       break;
+       if (c < (int) ctx->xt_t->option_offset ||
+                       c >= (int) ctx->xt_t->option_offset
+                                       + XT_OPTION_OFFSET_SCALE)
+               return 0;
 
-               case 'X':
-                       delete_chain = optarg;
-                       break;
+       xtables_option_tpcall(c, ctx->argv, invert, ctx->xt_t, NULL);
 
-               case 'd':
-                       if (!parse_ip_and_mask(optarg, &ip.dst, &ip.dmsk))
-                               break;
+       return 0;
+}
 
-                       if (invert)
-                               ip.invflags |= IPT_INV_DSTIP;
+static int final_check_xt_modules(struct parse_context *ctx)
+{
+       struct xtables_rule_match *rm;
 
-                       break;
+       DBG("xtables version code > 5");
 
-               case 'i':
-                       in_len = strlen(optarg);
+       for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
+               xtables_option_mfcall(rm->match);
 
-                       if (in_len + 1 > IFNAMSIZ)
-                               break;
+       if (ctx->xt_t != NULL)
+               xtables_option_tfcall(ctx->xt_t);
 
-                       strcpy(ip.iniface, optarg);
-                       memset(ip.iniface_mask, 0xff, in_len + 1);
+       return 0;
+}
 
-                       if (invert)
-                               ip.invflags |= IPT_INV_VIA_IN;
+#else
 
-                       break;
+static int parse_xt_modules(int c, connman_bool_t invert,
+                               struct parse_context *ctx)
+{
+       struct xtables_match *m;
+       struct xtables_rule_match *rm;
+       int err;
 
-               case 'j':
-                       target_name = optarg;
+       DBG("xtables version code <= 5");
 
-                       table = pre_load_table(table_name, table);
-                       if (table == NULL)
-                               goto out;
+       for (rm = ctx->xt_rm; rm != NULL; rm = rm->next) {
+               if (rm->completed == 1)
+                       continue;
 
-                       xt_t = prepare_target(table, target_name);
-                       if (xt_t == NULL)
-                               goto out;
+               m = rm->match;
 
-                       break;
+               if (m->parse == NULL)
+                       continue;
 
-               case 'm':
-                       match_name = optarg;
+               err = m->parse(c - m->option_offset,
+                               argv, invert, &m->mflags,
+                               NULL, &m->m);
+               if (err > 0)
+                       return -err;
+       }
 
-                       table = pre_load_table(table_name, table);
-                       if (table == NULL)
-                               goto out;
+       if (ctx->xt_t == NULL)
+               return 0;
 
-                       xt_m = prepare_matches(table, &xt_rm, match_name);
-                       if (xt_m == NULL)
-                               goto out;
+       if (ctx->xt_t->parse == NULL)
+               return 0;
 
-                       break;
+       err = ctx->xt_m->parse(c - ctx->xt_m->option_offset,
+                               ctx->argv, invert, &ctx->xt_m->mflags,
+                               NULL, &ctx->xt_m->m);
+       return -err;
+}
 
-               case 'o':
-                       out_len = strlen(optarg);
+static int final_check_xt_modules(struct parse_context *ctx)
+{
+       struct xtables_rule_match *rm;
 
-                       if (out_len + 1 > IFNAMSIZ)
-                               break;
+       DBG("xtables version code <= 5");
+
+       for (rm = ctx->xt_rm; rm != NULL; rm = rm->next)
+               if (rm->match->final_check != NULL)
+                       rm->match->final_check(rm->match->mflags);
+
+       if (ctx->xt_t != NULL && ctx->xt_t->final_check != NULL)
+               ctx->xt_t->final_check(ctx->xt_t->tflags);
+
+       return 0;
+}
+
+#endif
+
+static int parse_rule_spec(struct connman_iptables *table,
+                               struct parse_context *ctx)
+{
+       /*
+        * How the parser works:
+        *
+        *  - If getopt finds 's', 'd', 'i', 'o'.
+        *    just extract the information.
+        *  - if '!' is found, set the invert flag to true and
+        *    removes the '!' from the optarg string and jumps
+        *    back to getopt to reparse the current optarg string.
+        *    After reparsing the invert flag is reseted to false.
+        *  - If 'm' or 'j' is found then call either
+        *    prepare_matches() or prepare_target(). Those function
+        *    will modify (extend) the longopts for getopt_long.
+        *    That means getopt will change its matching context according
+        *    the loaded target.
+        *
+        *    Here an example with iptables-test
+        *
+        *    argv[0] = ./tools/iptables-test
+        *    argv[1] = -t
+        *    argv[2] = filter
+        *    argv[3] = -A
+        *    argv[4] = INPUT
+        *    argv[5] = -m
+        *    argv[6] = mark
+        *    argv[7] = --mark
+        *    argv[8] = 999
+        *    argv[9] = -j
+        *    argv[10] = LOG
+        *
+        *    getopt found 'm' then the optarg is "mark" and optind 7
+        *    The longopts array containts before hitting the `case 'm'`
+        *
+        *    val A has_arg 1 name append
+        *    val C has_arg 1 name compare
+        *    val D has_arg 1 name delete
+        *    val F has_arg 1 name flush-chain
+        *    val I has_arg 1 name insert
+        *    val L has_arg 2 name list
+        *    val N has_arg 1 name new-chain
+        *    val P has_arg 1 name policy
+        *    val X has_arg 1 name delete-chain
+        *    val d has_arg 1 name destination
+        *    val i has_arg 1 name in-interface
+        *    val j has_arg 1 name jump
+        *    val m has_arg 1 name match
+        *    val o has_arg 1 name out-interface
+        *    val s has_arg 1 name source
+        *    val t has_arg 1 name table
+        *
+        *    After executing the `case 'm'` block longopts is
+        *
+        *    val A has_arg 1 name append
+        *    val C has_arg 1 name compare
+        *    val D has_arg 1 name delete
+        *    val F has_arg 1 name flush-chain
+        *    val I has_arg 1 name insert
+        *    val L has_arg 2 name list
+        *    val N has_arg 1 name new-chain
+        *    val P has_arg 1 name policy
+        *    val X has_arg 1 name delete-chain
+        *    val d has_arg 1 name destination
+        *    val i has_arg 1 name in-interface
+        *    val j has_arg 1 name jump
+        *    val m has_arg 1 name match
+        *    val o has_arg 1 name out-interface
+        *    val s has_arg 1 name source
+        *    val t has_arg 1 name table
+        *    val   has_arg 1 name mark
+        *
+        *    So the 'mark' matcher has added the 'mark' options
+        *    and getopt will then return c '256' optarg "999" optind 9
+        *    And we will hit the 'default' statement which then
+        *    will call the matchers parser (xt_m->parser() or
+        *    xtables_option_mpcall() depending on which version
+        *    of libxtables is found.
+        */
+       connman_bool_t invert = FALSE;
+       int len, c, err;
+
+       DBG("");
+
+       ctx->ip = g_try_new0(struct ipt_ip, 1);
+       if (ctx->ip == NULL)
+               return -ENOMEM;
 
-                       strcpy(ip.outiface, optarg);
-                       memset(ip.outiface_mask, 0xff, out_len + 1);
+       /*
+        * As side effect parsing a rule sets some global flags
+        * which will be evaluated/verified. Let's reset them
+        * to ensure we can parse more than one rule.
+        */
+       clear_tables_flags();
+
+       /*
+        * Tell getopt_long not to generate error messages for unknown
+        * options and also reset optind back to 0.
+        */
+       opterr = 0;
+       optind = 0;
+
+       while ((c = getopt_long(ctx->argc, ctx->argv,
+                                       "-:d:i:o:s:m:j:",
+                                       iptables_globals.opts, NULL)) != -1) {
+               switch (c) {
+               case 's':
+                       /* Source specification */
+                       if (!parse_ip_and_mask(optarg,
+                                               &ctx->ip->src,
+                                               &ctx->ip->smsk))
+                               break;
 
                        if (invert)
-                               ip.invflags |= IPT_INV_VIA_OUT;
+                               ctx->ip->invflags |= IPT_INV_SRCIP;
 
                        break;
+               case 'd':
+                       /* Destination specification */
+                       if (!parse_ip_and_mask(optarg,
+                                               &ctx->ip->dst,
+                                               &ctx->ip->dmsk))
+                               break;
 
-               case 's':
-                       if (!parse_ip_and_mask(optarg, &ip.src, &ip.smsk))
+                       if (invert)
+                               ctx->ip->invflags |= IPT_INV_DSTIP;
+                       break;
+               case 'i':
+                       /* In interface specification */
+                       len = strlen(optarg);
+
+                       if (len + 1 > IFNAMSIZ)
                                break;
 
+                       strcpy(ctx->ip->iniface, optarg);
+                       memset(ctx->ip->iniface_mask, 0xff, len + 1);
+
                        if (invert)
-                               ip.invflags |= IPT_INV_SRCIP;
+                               ctx->ip->invflags |= IPT_INV_VIA_IN;
 
                        break;
+               case 'o':
+                       /* Out interface specification */
+                       len = strlen(optarg);
+
+                       if (len + 1 > IFNAMSIZ)
+                               break;
 
-               case 't':
-                       table_name = optarg;
+                       strcpy(ctx->ip->outiface, optarg);
+                       memset(ctx->ip->outiface_mask, 0xff, len + 1);
 
-                       table = pre_load_table(table_name, table);
-                       if (table == NULL)
+                       if (invert)
+                               ctx->ip->invflags |= IPT_INV_VIA_OUT;
+
+                       break;
+               case 'm':
+                       /* Matches */
+                       ctx->xt_m = prepare_matches(table, &ctx->xt_rm, optarg);
+                       if (ctx->xt_m == NULL) {
+                               err = -EINVAL;
                                goto out;
+                       }
 
                        break;
+               case 'j':
+                       /* Target */
+                       ctx->xt_t = prepare_target(table, optarg);
+                       if (ctx->xt_t == NULL) {
+                               err = -EINVAL;
+                               goto out;
+                       }
 
+                       break;
                case 1:
                        if (optarg[0] == '!' && optarg[1] == '\0') {
                                invert = TRUE;
+
+                               /* Remove the '!' from the optarg */
                                optarg[0] = '\0';
+
+                               /*
+                                * And recall getopt_long without reseting
+                                * invert.
+                                */
                                continue;
                        }
 
-                       connman_error("Invalid option");
-
-                       goto out;
-
+                       break;
                default:
-#if XTABLES_VERSION_CODE > 5
-                       if (xt_t != NULL && (xt_t->x6_parse != NULL ||
-                                               xt_t->parse != NULL) &&
-                                       (c >= (int) xt_t->option_offset &&
-                                       c < (int) xt_t->option_offset +
-                                       XT_OPTION_OFFSET_SCALE)) {
-                               xtables_option_tpcall(c, argv,
-                                                       invert, xt_t, NULL);
-
-                               break;
-                       }
-
-                       for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
-                                               tmp_xt_rm = tmp_xt_rm->next) {
-                               xt_m_t = tmp_xt_rm->match;
-
-                               if (tmp_xt_rm->completed ||
-                                               (xt_m_t->x6_parse == NULL &&
-                                                xt_m_t->parse == NULL))
-                                       continue;
-
-                               if (c < (int) xt_m_t->option_offset ||
-                                       c >= (int) xt_m_t->option_offset
-                                       + XT_OPTION_OFFSET_SCALE)
-                                       continue;
-
-                               xtables_option_mpcall(c, argv,
-                                                       invert, xt_m_t, NULL);
+                       err = parse_xt_modules(c, invert, ctx);
+                       if (err == 1)
+                               continue;
 
-                               break;
-                       }
-#else
-                       if (xt_t == NULL || xt_t->parse == NULL ||
-                               !xt_t->parse(c - xt_t->option_offset,
-                               argv, invert, &xt_t->tflags, NULL, &xt_t->t)) {
-
-                               for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
-                                               tmp_xt_rm = tmp_xt_rm->next) {
-                                       xt_m_t = tmp_xt_rm->match;
-
-                                       if (tmp_xt_rm->completed ||
-                                                       xt_m_t->parse == NULL)
-                                               continue;
-
-                                       if (xt_m->parse(c - xt_m->option_offset,
-                                               argv, invert, &xt_m->mflags,
-                                               NULL, &xt_m->m))
-                                               break;
-                               }
-                       }
-#endif
                        break;
                }
 
                invert = FALSE;
        }
 
-#if XTABLES_VERSION_CODE > 5
-       for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
-                               tmp_xt_rm = tmp_xt_rm->next)
-               xtables_option_mfcall(tmp_xt_rm->match);
-
-       if (xt_t != NULL)
-               xtables_option_tfcall(xt_t);
-#else
-       for (tmp_xt_rm = xt_rm; tmp_xt_rm != NULL;
-                               tmp_xt_rm = tmp_xt_rm->next)
-               if (tmp_xt_rm->match->final_check != NULL)
-                       tmp_xt_rm->match->final_check(
-                                       tmp_xt_rm->match->mflags);
-
-       if (xt_t != NULL && xt_t->final_check != NULL)
-               xt_t->final_check(xt_t->tflags);
-#endif
-
-       table = pre_load_table(table_name, table);
-       if (table == NULL)
-               goto out;
+       err = final_check_xt_modules(ctx);
 
-       /* Option parsing went fine, falling back to succes code */
-       ret = 0;
+out:
+       return err;
+}
 
-       if (delete_chain != NULL) {
-               printf("Delete chain %s\n", delete_chain);
+static void cleanup_parse_context(struct parse_context *ctx)
+{
+       g_strfreev(ctx->argv);
+       g_free(ctx->ip);
+       if (ctx->xt_t != NULL)
+               g_free(ctx->xt_t->t);
+       if (ctx->xt_m != NULL)
+               g_free(ctx->xt_m->m);
+       g_free(ctx);
+}
 
-               iptables_delete_chain(table, delete_chain);
+int __connman_iptables_new_chain(const char *table_name,
+                                       const char *chain)
+{
+       struct connman_iptables *table;
 
-               goto out;
-       }
+       DBG("-t %s -N %s", table_name, chain);
 
-       if (dump) {
-               iptables_dump(table);
+       table = pre_load_table(table_name, NULL);
+       if (table == NULL)
+               return -EINVAL;
 
-               goto out;
-       }
+       return iptables_add_chain(table, chain);
+}
 
-       if (flush_chain) {
-               DBG("Flush chain %s", flush_chain);
+int __connman_iptables_delete_chain(const char *table_name,
+                                       const char *chain)
+{
+       struct connman_iptables *table;
 
-               iptables_flush_chain(table, flush_chain);
+       DBG("-t %s -X %s", table_name, chain);
 
-               goto out;
-       }
+       table = pre_load_table(table_name, NULL);
+       if (table == NULL)
+               return -EINVAL;
 
-       if (chain && new_chain) {
-               ret = -EINVAL;
-               goto out;
-       }
+       return iptables_delete_chain(table, chain);
+}
 
-       if (new_chain) {
-               DBG("New chain %s", new_chain);
+int __connman_iptables_flush_chain(const char *table_name,
+                                       const char *chain)
+{
+       struct connman_iptables *table;
 
-               ret = iptables_add_chain(table, new_chain);
-               goto out;
-       }
+       DBG("-t %s -F %s", table_name, chain);
 
-       if (chain) {
-               if (policy != NULL) {
-                       printf("Changing policy of %s to %s\n", chain, policy);
+       table = pre_load_table(table_name, NULL);
+       if (table == NULL)
+               return -EINVAL;
 
-                       iptables_change_policy(table, chain, policy);
+       return iptables_flush_chain(table, chain);
+}
 
-                       goto out;
-               }
+int __connman_iptables_change_policy(const char *table_name,
+                                       const char *chain,
+                                       const char *policy)
+{
+       struct connman_iptables *table;
 
-               if (xt_t == NULL)
-                       goto out;
+       DBG("-t %s -F %s", table_name, chain);
 
-               if (compare == TRUE) {
-                       ret = iptables_compare_rule(table, &ip, chain,
-                                       target_name, xt_t, xt_m, xt_rm);
-                       goto out;
-               }
+       table = pre_load_table(table_name, NULL);
+       if (table == NULL)
+               return -EINVAL;
 
-               if (delete == TRUE) {
-                       DBG("Deleting %s to %s (match %s)\n",
-                                       target_name, chain, match_name);
+       return iptables_change_policy(table, chain, policy);
+}
 
-                       ret = iptables_delete_rule(table, &ip, chain,
-                                       target_name, xt_t, xt_m, xt_rm);
+int __connman_iptables_append(const char *table_name,
+                               const char *chain,
+                               const char *rule_spec)
+{
+       struct connman_iptables *table;
+       struct parse_context *ctx;
+       const char *target_name;
+       int err;
 
-                       goto out;
-               }
+       ctx = g_try_new0(struct parse_context, 1);
+       if (ctx == NULL)
+               return -ENOMEM;
 
-               if (insert == TRUE) {
-                       DBG("Inserting %s to %s (match %s)",
-                                       target_name, chain, match_name);
+       DBG("-t %s -A %s %s", table_name, chain, rule_spec);
 
-                       ret = iptables_insert_rule(table, &ip, chain,
-                                               target_name, xt_t, xt_rm);
+       err = prepare_getopt_args(rule_spec, ctx);
+       if (err < 0)
+               goto out;
 
-                       goto out;
-               } else {
-                       DBG("Adding %s to %s (match %s)",
-                                       target_name, chain, match_name);
+       table = pre_load_table(table_name, NULL);
+       if (table == NULL) {
+               err = -EINVAL;
+               goto out;
+       }
 
-                       ret = iptables_append_rule(table, &ip, chain,
-                                               target_name, xt_t, xt_rm);
+       err = parse_rule_spec(table, ctx);
+       if (err < 0)
+               goto out;
 
-                       goto out;
-               }
-       }
+       if (ctx->xt_t == NULL)
+               target_name = NULL;
+       else
+               target_name = ctx->xt_t->name;
 
+       err = iptables_insert_rule(table, ctx->ip, chain,
+                               target_name, ctx->xt_t, ctx->xt_rm);
 out:
-       if (xt_t)
-               g_free(xt_t->t);
+       cleanup_parse_context(ctx);
 
-       if (xt_m)
-               g_free(xt_m->m);
-
-       return ret;
+       return err;
 }
 
-int __connman_iptables_command(const char *format, ...)
+int __connman_iptables_delete(const char *table_name,
+                               const char *chain,
+                               const char *rule_spec)
 {
-       char **argv, **arguments, *command;
-       int argc, i, ret;
-       va_list args;
-
-       if (format == NULL)
-               return -EINVAL;
-
-       va_start(args, format);
-
-       command = g_strdup_vprintf(format, args);
-
-       va_end(args);
+       struct connman_iptables *table;
+       struct parse_context *ctx;
+       const char *target_name;
+       int err;
 
-       if (command == NULL)
+       ctx = g_try_new0(struct parse_context, 1);
+       if (ctx == NULL)
                return -ENOMEM;
 
-       arguments = g_strsplit_set(command, " ", -1);
-
-       for (argc = 0; arguments[argc]; argc++);
-       ++argc;
+       DBG("-t %s -D %s %s", table_name, chain, rule_spec);
 
-       DBG("command %s argc %d", command, argc);
+       err = prepare_getopt_args(rule_spec, ctx);
+       if (err < 0)
+               goto out;
 
-       argv = g_try_malloc0(argc * sizeof(char *));
-       if (argv == NULL) {
-               g_free(command);
-               g_strfreev(arguments);
-               return -ENOMEM;
+       table = pre_load_table(table_name, NULL);
+       if (table == NULL) {
+               err = -EINVAL;
+               goto out;
        }
 
-       argv[0] = "iptables";
-       for (i = 1; i < argc; i++)
-               argv[i] = arguments[i - 1];
+       err = parse_rule_spec(table, ctx);
+       if (err < 0)
+               goto out;
 
-       ret = iptables_command(argc, argv);
+       if (ctx->xt_t == NULL)
+               target_name = NULL;
+       else
+               target_name = ctx->xt_t->name;
 
-       g_free(command);
-       g_strfreev(arguments);
-       g_free(argv);
+       err = iptables_delete_rule(table, ctx->ip, chain,
+                               target_name, ctx->xt_t, ctx->xt_m,
+                               ctx->xt_rm);
+out:
+       cleanup_parse_context(ctx);
 
-       return ret;
+       return err;
 }
 
-
 int __connman_iptables_commit(const char *table_name)
 {
        struct connman_iptables *table;
@@ -2062,6 +2195,9 @@ int __connman_iptables_commit(const char *table_name)
 
        repl = iptables_blob(table);
 
+       if (debug_enabled == TRUE)
+               dump_ipt_replace(repl);
+
        err = iptables_replace(table, repl);
 
        g_free(repl->counters);
@@ -2082,17 +2218,79 @@ static void remove_table(gpointer user_data)
        table_cleanup(table);
 }
 
+static int flush_table_cb(struct ipt_entry *entry, int builtin,
+                               unsigned int hook, size_t size,
+                               unsigned int offset, void *user_data)
+{
+       GSList **chains = user_data;
+       struct xt_entry_target *target;
+       char *name;
+
+       if (offset + entry->next_offset == size)
+               return 0;
+
+       target = ipt_get_target(entry);
+
+       if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
+               name = g_strdup((const char*)target->data);
+       else if (builtin >= 0)
+                 name = g_strdup(hooknames[builtin]);
+       else
+               return 0;
+
+       *chains = g_slist_prepend(*chains, name);
+
+       return 0;
+}
+
+static void flush_table(const char *name)
+{
+       GSList *chains = NULL, *list;
+       struct connman_iptables *table;
+
+       table = pre_load_table(name, NULL);
+       if (table == NULL)
+               return;
+
+       iterate_entries(table->blob_entries->entrytable,
+                       table->info->valid_hooks,
+                       table->info->hook_entry,
+                       table->blob_entries->size,
+                       flush_table_cb, &chains);
+
+       for (list = chains; list != NULL; list = list->next) {
+               char *chain = list->data;
+
+               DBG("chain %s", chain);
+               iptables_flush_chain(table, chain);
+       }
+
+       __connman_iptables_commit(name);
+       g_slist_free_full(chains, g_free);
+}
+
+static void flush_all_chains(void)
+{
+       flush_table("filter");
+       flush_table("mangle");
+       flush_table("nat");
+}
+
 int __connman_iptables_init(void)
 {
        DBG("");
 
+       if (getenv("CONNMAN_IPTABLES_DEBUG"))
+               debug_enabled = TRUE;
+
        table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
                                                g_free, remove_table);
 
        xtables_init_all(&iptables_globals, NFPROTO_IPV4);
 
-       return 0;
+       flush_all_chains();
 
+       return 0;
 }
 
 void __connman_iptables_cleanup(void)