summaryrefslogtreecommitdiff
path: root/cleopatre/application/igmp_snoopd/src/main.c
blob: 3bca4e20c71793dba9dc90a7d7505426f7396f77 (plain)
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
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
/*
 * igmp_snoopd: an IGMP Snooping Daemon.
 * Copyright (C) 2011 SPiDCOM Technologies
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#define _POSIX_C_SOURCE 200112L   /* for pselect */

#include <assert.h>
#include <errno.h>
#include <linux/igmp.h>
#include <netinet/ip.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <unistd.h>

#include "libspid.h"

#include "data_struct.h"
#include "socket.h"
#include "internal.h"
#include "utils.h"

#define INTERFACE_NAME      "br0"

/* Command line options */
#define OPTARG_VLAN     "--vlan"

#define TIMER_SIGNAL    SIGALRM

/** Flag used by the signal handler to inform that the timer expired. */
static volatile sig_atomic_t timer_expired = 0;

/**
 * Handler for the signal used by the timer.
 * \param  sig  The signal number.
 */
static void
timer_signal_handler (int __attribute__((unused)) sig)
{
    timer_expired = 1;
}

/**
 * Process a packet.
 * \param  ctx  The context.
 * \param  msg  The received message.
 * \param  len  The length of the received message.
 * \return  true, if the message was of interest.
 *          false, otherwise (eg: packet discarded).
 */
static bool
process_packet (struct context *ctx, unsigned char *msg, size_t len)
{
    log_debug ("New packet");

    unsigned char *msg_end = msg + len;

    struct ethhdr *eth_header = (struct ethhdr *) msg;

    /* It's an "assert" instead of an "if", because thanks to the Linux Socket
     * Filter, we should only receive IGMP packets. So the message shouldn't be
     * too small to contain an Ethernet header. */
    assert ( ! MSG_TOO_SMALL (eth_header, sizeof (struct ethhdr), msg_end));

    /* If it's a VLAN tagged frame, we must account for the size of the VLAN
     * header. */
    size_t size_eth_header = sizeof (struct ethhdr);
    if (eth_header->h_proto == htons(ETH_P_8021Q))
    {
        log_debug  ("VLAN (802.1Q)");
        size_eth_header += VLAN_HEADER_LEN;
    }

    struct iphdr *ip_header = (struct iphdr *) (msg + size_eth_header);

    assert ( ! MSG_TOO_SMALL (ip_header, sizeof (struct iphdr), msg_end));

    size_t ip_header_len = ip_header->ihl * 4; /* multiplied by 4 because ihl
    is the length of the internet header in 32 bit words */

    if (inet_checksum ((const unsigned char *)ip_header, ip_header_len) != 0)
    {
        log_error ("Bad IP checksum");
        return false;
    }

    size_t ip_total_len = ntohs (ip_header->tot_len);
    if (MSG_TOO_SMALL (ip_header, ip_total_len, msg_end))
    {
        log_error ("annouced IP total length > actual msg length");
        return false;
    }
    else
    {
        /* Adjust msg_end.
         * The message may contain padding zeros at the end, added to
         * conform to Ethernet frame size. Now that we have the IP total
         * length, we can determine the length of the message without the
         * trailing zeros. */

        msg_end = (unsigned char *)ip_header + ip_total_len;
    }

    assert (ip_header->protocol == IPPROTO_IGMP);

    unsigned char *igmp_start = (unsigned char *)ip_header + ip_header_len;
    return process_igmp_packet (ctx, eth_header->h_source, igmp_start, msg_end);
}

/**
 * Send a General Query.
 */
static void
send_general_query (int sockfd)
{

    log_debug ("sending query...");

    unsigned char query[IGMP_V3_GENERAL_QUERY_LEN];

    /* TODO: cache query content instead of generating it on each send ? */
    gen_igmp_v3_general_query (query);

    const struct sockaddr_in dest_addr =
    {
        .sin_family = AF_INET,
        .sin_addr = {.s_addr = IGMP_ALL_HOSTS},
        .sin_port = 0
    };

    ssize_t ret;
    /* TODO: send [robustness_variable] times ? or just once ? */
    if ((ret = sendto (sockfd, query, IGMP_V3_GENERAL_QUERY_LEN, 0,
                       (const struct sockaddr *)&dest_addr,
                       sizeof (dest_addr))) == -1)
    {
        log_error ("send: %s", strerror (errno));
    }
    else
    {
        log_debug ("query sent.");
    }
}

/*
 * Initialize.
 * \param  ctx  The context.
 */
static void
init (struct context *ctx)
{
    LIST_INIT (&ctx->groups_head);

    init_metrics (&ctx->metrics);

    ctx->multicast_info = NULL;

    /* Init timer */
    struct sigevent evp;
    evp.sigev_notify = SIGEV_SIGNAL;
    evp.sigev_signo = TIMER_SIGNAL;
    evp.sigev_value.sival_int = 0;
    evp.sigev_notify_function = NULL;
    evp.sigev_notify_attributes = NULL;

    timer_create (CLOCK_MONOTONIC, &evp, &ctx->timer_query_tx);
}

/**
 * Dump info about current state.
 * \param  ctx  The context.
 */
static void
dump (const struct context *ctx)
{
    dump_info (&ctx->metrics);
    dump_groups (&ctx->groups_head);

    struct itimerspec timer_curr_value;
    timer_gettime (ctx->timer_query_tx, &timer_curr_value);
    log_debug ("timer_query_tx : %lus %.9ldns",
               (unsigned long)timer_curr_value.it_value.tv_sec,
               timer_curr_value.it_value.tv_nsec);
}

static void
log_libspid_error(const char *fct_name, libspid_error_t status)
{
    /* Backup the value of errno, in case it's changed by between here and the
     * moment it's logged */
    int errno_bak = errno;

    log_error ("%s: %d", fct_name, (int)status);

    if (status == LIBSPID_ERROR_SYSTEM)
    {
        log_error ("%s", strerror (errno_bak));
    }
}


/**
 * Receive a packet and process it.
 * \param  sockfd  The socket file descriptor.
 * \param  ctx  The context.
 * \param  mcast_info_file  The path of the multicast info file.
 */
static void
receive_and_process (int sockfd,
                     struct context *ctx,
                     const char *mcast_info_file)
{
    unsigned char msg[MSG_LEN];
    ssize_t len = recvfrom (sockfd, msg, sizeof (msg), 0, NULL, NULL);
    if (len == -1)
    {
        log_error ("recvfrom: %s", strerror (errno));
    }

    bool was_of_interest = process_packet (ctx, msg, (size_t)len);

    if (! was_of_interest)
    {
        log_debug ("packet was not of interest");
        return;
    }

    del_inactive (ctx);

    dump (ctx);

    bool should_update_mcast_info_file
        = update_multicast_info (&ctx->multicast_info, &ctx->groups_head);

    if (! should_update_mcast_info_file)
    {
        log_debug ("no need to update multicast file");
        return;
    }

    libspid_error_t status;

    status = libspid_multicast_info_write_file (ctx->multicast_info);
    if (status != LIBSPID_SUCCESS)
    {
        log_libspid_error ("libspid_multicast_info_write_file", status);
        return;
    }

    status = libspid_system_file_update_warn (getpid (), mcast_info_file);
    if (status != LIBSPID_SUCCESS)
    {
        log_libspid_error ("libspid_system_file_update_warn", status);
    }
}

/**
 * Start IGMP Snooping.
 * \param  ifname  The name of the network interface.
 * \param  mcast_info_file  The path to the file where to write the multicast
 *                           info.
 * \param  dominant_traffic_type  The type of the dominant traffic.
 * \param  ctx  The context.
 */
static void
igmp_snooping (const char *ifname,
               const char *mcast_info_file,
               traffic_type_t dominant_traffic_type,
               struct context *ctx)
{
    /* Socket for listening to traffic */
    int sockfd_rx = open_rx_socket_and_attach_filter (ifname,
                                                      dominant_traffic_type);
    if (sockfd_rx == -1)
    {
        exit (EXIT_FAILURE);
    }

    /* Socket for sending queries */
    int sockfd_tx = open_tx_socket (ifname);
    if (sockfd_tx == -1)
    {
        exit (EXIT_FAILURE);
    }

    seed_random_number_generator (ifname, sockfd_tx);

    sigset_t sigmask;

    /* Block the signal used for the timer */
    sigemptyset (&sigmask);
    sigaddset (&sigmask, TIMER_SIGNAL);
    if (sigprocmask (SIG_BLOCK, &sigmask, NULL) == -1)
    {
        log_error ("sigprocmask: %s", strerror (errno));
        exit (EXIT_FAILURE);
    }

    /* Install a handler for the signal used by the timer */
    struct sigaction sa;
    sa.sa_handler = timer_signal_handler;
    sigemptyset (&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction (TIMER_SIGNAL, &sa, NULL) == -1)
    {
        log_error ("sigaction: %s", strerror (errno));
        exit (EXIT_FAILURE);
    }

    sigset_t empty_sigmask;
    sigemptyset (&empty_sigmask);

    /* Start timer */
    update_timer_query_tx (ctx);

    while (true)
    {
        fd_set read_fds;
        FD_ZERO (&read_fds);
        FD_SET (sockfd_rx, &read_fds);

        int ret = pselect (sockfd_rx + 1, &read_fds, NULL, NULL, NULL,
                           &empty_sigmask);

        if (ret == 1)
        {
            assert (FD_ISSET (sockfd_rx, &read_fds));
            receive_and_process (sockfd_rx, ctx, mcast_info_file);
        }
        else
        {
            /* Only possible value for ret is -1:
             * can't be 0 because no timeout was specified.
             * can't be > 1 because only one fd
             */
            assert (ret == -1);

            if (errno == EINTR)
            {
                /* Interrupted by a signal. */
                if (timer_expired)
                {
                    timer_expired = 0;

                    send_general_query (sockfd_tx);

                    /* In case something bad happens to the query, we re-arm
                     * the timer.
                     * This will be canceled if the query is received. */
                    update_timer_query_tx (ctx);
                }
                else
                {
                    log_debug ("interrupted by unexpected signal");
                }
            }
            else
            {
                log_error ("pselect: %s", strerror (errno));
            }
        }
    }
}

int
main (int argc, char *argv[])
{
    init_log ("igmp_snoopd");

    log_debug ("start");

    /* TODO: get from config file instead of argv */
    traffic_type_t dominant_traffic_type = TRAFFIC_TYPE_UNTAGGED;

    if (argc == 1)
    {
        dominant_traffic_type = TRAFFIC_TYPE_UNTAGGED;
    }
    else if ((argc == 2) && (strcmp (argv[1], OPTARG_VLAN) == 0))
    {
        dominant_traffic_type = TRAFFIC_TYPE_VLAN_TAGGED;
    }
    else
    {
        printf ("Usage: %s [" OPTARG_VLAN "]\n"
                "\t" OPTARG_VLAN "   if the dominant traffic is VLAN tagged.\n", argv[0]);

        return -1;
    }

    struct context ctx;

    init (&ctx);

    igmp_snooping (INTERFACE_NAME, LIBSPID_MULTICAST_INFO_PATH,
                   dominant_traffic_type, &ctx); /* never returns */

    return 0;
}