aboutsummaryrefslogtreecommitdiffstats
path: root/bin/nfextract.c
blob: 1b1412548291fd6e5c798e644e10c1cca7b41a30 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

// The MIT License (MIT)

// Copyright (c) 2018 Yun-Chih Chen

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#define _XOPEN_SOURCE 700      // strptime
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809 // strdup
#endif

#include "extract.h"
#include "main.h"
#include "sql.h"
#include "util.h"

#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#define PROG "nfextract"
#define DATE_FORMAT_HUMAN "YYYY-MM-DD [HH:MM][:SS]"
#define DATE_FORMAT "%Y-%m-%d"
#define DATE_FORMAT_FULL DATE_FORMAT " %H:%M"
#define DATE_FORMAT_FULL2 DATE_FORMAT " %H:%M:%S"

sem_t nfl_commit_queue;
uint16_t nfl_group_id;

const char *help_text =
    "Usage: " PROG " [OPTION]\n"
    "\n"
    "Options:\n"
    "  -d --storage=<dirname>     sqlite storage file\n"
    "  -h --help                  print this help\n"
    "  -v --version               print version information\n"
    "  -s --since                 start showing entries on or newer than the "
    "specified date (format: " DATE_FORMAT_HUMAN ")\n"
    "  -u --until                 stop showing entries on or older than the "
    "specified date (format: " DATE_FORMAT_HUMAN ")\n"
    "\n";

void sig_handler(int signo) {
    if (signo == SIGHUP)
        puts("Terminated due to SIGHUP ...");
}

static inline void format_entry(char *output, Entry *e) {
    sprintf(output,
            "  "
            "t=%ld\t"
            "daddr=%s\t"
            "proto=%s\t"
            "uid=%d\t"
            "sport=%d\t"
            "dport=%d",
            e->timestamp, inet_ntoa(e->daddr),
            e->protocol == IPPROTO_TCP ? "TCP" : "UDP", e->uid, e->sport,
            e->dport);
}

static void callback(const State *s, const Timerange *range) {
    int nr_entries = s->header->nr_entries;

    DEBUG("callback: extracting %d entries", nr_entries);

    int i = 0;
    while (i < nr_entries && s->store[i].timestamp < range->from)
        i++;

    char output[1024];
    while (i < nr_entries && s->store[i].timestamp < range->until) {
        format_entry(output, &s->store[i]);
        puts((char *)output);
        ++i;
    }
}

static void extract_all(const char *storage, const Timerange *range) {
    sqlite3 *db = NULL;
    db_open(&db, storage);
    db_read_data_by_timerange(db, range, callback);
    db_close(db);
}

static time_t parse_date_string(time_t default_t, const char *date) {
    struct tm parsed;
    char *ret;
    if (!date)
        return default_t;

#define PARSE(FORMAT)                                                          \
    ret = strptime(date, FORMAT, &parsed);                                     \
    if (ret && !*ret)                                                          \
        return mktime(&parsed);

    PARSE(DATE_FORMAT);
    PARSE(DATE_FORMAT_FULL);
    PARSE(DATE_FORMAT_FULL2);

    FATAL("Wrong date format: expected: \"" DATE_FORMAT_HUMAN "\", got: \"%s\"",
          date);
    return -1;
}

static void populate_date_range(Timerange *range, const char *since,
                                const char *until) {
    range->from = parse_date_string(0, since);
    range->until = parse_date_string(time(NULL), until);
}

int main(int argc, char *argv[]) {
    char *storage = NULL;
    char *date_since_str = NULL, *date_until_str = NULL;
    Timerange date_range;

    struct option longopts[] = {{"storage_file", required_argument, NULL, 'd'},
                                {"since", optional_argument, NULL, 's'},
                                {"until", optional_argument, NULL, 'u'},
                                {"help", no_argument, NULL, 'h'},
                                {"version", no_argument, NULL, 'v'},
                                {0, 0, 0, 0}};

    int opt;
    while ((opt = getopt_long(argc, argv, "d:s:u:hv", longopts, NULL)) != -1) {
        switch (opt) {
        case 'h':
            printf("%s", help_text);
            exit(0);
            break;
        case 'v':
            printf("%s %s", PROG, VERSION);
            exit(0);
            break;
        case 'd':
            if (!optarg)
                FATAL("Expected: --storage_file=[PATH]");
            storage = strdup(optarg);
            break;
        case 's':
            if (!optarg)
                FATAL("Expected: --since=\"" DATE_FORMAT_HUMAN "\"");
            date_since_str = strdup(optarg);
            break;
        case 'u':
            if (!optarg)
                FATAL("Expected: --until=\"" DATE_FORMAT_HUMAN "\"");
            date_until_str = strdup(optarg);
            break;
        case '?':
            FATAL("Unknown argument, see --help");
        }
    }

    // verify arguments
    ASSERT(storage != NULL,
           "You must provide a storage directory (see --help)");

    if (check_file_exist(storage) < 0)
        ERROR("storage file not exist");

    if (signal(SIGHUP, sig_handler) == SIG_ERR)
        ERROR("Could not set SIGHUP handler");

    populate_date_range(&date_range, date_since_str, date_until_str);
    free(date_since_str);
    free(date_until_str);

    extract_all(storage, &date_range);
    free(storage);

    return 0;
}