iptables-restoreのコードリーディング

はじめに

iptables-restore のコードリーディングをしてみました。 対象バージョンは CentOS 7 のパッケージに合わせて 1.4.21 です。

$ rpm -qf `which iptables-restore`
iptables-1.4.21-17.el7.x86_64

プロジェクトページは netfilter/iptables project homepage - The netfilter.org project で、 ブラウザで見られるレポジトリは iptables - iptables tree です。

main関数からの流れ

main 関数の定義。 xtables-multi.c#L16-#L41

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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);
}

subcmd_main 関数の実装。 xshared.c#L191-#L214

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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);
}

subcmd_get 関数の実装。 xshared.c#L183-#L189

183
184
185
186
187
188
189
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;
}

iptables_restore_main 関数の実装。 iptables-restore.c#L180-#L462

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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;
}
  • 256行目: 空行はスキップ。
  • 258行目: # で始まる行はスキップ(コメント)。
  • 262行目: テーブル内を処理中に COMMIT の行が来たらコミット処理を行い、テーブル終了。
  • 273行目: テーブルの外にいるときに行頭が * のときはテーブル開始。
    • * の後 ' ', '\t', '\n' のどれかの手前までをテーブル名と解釈。
  • 309行目: テーブル内で行頭が : のときはチェーン開始。
    • : の後 ' ', '\t', '\n' のどれかの手前までをチェーン名と解釈。
    • その後次の ' ', '\t', '\n' のどれかの手前までをポリシーと解釈。
    • ポリシーが - 以外の場合は -c オプションを指定していた場合はその後のカウンター部分を解釈。
  • 385行目: テーブル内で行頭が : 以外の時
    • 行頭が [ の時はカウンタ( [整数:整数] 形式)とコマンドを処理。
    • 行頭が [ でない時はコマンドを処理。
  • 454行目: ファイルの終端まで来てテーブル内のままの時は COMMIT の呼び忘れとみなしてエラーで終了。

parse_counters 関数の定義。 iptables-restore.c#L79-#L88

79
80
81
82
83
84
85
86
87
88
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;
}

set_policy関連

libiptc/libiptc.c#L2747-#L2756

2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
const struct xtc_ops TC_OPS = {
    .commit        = TC_COMMIT,
    .free          = TC_FREE,
    .builtin       = TC_BUILTIN,
    .is_chain      = TC_IS_CHAIN,
    .flush_entries = TC_FLUSH_ENTRIES,
    .create_chain  = TC_CREATE_CHAIN,
    .set_policy    = TC_SET_POLICY,
    .strerror      = TC_STRERROR,
};

libiptc/libip4tc.c#L85

85
#define TC_SET_POLICY               iptc_set_policy

libiptc/libiptc.c#L2406-#L2449

2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
/* Sets the policy on a built-in chain. */
int
TC_SET_POLICY(const IPT_CHAINLABEL chain,
          const IPT_CHAINLABEL policy,
          STRUCT_COUNTERS *counters,
          struct xtc_handle *handle)
{
    struct chain_head *c;

    iptc_fn = TC_SET_POLICY;

    if (!(c = iptcc_find_label(chain, handle))) {
            DEBUGP("cannot find chain `%s'\n", chain);
            errno = ENOENT;
            return 0;
    }

    if (!iptcc_is_builtin(c)) {
            DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain);
            errno = ENOENT;
            return 0;
    }

    if (strcmp(policy, LABEL_ACCEPT) == 0)
            c->verdict = -NF_ACCEPT - 1;
    else if (strcmp(policy, LABEL_DROP) == 0)
            c->verdict = -NF_DROP - 1;
    else {
            errno = EINVAL;
            return 0;
    }

    if (counters) {
            /* set byte and packet counters */
            memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS));
            c->counter_map.maptype = COUNTER_MAP_SET;
    } else {
            c->counter_map.maptype = COUNTER_MAP_NOMAP;
    }

    set_changed(handle);

    return 1;
}

2438行目のif文を見ると引数の countersNULL の場合は2443行目で c->counter_map.maptypeCOUNTER_MAP_NOMAP にセットされます。 ですが iptables_restore_main 関数の356〜380行目を見ると -c オプションを指定するしないに関わらず、 set_policycountersNULL でない値を渡していますので、 2441行目で c->counter_map.maptypeCOUNTER_MAP_SET にセットされます。

libiptc/libiptc.c#L107-#L125

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
struct chain_head
{
    struct list_head list;
    char name[TABLE_MAXNAMELEN];
    unsigned int hooknum;           /* hook number+1 if builtin */
    unsigned int references;        /* how many jumps reference us */
    int verdict;                    /* verdict if builtin */

    STRUCT_COUNTERS counters;       /* per-chain counters */
    struct counter_map counter_map;

    unsigned int num_rules;         /* number of rules in list */
    struct list_head rules;         /* list of rules */

    unsigned int index;             /* index (needed for jump resolval) */
    unsigned int head_offset;       /* offset in rule blob */
    unsigned int foot_index;        /* index (needed for counter_map) */
    unsigned int foot_offset;       /* offset in rule blob */
};

libiptc/linux_list.h#L43-#L55

43
44
45
46
47
48
49
50
51
52
53
54
55
/*
 * Simple doubly linked list implementation.
 *
 * Some of the internal functions ("__xxx") are useful when
 * manipulating whole lists rather than single entries, as
 * sometimes we already know the next/prev entries and we can
 * generate better code by using them directly rather than
 * using the generic single-entry routines.
 */

struct list_head {
    struct list_head *next, *prev;
};

libiptc/libiptc.c#L710-#L785

710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
/* Returns chain head if found, otherwise NULL. */
static struct chain_head *
iptcc_find_label(const char *name, struct xtc_handle *handle)
{
    struct list_head *pos;
    struct list_head *list_start_pos;
    unsigned int i=0;
    int res;

    if (list_empty(&handle->chains))
            return NULL;

    /* First look at builtin chains */
    list_for_each(pos, &handle->chains) {
            struct chain_head *c = list_entry(pos, struct chain_head, list);
            if (!iptcc_is_builtin(c))
                    break;
            if (!strcmp(c->name, name))
                    return c;
    }

    /* Find a smart place to start the search via chain index */
    //list_start_pos = iptcc_linearly_search_chain_index(name, handle);
    list_start_pos = iptcc_bsearch_chain_index(name, &i, handle);

    /* Handel if bsearch bails out early */
    if (list_start_pos == &handle->chains) {
            list_start_pos = pos;
    }
#ifdef DEBUG
    else {
            /* Verify result of bsearch against linearly index search */
            struct list_head *test_pos;
            struct chain_head *test_c, *tmp_c;
            test_pos = iptcc_linearly_search_chain_index(name, handle);
            if (list_start_pos != test_pos) {
                    debug("BUG in chain_index search\n");
                    test_c=list_entry(test_pos,      struct chain_head,list);
                    tmp_c =list_entry(list_start_pos,struct chain_head,list);
                    debug("Verify search found:\n");
                    debug(" Chain:%s\n", test_c->name);
                    debug("BSearch found:\n");
                    debug(" Chain:%s\n", tmp_c->name);
                    exit(42);
            }
    }
#endif

    /* Initial/special case, no user defined chains */
    if (handle->num_chains == 0)
            return NULL;

    /* Start searching through the chain list */
    list_for_each(pos, list_start_pos->prev) {
            struct chain_head *c = list_entry(pos, struct chain_head, list);
            res = strcmp(c->name, name);
            debug("List search name:%s == %s res:%d\n", name, c->name, res);
            if (res==0)
                    return c;

            /* We can stop earlier as we know list is sorted */
            if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/
                    debug(" Not in list, walked too far, sorted list\n");
                    return NULL;
            }

            /* Stop on wrap around, if list head is reached */
            if (pos == &handle->chains) {
                    debug("Stop, list head reached\n");
                    return NULL;
            }
    }

    debug("List search NOT found name:%s\n", name);
    return NULL;
}

libiptc/libiptc.c#L642-#L646

642
643
644
645
646
/* Is the given chain builtin (1) or user-defined (0) */
static inline unsigned int iptcc_is_builtin(struct chain_head *c)
{
    return (c->hooknum ? 1 : 0);
}

libiptc/linux_list.h#L324-#L331

324
325
326
327
328
329
330
331
/**
 * list_entry - get the struct for this entry
 * @ptr:    the &struct list_head pointer.
 * @type:   the type of the struct this is embedded in.
 * @member: the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

libiptc/linux_list.h#L7-#L17

 7
 8
 9
10
11
12
13
14
15
16
17
/**
 * container_of - cast a member of a structure out to the containing structure
 *
 * @ptr:    the pointer to the member.
 * @type:   the type of the container struct this is embedded in.
 * @member: the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({                  \
        const typeof( ((type *)0)->member ) *__mptr = (ptr);        \
        (type *)( (char *)__mptr - offsetof(type,member) );})

libiptc/libiptc.c#L184-#L189

184
185
186
187
188
189
/* notify us that the ruleset has been modified by the user */
static inline void
set_changed(struct xtc_handle *h)
{
    h->changed = 1;
}

do_command4

iptables/iptables.c#L1311-#L1955

1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
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;
}

iptables/iptables.c#L341-#L351

341
342
343
344
345
346
347
348
349
350
351
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;
}

commit

libiptc/libiptc.c#L2517-#L2695

2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
int
TC_COMMIT(struct xtc_handle *handle)
{
    /* Replace, then map back the counters. */
    STRUCT_REPLACE *repl;
    STRUCT_COUNTERS_INFO *newcounters;
    struct chain_head *c;
    int ret;
    size_t counterlen;
    int new_number;
    unsigned int new_size;

    iptc_fn = TC_COMMIT;
    CHECK(*handle);

    /* Don't commit if nothing changed. */
    if (!handle->changed)
            goto finished;

    new_number = iptcc_compile_table_prep(handle, &new_size);
    if (new_number < 0) {
            errno = ENOMEM;
            goto out_zero;
    }

    repl = malloc(sizeof(*repl) + new_size);
    if (!repl) {
            errno = ENOMEM;
            goto out_zero;
    }
    memset(repl, 0, sizeof(*repl) + new_size);

#if 0
    TC_DUMP_ENTRIES(*handle);
#endif

    counterlen = sizeof(STRUCT_COUNTERS_INFO)
                    + sizeof(STRUCT_COUNTERS) * new_number;

    /* These are the old counters we will get from kernel */
    repl->counters = malloc(sizeof(STRUCT_COUNTERS)
                            * handle->info.num_entries);
    if (!repl->counters) {
            errno = ENOMEM;
            goto out_free_repl;
    }
    /* These are the counters we're going to put back, later. */
    newcounters = malloc(counterlen);
    if (!newcounters) {
            errno = ENOMEM;
            goto out_free_repl_counters;
    }
    memset(newcounters, 0, counterlen);

    strcpy(repl->name, handle->info.name);
    repl->num_entries = new_number;
    repl->size = new_size;

    repl->num_counters = handle->info.num_entries;
    repl->valid_hooks  = handle->info.valid_hooks;

    DEBUGP("num_entries=%u, size=%u, num_counters=%u\n",
            repl->num_entries, repl->size, repl->num_counters);

    ret = iptcc_compile_table(handle, repl);
    if (ret < 0) {
            errno = ret;
            goto out_free_newcounters;
    }


#ifdef IPTC_DEBUG2
    {
            int fd = open("/tmp/libiptc-so_set_replace.blob",
                            O_CREAT|O_WRONLY);
            if (fd >= 0) {
                    write(fd, repl, sizeof(*repl) + repl->size);
                    close(fd);
            }
    }
#endif

    ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_REPLACE, repl,
                     sizeof(*repl) + repl->size);
    if (ret < 0)
            goto out_free_newcounters;

    /* Put counters back. */
    strcpy(newcounters->name, handle->info.name);
    newcounters->num_counters = new_number;

    list_for_each_entry(c, &handle->chains, list) {
            struct rule_head *r;

            /* Builtin chains have their own counters */
            if (iptcc_is_builtin(c)) {
                    DEBUGP("counter for chain-index %u: ", c->foot_index);
                    switch(c->counter_map.maptype) {
                    case COUNTER_MAP_NOMAP:
                            counters_nomap(newcounters, c->foot_index);
                            break;
                    case COUNTER_MAP_NORMAL_MAP:
                            counters_normal_map(newcounters, repl,
                                                c->foot_index,
                                                c->counter_map.mappos);
                            break;
                    case COUNTER_MAP_ZEROED:
                            counters_map_zeroed(newcounters, repl,
                                                c->foot_index,
                                                c->counter_map.mappos,
                                                &c->counters);
                            break;
                    case COUNTER_MAP_SET:
                            counters_map_set(newcounters, c->foot_index,
                                             &c->counters);
                            break;
                    }
            }

            list_for_each_entry(r, &c->rules, list) {
                    DEBUGP("counter for index %u: ", r->index);
                    switch (r->counter_map.maptype) {
                    case COUNTER_MAP_NOMAP:
                            counters_nomap(newcounters, r->index);
                            break;

                    case COUNTER_MAP_NORMAL_MAP:
                            counters_normal_map(newcounters, repl,
                                                r->index,
                                                r->counter_map.mappos);
                            break;

                    case COUNTER_MAP_ZEROED:
                            counters_map_zeroed(newcounters, repl,
                                                r->index,
                                                r->counter_map.mappos,
                                                &r->entry->counters);
                            break;

                    case COUNTER_MAP_SET:
                            counters_map_set(newcounters, r->index,
                                             &r->entry->counters);
                            break;
                    }
            }
    }

#ifdef IPTC_DEBUG2
    {
            int fd = open("/tmp/libiptc-so_set_add_counters.blob",
                            O_CREAT|O_WRONLY);
            if (fd >= 0) {
                    write(fd, newcounters, counterlen);
                    close(fd);
            }
    }
#endif

    ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS,
                     newcounters, counterlen);
    if (ret < 0)
            goto out_free_newcounters;

    free(repl->counters);
    free(repl);
    free(newcounters);

finished:
    return 1;

out_free_newcounters:
    free(newcounters);
out_free_repl_counters:
    free(repl->counters);
out_free_repl:
    free(repl);
out_zero:
    return 0;
}

libiptc/libiptc.c#L2505-#L2514

2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters,
                             unsigned int idx, STRUCT_COUNTERS *counters)
{
    /* Want to set counter (iptables-restore) */

    memcpy(&newcounters->counters[idx], counters,
            sizeof(STRUCT_COUNTERS));

    DEBUGP_C("SET\n");
}

libiptc/libiptc.c#L2467-#L2471

2467
2468
2469
2470
2471
static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx)
{
    newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0});
    DEBUGP_C("NOMAP => zero\n");
}

ということで iptc_set_policy 関数の2443行目で c->counter_map.maptypeCOUNTER_MAP_NOMAP にセットされたとしても、 counters_nomap 関数で counters{0, 0} にセットされることになります。

まとめ

iptables-restore:INPUT ACCEPT [191890:367927864] のような行を入力しても -c オプションを指定しない場合はカウンタは0にリセットされます。

iptablesのコードリーディング に続きます。