babel.c 27.1 KB
Newer Older
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1
/*
2
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
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

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.
*/

#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <assert.h>

#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>

41
#include "babel.h"
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
42 43 44
#include "util.h"
#include "net.h"
#include "kernel.h"
45
#include "network.h"
46
#include "source.h"
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
47 48 49 50
#include "neighbour.h"
#include "route.h"
#include "xroute.h"
#include "message.h"
51
#include "request.h"
52
#include "filter.h"
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
53 54 55 56 57 58 59 60

struct timeval now;

unsigned char myid[16];
int debug = 0;

int reboot_time;

61
int idle_time = 320;
62
int link_detect = 0;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
63
int all_wireless = 0;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
64 65
int wireless_hello_interval = -1;
int wired_hello_interval = -1;
66
int idle_hello_interval = -1;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
67
int update_interval = -1;
68 69
int do_daemonise = 0;
char *logfile = NULL, *pidfile = NULL;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
70

71 72 73
unsigned char *receive_buffer = NULL;
int receive_buffer_size = 0;

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
74
const unsigned char zeroes[16] = {0};
75 76 77
const unsigned char ones[16] =
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
78

79
char *state_file = "/var/lib/babel-state";
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
80 81 82 83

int protocol_port;
unsigned char protocol_group[16];
int protocol_socket = -1;
84
int kernel_socket = -1;
85
static int kernel_routes_changed = 0;
86 87
static int kernel_link_changed = 0;
static int kernel_addr_changed = 0;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
88

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
89
static volatile sig_atomic_t exiting = 0, dumping = 0, changed = 0;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
90

91
static int kernel_routes_callback(int changed, void *closure);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
92
static void init_signals(void);
93
static void dump_tables(FILE *out);
94
static int reopen_logfile();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
95 96 97 98 99

int
main(int argc, char **argv)
{
    struct sockaddr_in6 sin6;
100
    int i, rc, fd, rfd, have_id = 0;
101
    struct timeval check_neighbours_time;
102
    int expiry_time, kernel_dump_time;
103
    char *config_file = NULL;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
104 105 106 107
    void *vrc;
    unsigned int seed;
    char **arg;

108
    parse_address("ff02::cca6:c0f9:e182:5373", protocol_group, NULL);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
109 110
    protocol_port = 8475;

111
#define SHIFT() do { arg++; } while(0)
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
112 113 114 115 116 117 118 119 120 121 122 123
#define SHIFTE() do { arg++; if(*arg == NULL) goto syntax; } while(0)

    arg = argv;

    SHIFTE();

    while((*arg)[0] == '-') {
        if(strcmp(*arg, "--") == 0) {
            SHIFTE();
            break;
        } else if(strcmp(*arg, "-m") == 0) {
            SHIFTE();
124
            rc = parse_address(*arg, protocol_group, NULL);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
            if(rc < 0)
                goto syntax;
            if(protocol_group[0] != 0xff) {
                fprintf(stderr,
                        "%s is not a multicast address\n", *arg);
                goto syntax;
            }
            if(protocol_group[1] != 2) {
                fprintf(stderr,
                        "Warning: %s is not a link-local multicast address\n",
                        *arg);
            }
        } else if(strcmp(*arg, "-p") == 0) {
            SHIFTE();
            protocol_port = atoi(*arg);
140
        } else if(strcmp(*arg, "-X") == 0) {
141 142 143 144
            int metric;
            unsigned char prefix[16];
            unsigned char plen;

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
145
            SHIFTE();
146
            rc = parse_net(*arg, prefix, &plen, NULL);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
147 148 149
            if(rc < 0)
                goto syntax;
            SHIFTE();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
150
            if(strcmp(*arg, "infinity") == 0)
151
                metric = INFINITY;
152
            else {
153
                metric = atoi(*arg);
154 155 156
                if(metric < 0 || metric > INFINITY)
                    goto syntax;
            }
157 158 159 160 161
            rc = add_xroute(XROUTE_FORCED, prefix, plen, metric, 0, 0);
            if(rc < 0) {
                fprintf(stderr, "Couldn't add xroute.\n");
                exit(1);
            }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
162 163
        } else if(strcmp(*arg, "-h") == 0) {
            SHIFTE();
164 165 166
            wireless_hello_interval = parse_msec(*arg);
            if(wireless_hello_interval <= 0)
                goto syntax;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
167 168
        } else if(strcmp(*arg, "-H") == 0) {
            SHIFTE();
169 170 171
            wired_hello_interval = parse_msec(*arg);
            if(wired_hello_interval <= 0)
                goto syntax;
172 173
        } else if(strcmp(*arg, "-i") == 0) {
            SHIFTE();
174 175 176
            idle_hello_interval = parse_msec(*arg);
            if(idle_hello_interval <= 0)
                goto syntax;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
177 178
        } else if(strcmp(*arg, "-u") == 0) {
            SHIFTE();
179 180 181
            update_interval = parse_msec(*arg);
            if(update_interval <= 0)
                goto syntax;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
182 183 184
        } else if(strcmp(*arg, "-k") == 0) {
            SHIFTE();
            kernel_metric = atoi(*arg);
185
            if(kernel_metric < 0 || kernel_metric > 0xFFFF)
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
186 187 188 189 190 191 192 193 194 195 196
                goto syntax;
        } else if(strcmp(*arg, "-P") == 0) {
            parasitic = 1;
        } else if(strcmp(*arg, "-s") == 0) {
            split_horizon = 0;
        } else if(strcmp(*arg, "-S") == 0) {
            SHIFTE();
            state_file = *arg;
        } else if(strcmp(*arg, "-d") == 0) {
            SHIFTE();
            debug = atoi(*arg);
197 198
        } else if(strcmp(*arg, "-l") == 0) {
            link_detect = 1;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
199 200
        } else if(strcmp(*arg, "-w") == 0) {
            all_wireless = 1;
201 202 203 204 205 206 207 208 209 210
        } else if(strcmp(*arg, "-t") == 0) {
            SHIFTE();
            export_table = atoi(*arg);
            if(export_table < 0 || export_table > 0xFFFF)
                goto syntax;
        } else if(strcmp(*arg, "-T") == 0) {
            SHIFTE();
            import_table = atoi(*arg);
            if(import_table < 0 || import_table > 0xFFFF)
                goto syntax;
211 212 213 214 215 216 217 218 219 220 221 222
        } else if(strcmp(*arg, "-c") == 0) {
            SHIFTE();
            config_file = *arg;
        } else if(strcmp(*arg, "-C") == 0) {
            int rc;
            SHIFTE();
            rc = parse_config_from_string(*arg);
            if(rc < 0) {
                fprintf(stderr,
                        "Couldn't parse configuration from command line.\n");
                exit(1);
            }
223 224 225 226 227 228 229 230
        } else if(strcmp(*arg, "-D") == 0) {
            do_daemonise = 1;
        } else if(strcmp(*arg, "-L") == 0) {
            SHIFTE();
            logfile = *arg;
        } else if(strcmp(*arg, "-I") == 0) {
            SHIFTE();
            pidfile = *arg;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
231 232 233 234 235 236
        } else {
            goto syntax;
        }
        SHIFTE();
    }

237 238 239 240 241 242 243 244 245

    if(!config_file) {
        if(access("/etc/babel.conf", R_OK) >= 0)
            config_file = "/etc/babel.conf";
    }
    if(config_file) {
        rc = parse_config_from_file(config_file);
        if(rc < 0) {
            fprintf(stderr,
246 247
                    "Couldn't parse configuration from file %s.\n",
                    config_file);
248 249 250 251
            exit(1);
        }
    }

252 253 254 255 256 257
    rc = finalise_filters();
    if(rc < 0) {
        fprintf(stderr, "Couldn't finalise filters.\n");
        exit(1);
    }

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
258
    if(wireless_hello_interval <= 0)
259
        wireless_hello_interval = 6000;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
260 261

    if(wired_hello_interval <= 0)
262
        wired_hello_interval = 30000;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
263 264 265 266

    if(update_interval <= 0)
        update_interval =
            MIN(MAX(wireless_hello_interval * 5, wired_hello_interval),
267
                70000);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
268 269

    if(seqno_interval <= 0)
270 271 272
        seqno_interval = MAX(1000,
                             MIN(wireless_hello_interval - 100,
                                 wired_hello_interval / 4 - 100));
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
273

274 275 276 277 278
    if(do_daemonise) {
        if(logfile == NULL)
            logfile = "/var/log/babel.log";
    }

279 280 281 282
    rc = reopen_logfile();
    if(rc < 0) {
        perror("reopen_logfile()");
        goto fail;
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
    }

    fd = open("/dev/null", O_RDONLY);
    if(fd < 0) {
        perror("open(null)");
        goto fail;
    }

    rc = dup2(fd, 0);
    if(rc < 0) {
        perror("dup2(null, 0)");
        goto fail;
    }

    close(fd);

    if(do_daemonise) {
        rc = daemonise();
        if(rc < 0) {
            perror("daemonise");
            goto fail_nopid;
        }
    }

    if(pidfile) {
        int pfd, len;
        char buf[100];

        len = snprintf(buf, 100, "%lu", (unsigned long)getpid());
        if(len < 0 || len >= 100) {
            perror("snprintf(getpid)");
            goto fail_nopid;
        }

        pfd = open(pidfile, O_WRONLY | O_CREAT | O_EXCL, 0644);
        if(pfd < 0) {
            perror("creat(pidfile)");
            goto fail_nopid;
        }

        rc = write(pfd, buf, len);
        if(rc < len) {
            perror("write(pidfile)");
            goto fail;
        }

        close(pfd);
    }

332 333 334 335 336 337 338 339 340 341 342 343
    rc = kernel_setup(1);
    if(rc < 0) {
        fprintf(stderr, "kernel_setup failed.\n");
        exit(1);
    }

    rc = kernel_setup_socket(1);
    if(rc < 0) {
        fprintf(stderr, "kernel_setup_socket failed.\n");
        kernel_setup(0);
        exit(1);
    }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
344 345

    gettimeofday(&now, NULL);
346

347 348
    rfd = open("/dev/urandom", O_RDONLY);
    if(rfd < 0) {
349
        perror("open(random)");
350 351 352 353 354 355 356 357 358 359 360 361 362 363
    }

    rc = parse_address(*arg, myid, NULL);
    if(rc >= 0) {
        have_id = 1;
        /* Cannot use SHIFTE -- need to goto fail */
        SHIFT();
        if(*arg == NULL) {
            fprintf(stderr, "No interfaces given.\n");
            goto fail;
        }
    } else {
        struct kernel_route routes[240];
        rc = kernel_addresses(routes, 240);
364 365 366
        if(rc < 0) {
            perror("kernel_addresses");
        }
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        if(rc > 0) {
            /* Search for a global IPv6 address */
            for(i = 0; i < rc; i++) {
                if(martian_prefix(routes[i].prefix, routes[i].plen))
                    continue;
                if(routes[i].plen == 128 &&
                   (routes[i].prefix[0] & 0xE0) == 0x20) {
                    memcpy(myid, routes[i].prefix, 16);
                    have_id = 1;
                    break;
                }
            }
            /* Try a global Ipv4 address */
            if(!have_id) {
                for(i = 0; i < rc; i++) {
                    if(martian_prefix(routes[i].prefix, routes[i].plen))
                        continue;
                    if(routes[i].plen == 128 &&
                       v4mapped(routes[i].prefix) &&
                       routes[i].prefix[12] != 10 &&
                       (routes[i].prefix[12] != 172 ||
388
                        (routes[i].prefix[13] & 0xF0) != 16) &&
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
                       (routes[i].prefix[12] != 192 ||
                        routes[i].prefix[13] != 168)) {
                        memcpy(myid, routes[i].prefix, 16);
                        have_id = 1;
                        break;
                    }
                }
            }
        }
    }

    if(!have_id) {
        if(rfd < 0) {
            fprintf(stderr, "Couldn't find suitable router-id.\n");
            goto fail;
        }
        fprintf(stderr,
                "Warning: couldn't find suitable router-id, "
                "using random value.\n");
        rc = read(rfd, myid, 16);
        if(rc < 16) {
            perror("read(random)");
            goto fail;
        } else {
            have_id = 1;
        }
    }

    if(random < 0) {
418 419
        memcpy(&seed, myid + 12, 4);
    } else {
420
        rc = read(rfd, &seed, sizeof(unsigned int));
421 422
        if(rc < sizeof(unsigned int)) {
            perror("read(random)");
423
            goto fail;
424
        }
425 426
        close(rfd);
        rfd = -1;
427
    }
428

429 430 431
    seed ^= (now.tv_sec ^ now.tv_usec);
    srandom(seed);

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
432
    reboot_time = now.tv_sec;
433
    myseqno = (random() & 0xFFFF);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
434 435 436

    fd = open(state_file, O_RDONLY);
    if(fd < 0 && errno != ENOENT)
437
        perror("open(babel-state)");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
438
    rc = unlink(state_file);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
439
    if(rc < 0)
440
        perror("unlink(babel-state)");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
441
    if(fd >= 0 && rc < 0) {
442
        /* If we couldn't unlink it, it's probably stale. */
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
443 444 445 446 447
        close(fd);
        fd = -1;
    }
    if(fd >= 0) {
        char buf[100];
448 449 450
        char buf2[100];
        int s;
        long t;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
451 452
        rc = read(fd, buf, 99);
        if(rc < 0) {
453
            perror("read(babel-state)");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
454 455
        } else {
            buf[rc] = '\0';
456 457 458
            rc = sscanf(buf, "%99s %d %ld\n", buf2, &s, &t);
            if(rc == 3 && s >= 0 && s <= 0xFFFF) {
                unsigned char sid[16];
459
                rc = parse_address(buf2, sid, NULL);
460 461 462 463 464
                if(rc < 0) {
                    fprintf(stderr, "Couldn't parse babel-state.\n");
                } else {
                    debugf("Got %s %d %ld from babel-state.\n",
                           format_address(sid), s, t);
465 466 467 468
                    if(memcmp(sid, myid, 16) == 0)
                        myseqno = seqno_plus(s, 1);
                    else
                        fprintf(stderr, "ID mismatch in babel-state.\n");
469 470 471
                    if(t >= 1176800000L && t <= now.tv_sec)
                        reboot_time = t;
                }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
472
            } else {
473
                fprintf(stderr, "Couldn't parse babel-state.\n");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
474 475 476
            }
        }
        close(fd);
477
        fd = -1;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
478 479
    }

480 481 482 483
    if(reboot_time + silent_time > now.tv_sec)
        fprintf(stderr, "Respecting %ld second silent time.\n",
                (long int)(reboot_time + silent_time - now.tv_sec));

484
    protocol_socket = babel_socket(protocol_port);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
485 486 487 488 489 490
    if(protocol_socket < 0) {
        perror("Couldn't create link local socket");
        goto fail;
    }

    while(*arg) {
491 492
        debugf("Adding network %s.\n", *arg);
        vrc = add_network(*arg);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
493 494 495 496 497
        if(vrc == NULL)
            goto fail;
        SHIFT();
    }

498 499
    init_signals();
    check_networks();
500
    if(receive_buffer == NULL) {
501
        fprintf(stderr, "Warning: couldn't find any operational interfaces.\n");
502 503 504
        resize_receive_buffer(1500);
        if(receive_buffer == NULL)
            goto fail;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
505
    }
506
    check_xroutes();
507
    kernel_routes_changed = 0;
508 509
    kernel_link_changed = 0;
    kernel_addr_changed = 0;
510
    kernel_dump_time = now.tv_sec + 20 + random() % 20;
511
    timeval_plus_msec(&check_neighbours_time, &now, 5000 + random() % 5000);
512
    expiry_time = now.tv_sec + 20 + random() % 20;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
513

514
    /* Make some noise so that others notice us */
515
    for(i = 0; i < numnets; i++) {
516 517
        if(!nets[i].up)
            continue;
518
        gettimeofday(&now, NULL);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
519
        send_hello(&nets[i]);
520
        send_self_update(&nets[i], 0);
521
        send_request(&nets[i], NULL, 0, 0, 0, 0);
522
        flushbuf(&nets[i]);
523
        usleep(5000 + random() % 10000);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
524 525 526 527 528 529 530 531 532 533
    }

    debugf("Entering main loop.\n");

    while(1) {
        struct timeval tv;
        fd_set readfds;

        gettimeofday(&now, NULL);

534 535
        tv = check_neighbours_time;
        timeval_min_sec(&tv, expiry_time);
536
        timeval_min(&tv, &request_resend_time);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
537
        for(i = 0; i < numnets; i++) {
538 539
            if(!nets[i].up)
                continue;
540
            timeval_min(&tv, &nets[i].flush_timeout);
541
            timeval_min(&tv, &nets[i].hello_timeout);
542
            if(!network_idle(&nets[i])) {
543 544
                timeval_min(&tv, &nets[i].self_update_timeout);
                timeval_min(&tv, &nets[i].update_timeout);
545
            }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
546
        }
547
        timeval_min(&tv, &update_flush_timeout);
548
        FD_ZERO(&readfds);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
549 550 551
        if(timeval_compare(&tv, &now) > 0) {
            timeval_minus(&tv, &tv, &now);
            FD_SET(protocol_socket, &readfds);
552
            if(kernel_socket < 0) kernel_setup_socket(1);
553 554 555 556
            if(kernel_socket >= 0)
                FD_SET(kernel_socket, &readfds);
            rc = select(MAX(protocol_socket, kernel_socket) + 1,
                        &readfds, NULL, NULL, &tv);
557
            if(rc < 0) {
558 559 560 561
                if(errno == EINTR) {
                    rc = 0;
                    FD_ZERO(&readfds);
                } else {
562 563 564 565
                    perror("select");
                    sleep(1);
                    continue;
                }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
566 567 568 569 570 571 572 573
            }
        }

        gettimeofday(&now, NULL);

        if(exiting)
            break;

574
        if(kernel_socket >= 0 && FD_ISSET(kernel_socket, &readfds))
575
            kernel_callback(kernel_routes_callback, NULL);
576

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
577
        if(FD_ISSET(protocol_socket, &readfds)) {
578 579 580
            rc = babel_recv(protocol_socket,
                            receive_buffer, receive_buffer_size,
                            (struct sockaddr*)&sin6, sizeof(sin6));
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
581 582 583 584 585 586 587
            if(rc < 0) {
                if(errno != EAGAIN && errno != EINTR) {
                    perror("recv");
                    sleep(1);
                }
            } else {
                for(i = 0; i < numnets; i++) {
588 589
                    if(!nets[i].up)
                        continue;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
590 591
                    if(nets[i].ifindex == sin6.sin6_scope_id) {
                        parse_packet((unsigned char*)&sin6.sin6_addr, &nets[i],
592 593 594
                                     receive_buffer, rc);
                        VALGRIND_MAKE_MEM_UNDEFINED(receive_buffer,
                                                    receive_buffer_size);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
595 596 597 598 599 600
                        break;
                    }
                }
            }
        }

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
601 602 603 604
        if(changed) {
            kernel_dump_time = now.tv_sec;
            check_neighbours_time = now;
            expiry_time = now.tv_sec;
605 606 607 608 609
            rc = reopen_logfile();
            if(rc < 0) {
                perror("reopen_logfile");
                break;
            }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
610 611 612
            changed = 0;
        }

613
        if (kernel_link_changed || kernel_addr_changed) {
614 615 616 617
            check_networks();
            kernel_link_changed = 0;
        }

618 619
        if(kernel_routes_changed || kernel_addr_changed ||
           now.tv_sec >= kernel_dump_time) {
620
            rc = check_xroutes();
621 622 623
            if(rc > 0)
                send_self_update(NULL, 1);
            else if(rc < 0)
624
                fprintf(stderr, "Warning: couldn't check exported routes.\n");
625
            kernel_routes_changed = kernel_addr_changed = 0;
626
            if(kernel_socket >= 0)
627
                kernel_dump_time = now.tv_sec + 200 + random() % 200;
628 629 630 631
            else
                kernel_dump_time = now.tv_sec + 20 + random() % 20;
        }

632 633 634 635 636 637 638 639 640
        if(timeval_compare(&check_neighbours_time, &now) < 0) {
            int msecs;
            msecs = check_neighbours();
            msecs = MAX(msecs, 500);
            timeval_plus_msec(&check_neighbours_time, &now,
                              msecs / 2 + random() % msecs);
        }

        if(now.tv_sec >= expiry_time) {
641
            check_networks();
642
            expire_routes();
643
            expire_requests();
644 645 646
            expiry_time = now.tv_sec + 20 + random() % 20;
        }

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
647
        for(i = 0; i < numnets; i++) {
648 649
            if(!nets[i].up)
                continue;
650
            if(timeval_compare(&now, &nets[i].hello_timeout) >= 0)
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
651
                send_hello(&nets[i]);
652
            if(timeval_compare(&now, &nets[i].ihu_timeout) >= 0)
653
                send_ihu(NULL, &nets[i]);
654
            if(!network_idle(&nets[i])) {
655
                if(timeval_compare(&now, &nets[i].update_timeout) >= 0)
656
                    send_update(&nets[i], 0, NULL, 0);
657
                if(timeval_compare(&now, &nets[i].self_update_timeout) >= 0)
658
                    send_self_update(&nets[i], 0);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
659 660 661
            }
        }

662
        if(timeval_compare(&now, &request_resend_time) >= 0)
663 664
            resend_requests();

665
        if(update_flush_timeout.tv_sec != 0) {
666
            if(timeval_compare(&now, &update_flush_timeout) >= 0)
667 668 669 670
                flushupdates();
        }

        for(i = 0; i < numnets; i++) {
671 672
            if(!nets[i].up)
                continue;
673 674
            if(nets[i].flush_timeout.tv_sec != 0) {
                if(timeval_compare(&now, &nets[i].flush_timeout) >= 0)
675 676 677 678
                    flushbuf(&nets[i]);
            }
        }

679
        if(debug || dumping) {
680
            dump_tables(stdout);
681 682
            dumping = 0;
        }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
683 684 685
    }

    debugf("Exiting...\n");
686
    while(numroutes > 0) {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
687
        /* Uninstall and retract all routes. */
688 689 690
        if(routes[0].installed) {
            uninstall_route(&routes[0]);
            send_update(NULL, 1, routes[0].src->prefix, routes[0].src->plen);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
691
        }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
692
        /* We need to flush the route so network_up won't reinstall it */
693
        flush_route(&routes[0]);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
694 695
    }
    for(i = 0; i < numnets; i++) {
696 697
        if(!nets[i].up)
            continue;
698
        /* Retract exported routes. */
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
699 700
        send_self_retract(&nets[i]);
        /* Make sure that we expire quickly from our neighbours'
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
701 702
           association caches.  Since we sleep on average 10ms per
           network, set the hello interval to numnets cs. */
703
        send_hello_noupdate(&nets[i], numnets);
704
        flushupdates();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
705
        flushbuf(&nets[i]);
706
        usleep(5000 + random() % 10000);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
707 708
    }
    for(i = 0; i < numnets; i++) {
709 710
        if(!nets[i].up)
            continue;
711
        /* Make sure they got it. */
712
        send_self_retract(&nets[i]);
713
        send_hello_noupdate(&nets[i], 1);
714
        flushupdates();
715
        flushbuf(&nets[i]);
716
        usleep(5000 + random() % 10000);
717
        network_up(&nets[i], 0);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
718
    }
719
    kernel_setup_socket(0);
720
    kernel_setup(0);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
721 722 723

    fd = open(state_file, O_WRONLY | O_TRUNC | O_CREAT, 0644);
    if(fd < 0) {
724
        perror("creat(babel-state)");
725
        unlink(state_file);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
726 727
    } else {
        char buf[100];
728 729
        rc = snprintf(buf, 100, "%s %d %ld\n",
                      format_address(myid), (int)myseqno, (long)now.tv_sec);
730 731
        if(rc < 0 || rc >= 100) {
            fprintf(stderr, "write(babel-state): overflow.\n");
732
            unlink(state_file);
733 734 735 736 737 738 739
        } else {
            rc = write(fd, buf, rc);
            if(rc < 0) {
                perror("write(babel-state)");
                unlink(state_file);
            }
            fsync(fd);
740
        }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
741 742
        close(fd);
    }
743 744
    if(pidfile)
        unlink(pidfile);
745
    debugf("Done.\n");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
746 747 748 749 750 751 752
    return 0;

 syntax:
    fprintf(stderr,
            "Syntax: %s "
            "[-m multicast_address] [-p port] [-S state-file]\n"
            "                "
753
            "[-h hello] [-H wired_hello] [-i idle_hello] [-u update]\n"
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
754
            "                "
755
            "[-k metric] [-s] [-p] [-l] [-w] [-d level]\n"
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
756
            "                "
757
            "[-t table] [-T table] [-X net cost] [-c file] [-C statement]\n"
758
            "                "
759 760
            "[-D] [-L logfile] [-I pidfile]\n"
            "                "
761
            "id interface...\n",
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
762 763 764 765
            argv[0]);
    exit(1);

 fail:
766 767 768
    if(pidfile)
        unlink(pidfile);
 fail_nopid:
769 770 771
    for(i = 0; i < numnets; i++) {
        if(!nets[i].up)
            continue;
772
        network_up(&nets[i], 0);
773
    }
774
    kernel_setup_socket(0);
775
    kernel_setup(0);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
776 777 778
    exit(1);
}

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
void
resize_receive_buffer(int size)
{
    char *new;

    if(size <= receive_buffer_size)
        return;

    if(receive_buffer == NULL) {
        receive_buffer = malloc(size);
        if(receive_buffer == NULL)
            return;
        receive_buffer_size = size;
    }

    new = realloc(receive_buffer, size);
    if(new == NULL) {
        perror("malloc(receive_buffer)");
        return;
    }
    receive_buffer_size = size;
}

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
802 803 804 805 806 807
static void
sigexit(int signo)
{
    exiting = 1;
}

808 809 810 811 812 813
static void
sigdump(int signo)
{
    dumping = 1;
}

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
814 815 816 817 818 819
static void
sigchanged(int signo)
{
    changed = 1;
}

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
static void
init_signals(void)
{
    struct sigaction sa;
    sigset_t ss;

    sigemptyset(&ss);
    sa.sa_handler = sigexit;
    sa.sa_mask = ss;
    sa.sa_flags = 0;
    sigaction(SIGTERM, &sa, NULL);

    sigemptyset(&ss);
    sa.sa_handler = sigexit;
    sa.sa_mask = ss;
    sa.sa_flags = 0;
    sigaction(SIGHUP, &sa, NULL);

    sigemptyset(&ss);
    sa.sa_handler = sigexit;
    sa.sa_mask = ss;
    sa.sa_flags = 0;
    sigaction(SIGINT, &sa, NULL);
843 844 845 846 847 848

    sigemptyset(&ss);
    sa.sa_handler = sigdump;
    sa.sa_mask = ss;
    sa.sa_flags = 0;
    sigaction(SIGUSR1, &sa, NULL);
849

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
850 851 852 853 854 855
    sigemptyset(&ss);
    sa.sa_handler = sigchanged;
    sa.sa_mask = ss;
    sa.sa_flags = 0;
    sigaction(SIGUSR2, &sa, NULL);

856 857 858 859 860 861 862
#ifdef SIGINFO
    sigemptyset(&ss);
    sa.sa_handler = sigdump;
    sa.sa_mask = ss;
    sa.sa_flags = 0;
    sigaction(SIGINFO, &sa, NULL);
#endif
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
863 864
}

865 866 867 868 869 870
static void
dump_tables(FILE *out)
{
    int i;

    fprintf(out, "\n");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
871

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
872
    fprintf(out, "My id %s seqno %d\n", format_address(myid), myseqno);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
873

874
    for(i = 0; i < numneighs; i++) {
875
        if(neighs[i].id[0] == 0xFF)
876 877
            continue;
        fprintf(out, "Neighbour %s ", format_address(neighs[i].id));
878 879 880 881 882 883 884
        fprintf(out, "at %s dev %s reach %04x rxcost %d txcost %d%s.\n",
                format_address(neighs[i].address),
                neighs[i].network->ifname,
                neighs[i].reach,
                neighbour_rxcost(&neighs[i]),
                neighs[i].txcost,
                neighs[i].network->up ? "" : " (down)");
885 886
    }
    for(i = 0; i < numxroutes; i++) {
887 888
        fprintf(out, "%s metric %d (%s)\n",
                format_prefix(xroutes[i].prefix, xroutes[i].plen),
889
                xroutes[i].metric,
890
                xroutes[i].kind == XROUTE_FORCED ? "forced" : "exported");
891 892
    }
    for(i = 0; i < numroutes; i++) {
893 894 895
        int id =
            routes[i].src->plen != 128 ||
            memcmp(routes[i].src->prefix, routes[i].src->address, 16) != 0;
896 897 898
        const unsigned char *nexthop =
            memcmp(routes[i].nexthop, routes[i].neigh->address, 16) == 0 ?
            NULL : routes[i].nexthop;
899
        fprintf(out, "%s metric %d refmetric %d %s%s seqno %d age %d "
900
                "via %s neigh %s%s%s%s\n",
901
                format_prefix(routes[i].src->prefix, routes[i].src->plen),
902 903 904 905
                routes[i].metric, routes[i].refmetric,
                id ? "id " : "",
                id ? format_address(routes[i].src->address) : "",
                (int)routes[i].seqno,
906
                (int)(now.tv_sec - routes[i].time),
907 908
                routes[i].neigh->network->ifname,
                format_address(routes[i].neigh->address),
909 910
                nexthop ? " nexthop " : "",
                nexthop ? format_address(nexthop) : "",
911 912
                routes[i].installed ? " (installed)" :
                route_feasible(&routes[i]) ? " (feasible)" : "");
913 914 915 916
    }
    fflush(out);
}

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
static int
reopen_logfile()
{
    int lfd, rc;

    if(logfile == NULL)
        return 0;

    lfd = open(logfile, O_CREAT | O_WRONLY | O_APPEND, 0644);
    if(lfd < 0)
        return -1;

    fflush(stdout);
    fflush(stderr);

    rc = dup2(lfd, 1);
    if(rc < 0)
        return -1;

    rc = dup2(lfd, 2);
    if(rc < 0)
        return -1;

    if(lfd > 2)
        close(lfd);

    return 1;
}

946
static int
947
kernel_routes_callback(int changed, void *closure)
948
{
949 950 951 952 953 954
    if (changed & CHANGE_LINK)
        kernel_link_changed = 1;
    if (changed & CHANGE_ADDR)
        kernel_addr_changed = 1;
    if (changed & CHANGE_ROUTE)
        kernel_routes_changed = 1;
955
    return 1;
956
}