Statistics
| Branch: | Revision:

iof-bird-daemon / sysdep / linux / netlink.c @ 9b136840

History | View | Annotate | Download (34.3 KB)

1
/*
2
 *        BIRD -- Linux Netlink Interface
3
 *
4
 *        (c) 1999--2000 Martin Mares <mj@ucw.cz>
5
 *
6
 *        Can be freely distributed and used under the terms of the GNU GPL.
7
 */
8

    
9
#include <stdio.h>
10
#include <unistd.h>
11
#include <fcntl.h>
12
#include <sys/socket.h>
13
#include <sys/uio.h>
14
#include <errno.h>
15

    
16
#undef LOCAL_DEBUG
17

    
18
#include "nest/bird.h"
19
#include "nest/route.h"
20
#include "nest/protocol.h"
21
#include "nest/iface.h"
22
#include "lib/alloca.h"
23
#include "lib/timer.h"
24
#include "lib/unix.h"
25
#include "lib/krt.h"
26
#include "lib/socket.h"
27
#include "lib/string.h"
28
#include "lib/hash.h"
29
#include "conf/conf.h"
30

    
31
#include <asm/types.h>
32
#include <linux/if.h>
33
#include <linux/netlink.h>
34
#include <linux/rtnetlink.h>
35

    
36

    
37
#ifndef MSG_TRUNC                        /* Hack: Several versions of glibc miss this one :( */
38
#define MSG_TRUNC 0x20
39
#endif
40

    
41
#ifndef IFF_LOWER_UP
42
#define IFF_LOWER_UP 0x10000
43
#endif
44

    
45
#ifndef RTA_TABLE
46
#define RTA_TABLE  15
47
#endif
48

    
49

    
50
/*
51
 *        Synchronous Netlink interface
52
 */
53

    
54
struct nl_sock
55
{
56
  int fd;
57
  u32 seq;
58
  byte *rx_buffer;                        /* Receive buffer */
59
  struct nlmsghdr *last_hdr;                /* Recently received packet */
60
  uint last_size;
61
};
62

    
63
#define NL_RX_SIZE 8192
64

    
65
static struct nl_sock nl_scan = {.fd = -1};        /* Netlink socket for synchronous scan */
66
static struct nl_sock nl_req  = {.fd = -1};        /* Netlink socket for requests */
67

    
68
static void
69
nl_open_sock(struct nl_sock *nl)
70
{
71
  if (nl->fd < 0)
72
    {
73
      nl->fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
74
      if (nl->fd < 0)
75
        die("Unable to open rtnetlink socket: %m");
76
      nl->seq = now;
77
      nl->rx_buffer = xmalloc(NL_RX_SIZE);
78
      nl->last_hdr = NULL;
79
      nl->last_size = 0;
80
    }
81
}
82

    
83
static void
84
nl_open(void)
85
{
86
  nl_open_sock(&nl_scan);
87
  nl_open_sock(&nl_req);
88
}
89

    
90
static void
91
nl_send(struct nl_sock *nl, struct nlmsghdr *nh)
92
{
93
  struct sockaddr_nl sa;
94

    
95
  memset(&sa, 0, sizeof(sa));
96
  sa.nl_family = AF_NETLINK;
97
  nh->nlmsg_pid = 0;
98
  nh->nlmsg_seq = ++(nl->seq);
99
  if (sendto(nl->fd, nh, nh->nlmsg_len, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0)
100
    die("rtnetlink sendto: %m");
101
  nl->last_hdr = NULL;
102
}
103

    
104
static void
105
nl_request_dump(int af, int cmd)
106
{
107
  struct {
108
    struct nlmsghdr nh;
109
    struct rtgenmsg g;
110
  } req = {
111
    .nh.nlmsg_type = cmd,
112
    .nh.nlmsg_len = sizeof(req),
113
    .nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
114
    .g.rtgen_family = af
115
  };
116
  nl_send(&nl_scan, &req.nh);
117
}
118

    
119
static struct nlmsghdr *
120
nl_get_reply(struct nl_sock *nl)
121
{
122
  for(;;)
123
    {
124
      if (!nl->last_hdr)
125
        {
126
          struct iovec iov = { nl->rx_buffer, NL_RX_SIZE };
127
          struct sockaddr_nl sa;
128
          struct msghdr m = { (struct sockaddr *) &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
129
          int x = recvmsg(nl->fd, &m, 0);
130
          if (x < 0)
131
            die("nl_get_reply: %m");
132
          if (sa.nl_pid)                /* It isn't from the kernel */
133
            {
134
              DBG("Non-kernel packet\n");
135
              continue;
136
            }
137
          nl->last_size = x;
138
          nl->last_hdr = (void *) nl->rx_buffer;
139
          if (m.msg_flags & MSG_TRUNC)
140
            bug("nl_get_reply: got truncated reply which should be impossible");
141
        }
142
      if (NLMSG_OK(nl->last_hdr, nl->last_size))
143
        {
144
          struct nlmsghdr *h = nl->last_hdr;
145
          nl->last_hdr = NLMSG_NEXT(h, nl->last_size);
146
          if (h->nlmsg_seq != nl->seq)
147
            {
148
              log(L_WARN "nl_get_reply: Ignoring out of sequence netlink packet (%x != %x)",
149
                  h->nlmsg_seq, nl->seq);
150
              continue;
151
            }
152
          return h;
153
        }
154
      if (nl->last_size)
155
        log(L_WARN "nl_get_reply: Found packet remnant of size %d", nl->last_size);
156
      nl->last_hdr = NULL;
157
    }
158
}
159

    
160
static struct tbf rl_netlink_err = TBF_DEFAULT_LOG_LIMITS;
161

    
162
static int
163
nl_error(struct nlmsghdr *h)
164
{
165
  struct nlmsgerr *e;
166
  int ec;
167

    
168
  if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
169
    {
170
      log(L_WARN "Netlink: Truncated error message received");
171
      return ENOBUFS;
172
    }
173
  e = (struct nlmsgerr *) NLMSG_DATA(h);
174
  ec = -e->error;
175
  if (ec)
176
    log_rl(&rl_netlink_err, L_WARN "Netlink: %s", strerror(ec));
177
  return ec;
178
}
179

    
180
static struct nlmsghdr *
181
nl_get_scan(void)
182
{
183
  struct nlmsghdr *h = nl_get_reply(&nl_scan);
184

    
185
  if (h->nlmsg_type == NLMSG_DONE)
186
    return NULL;
187
  if (h->nlmsg_type == NLMSG_ERROR)
188
    {
189
      nl_error(h);
190
      return NULL;
191
    }
192
  return h;
193
}
194

    
195
static int
196
nl_exchange(struct nlmsghdr *pkt)
197
{
198
  struct nlmsghdr *h;
199

    
200
  nl_send(&nl_req, pkt);
201
  for(;;)
202
    {
203
      h = nl_get_reply(&nl_req);
204
      if (h->nlmsg_type == NLMSG_ERROR)
205
        break;
206
      log(L_WARN "nl_exchange: Unexpected reply received");
207
    }
208
  return nl_error(h) ? -1 : 0;
209
}
210

    
211
/*
212
 *        Netlink attributes
213
 */
214

    
215
static int nl_attr_len;
216

    
217
static void *
218
nl_checkin(struct nlmsghdr *h, int lsize)
219
{
220
  nl_attr_len = h->nlmsg_len - NLMSG_LENGTH(lsize);
221
  if (nl_attr_len < 0)
222
    {
223
      log(L_ERR "nl_checkin: underrun by %d bytes", -nl_attr_len);
224
      return NULL;
225
    }
226
  return NLMSG_DATA(h);
227
}
228

    
229
struct nl_want_attrs {
230
  u8 defined:1;
231
  u8 checksize:1;
232
  u8 size;
233
};
234

    
235

    
236
#define BIRD_IFLA_MAX (IFLA_WIRELESS+1)
237

    
238
static struct nl_want_attrs ifla_attr_want[BIRD_IFLA_MAX] = {
239
  [IFLA_IFNAME]          = { 1, 0, 0 },
240
  [IFLA_MTU]          = { 1, 1, sizeof(u32) },
241
  [IFLA_WIRELESS] = { 1, 0, 0 },
242
};
243

    
244
#define BIRD_IFA_MAX  (IFA_ANYCAST+1)
245

    
246
#ifndef IPV6
247
static struct nl_want_attrs ifa_attr_want4[BIRD_IFA_MAX] = {
248
  [IFA_ADDRESS]          = { 1, 1, sizeof(ip4_addr) },
249
  [IFA_LOCAL]          = { 1, 1, sizeof(ip4_addr) },
250
  [IFA_BROADCAST] = { 1, 1, sizeof(ip4_addr) },
251
};
252
#else
253
static struct nl_want_attrs ifa_attr_want6[BIRD_IFA_MAX] = {
254
  [IFA_ADDRESS]          = { 1, 1, sizeof(ip6_addr) },
255
  [IFA_LOCAL]          = { 1, 1, sizeof(ip6_addr) },
256
};
257
#endif
258

    
259
#define BIRD_RTA_MAX  (RTA_TABLE+1)
260

    
261
static struct nl_want_attrs mpnh_attr_want4[BIRD_RTA_MAX] = {
262
  [RTA_GATEWAY]          = { 1, 1, sizeof(ip4_addr) },
263
};
264

    
265
#ifndef IPV6
266
static struct nl_want_attrs rtm_attr_want4[BIRD_RTA_MAX] = {
267
  [RTA_DST]          = { 1, 1, sizeof(ip4_addr) },
268
  [RTA_OIF]          = { 1, 1, sizeof(u32) },
269
  [RTA_GATEWAY]          = { 1, 1, sizeof(ip4_addr) },
270
  [RTA_PRIORITY]  = { 1, 1, sizeof(u32) },
271
  [RTA_PREFSRC]          = { 1, 1, sizeof(ip4_addr) },
272
  [RTA_METRICS]          = { 1, 0, 0 },
273
  [RTA_MULTIPATH] = { 1, 0, 0 },
274
  [RTA_FLOW]          = { 1, 1, sizeof(u32) },
275
  [RTA_TABLE]          = { 1, 1, sizeof(u32) },
276
};
277
#else
278
static struct nl_want_attrs rtm_attr_want6[BIRD_RTA_MAX] = {
279
  [RTA_DST]          = { 1, 1, sizeof(ip6_addr) },
280
  [RTA_IIF]          = { 1, 1, sizeof(u32) },
281
  [RTA_OIF]          = { 1, 1, sizeof(u32) },
282
  [RTA_GATEWAY]          = { 1, 1, sizeof(ip6_addr) },
283
  [RTA_PRIORITY]  = { 1, 1, sizeof(u32) },
284
  [RTA_PREFSRC]          = { 1, 1, sizeof(ip6_addr) },
285
  [RTA_METRICS]          = { 1, 0, 0 },
286
  [RTA_FLOW]          = { 1, 1, sizeof(u32) },
287
  [RTA_TABLE]          = { 1, 1, sizeof(u32) },
288
};
289
#endif
290

    
291

    
292
static int
293
nl_parse_attrs(struct rtattr *a, struct nl_want_attrs *want, struct rtattr **k, int ksize)
294
{
295
  int max = ksize / sizeof(struct rtattr *);
296
  bzero(k, ksize);
297

    
298
  for ( ; RTA_OK(a, nl_attr_len); a = RTA_NEXT(a, nl_attr_len))
299
    {
300
      if ((a->rta_type >= max) || !want[a->rta_type].defined)
301
        continue;
302

    
303
      if (want[a->rta_type].checksize && (RTA_PAYLOAD(a) != want[a->rta_type].size))
304
        {
305
          log(L_ERR "nl_parse_attrs: Malformed attribute received");
306
          return 0;
307
        }
308

    
309
      k[a->rta_type] = a;
310
    }
311

    
312
  if (nl_attr_len)
313
    {
314
      log(L_ERR "nl_parse_attrs: remnant of size %d", nl_attr_len);
315
      return 0;
316
    }
317

    
318
  return 1;
319
}
320

    
321
static inline u32 rta_get_u32(struct rtattr *a)
322
{ return *(u32 *) RTA_DATA(a); }
323

    
324
static inline ip4_addr rta_get_ip4(struct rtattr *a)
325
{ return ip4_ntoh(*(ip4_addr *) RTA_DATA(a)); }
326

    
327
static inline ip6_addr rta_get_ip6(struct rtattr *a)
328
{ return ip6_ntoh(*(ip6_addr *) RTA_DATA(a)); }
329

    
330
static inline ip_addr rta_get_ipa(struct rtattr *a)
331
{
332
  if (RTA_PAYLOAD(a) == sizeof(ip4_addr))
333
    return ipa_from_ip4(rta_get_ip4(a));
334
  else
335
    return ipa_from_ip6(rta_get_ip6(a));
336
}
337

    
338
struct rtattr *
339
nl_add_attr(struct nlmsghdr *h, uint bufsize, uint code, const void *data, uint dlen)
340
{
341
  uint pos = NLMSG_ALIGN(h->nlmsg_len);
342
  uint len = RTA_LENGTH(dlen);
343

    
344
  if (pos + len > bufsize)
345
    bug("nl_add_attr: packet buffer overflow");
346

    
347
  struct rtattr *a = (struct rtattr *)((char *)h + pos);
348
  a->rta_type = code;
349
  a->rta_len = len;
350
  h->nlmsg_len = pos + len;
351

    
352
  if (dlen > 0)
353
    memcpy(RTA_DATA(a), data, dlen);
354

    
355
  return a;
356
}
357

    
358
static inline void
359
nl_add_attr_u32(struct nlmsghdr *h, unsigned bufsize, int code, u32 data)
360
{
361
  nl_add_attr(h, bufsize, code, &data, 4);
362
}
363

    
364
static inline void
365
nl_add_attr_ipa(struct nlmsghdr *h, unsigned bufsize, int code, ip_addr ipa, int af)
366
{
367
  if (af == AF_INET)
368
  {
369
    ip4_addr ip4 = ip4_hton(ipa_to_ip4(ipa));
370
    nl_add_attr(h, bufsize, code, &ip4, sizeof(ip4));
371
  }
372
  else
373
  {
374
    ip6_addr ip6 = ip6_hton(ipa_to_ip6(ipa));
375
    nl_add_attr(h, bufsize, code, &ip6, sizeof(ip6));
376
  }
377
}
378

    
379
static inline struct rtattr *
380
nl_open_attr(struct nlmsghdr *h, uint bufsize, uint code)
381
{
382
  return nl_add_attr(h, bufsize, code, NULL, 0);
383
}
384

    
385
static inline void
386
nl_close_attr(struct nlmsghdr *h, struct rtattr *a)
387
{
388
  a->rta_len = (void *)h + NLMSG_ALIGN(h->nlmsg_len) - (void *)a;
389
}
390

    
391
static inline struct rtnexthop *
392
nl_open_nexthop(struct nlmsghdr *h, uint bufsize)
393
{
394
  uint pos = NLMSG_ALIGN(h->nlmsg_len);
395
  uint len = RTNH_LENGTH(0);
396

    
397
  if (pos + len > bufsize)
398
    bug("nl_open_nexthop: packet buffer overflow");
399

    
400
  h->nlmsg_len = pos + len;
401

    
402
  return (void *)h + pos;
403
}
404

    
405
static inline void
406
nl_close_nexthop(struct nlmsghdr *h, struct rtnexthop *nh)
407
{
408
  nh->rtnh_len = (void *)h + NLMSG_ALIGN(h->nlmsg_len) - (void *)nh;
409
}
410

    
411
static void
412
nl_add_multipath(struct nlmsghdr *h, unsigned bufsize, struct mpnh *nh)
413
{
414
  struct rtattr *a = nl_open_attr(h, bufsize, RTA_MULTIPATH);
415

    
416
  for (; nh; nh = nh->next)
417
  {
418
    struct rtnexthop *rtnh = nl_open_nexthop(h, bufsize);
419

    
420
    rtnh->rtnh_flags = 0;
421
    rtnh->rtnh_hops = nh->weight;
422
    rtnh->rtnh_ifindex = nh->iface->index;
423

    
424
    nl_add_attr_ipa(h, bufsize, RTA_GATEWAY, nh->gw, AF_INET);
425

    
426
    nl_close_nexthop(h, rtnh);
427
  }
428

    
429
  nl_close_attr(h, a);
430
}
431

    
432
static struct mpnh *
433
nl_parse_multipath(struct krt_proto *p, struct rtattr *ra)
434
{
435
  /* Temporary buffer for multicast nexthops */
436
  static struct mpnh *nh_buffer;
437
  static int nh_buf_size;        /* in number of structures */
438
  static int nh_buf_used;
439

    
440
  struct rtattr *a[BIRD_RTA_MAX];
441
  struct rtnexthop *nh = RTA_DATA(ra);
442
  struct mpnh *rv, *first, **last;
443
  int len = RTA_PAYLOAD(ra);
444

    
445
  first = NULL;
446
  last = &first;
447
  nh_buf_used = 0;
448

    
449
  while (len)
450
    {
451
      /* Use RTNH_OK(nh,len) ?? */
452
      if ((len < sizeof(*nh)) || (len < nh->rtnh_len))
453
        return NULL;
454

    
455
      if (nh_buf_used == nh_buf_size)
456
      {
457
        nh_buf_size = nh_buf_size ? (nh_buf_size * 2) : 4;
458
        nh_buffer = xrealloc(nh_buffer, nh_buf_size * sizeof(struct mpnh));
459
      }
460
      *last = rv = nh_buffer + nh_buf_used++;
461
      rv->next = NULL;
462
      last = &(rv->next);
463

    
464
      rv->weight = nh->rtnh_hops;
465
      rv->iface = if_find_by_index(nh->rtnh_ifindex);
466
      if (!rv->iface)
467
        return NULL;
468

    
469
      /* Nonexistent RTNH_PAYLOAD ?? */
470
      nl_attr_len = nh->rtnh_len - RTNH_LENGTH(0);
471
      nl_parse_attrs(RTNH_DATA(nh), mpnh_attr_want4, a, sizeof(a));
472
      if (a[RTA_GATEWAY])
473
        {
474
          memcpy(&rv->gw, RTA_DATA(a[RTA_GATEWAY]), sizeof(ip_addr));
475
          ipa_ntoh(rv->gw);
476

    
477
          neighbor *ng = neigh_find2(&p->p, &rv->gw, rv->iface,
478
                                     (nh->rtnh_flags & RTNH_F_ONLINK) ? NEF_ONLINK : 0);
479
          if (!ng || (ng->scope == SCOPE_HOST))
480
            return NULL;
481
        }
482
      else
483
        return NULL;
484

    
485
      len -= NLMSG_ALIGN(nh->rtnh_len);
486
      nh = RTNH_NEXT(nh);
487
    }
488

    
489
  return first;
490
}
491

    
492
static void
493
nl_add_metrics(struct nlmsghdr *h, uint bufsize, u32 *metrics, int max)
494
{
495
  struct rtattr *a = nl_open_attr(h, bufsize, RTA_METRICS);
496
  int t;
497

    
498
  for (t = 1; t < max; t++)
499
    if (metrics[0] & (1 << t))
500
      nl_add_attr_u32(h, bufsize, t, metrics[t]);
501

    
502
  nl_close_attr(h, a);
503
}
504

    
505
static int
506
nl_parse_metrics(struct rtattr *hdr, u32 *metrics, int max)
507
{
508
  struct rtattr *a = RTA_DATA(hdr);
509
  int len = RTA_PAYLOAD(hdr);
510

    
511
  metrics[0] = 0;
512
  for (; RTA_OK(a, len); a = RTA_NEXT(a, len))
513
  {
514
    if (a->rta_type == RTA_UNSPEC)
515
      continue;
516

    
517
    if (a->rta_type >= max)
518
      continue;
519

    
520
    if (RTA_PAYLOAD(a) != 4)
521
      return -1;
522

    
523
    metrics[0] |= 1 << a->rta_type;
524
    metrics[a->rta_type] = rta_get_u32(a);
525
  }
526

    
527
  if (len > 0)
528
    return -1;
529

    
530
  return 0;
531
}
532

    
533

    
534
/*
535
 *        Scanning of interfaces
536
 */
537

    
538
static void
539
nl_parse_link(struct nlmsghdr *h, int scan)
540
{
541
  struct ifinfomsg *i;
542
  struct rtattr *a[BIRD_IFLA_MAX];
543
  int new = h->nlmsg_type == RTM_NEWLINK;
544
  struct iface f = {};
545
  struct iface *ifi;
546
  char *name;
547
  u32 mtu;
548
  uint fl;
549

    
550
  if (!(i = nl_checkin(h, sizeof(*i))) || !nl_parse_attrs(IFLA_RTA(i), ifla_attr_want, a, sizeof(a)))
551
    return;
552
  if (!a[IFLA_IFNAME] || (RTA_PAYLOAD(a[IFLA_IFNAME]) < 2) || !a[IFLA_MTU])
553
    {
554
      /*
555
       * IFLA_IFNAME and IFLA_MTU are required, in fact, but there may also come
556
       * a message with IFLA_WIRELESS set, where (e.g.) no IFLA_IFNAME exists.
557
       * We simply ignore all such messages with IFLA_WIRELESS without notice.
558
       */
559

    
560
      if (a[IFLA_WIRELESS])
561
        return;
562

    
563
      log(L_ERR "KIF: Malformed message received");
564
      return;
565
    }
566

    
567
  name = RTA_DATA(a[IFLA_IFNAME]);
568
  mtu = rta_get_u32(a[IFLA_MTU]);
569

    
570
  ifi = if_find_by_index(i->ifi_index);
571
  if (!new)
572
    {
573
      DBG("KIF: IF%d(%s) goes down\n", i->ifi_index, name);
574
      if (!ifi)
575
        return;
576

    
577
      if_delete(ifi);
578
    }
579
  else
580
    {
581
      DBG("KIF: IF%d(%s) goes up (mtu=%d,flg=%x)\n", i->ifi_index, name, mtu, i->ifi_flags);
582
      if (ifi && strncmp(ifi->name, name, sizeof(ifi->name)-1))
583
        if_delete(ifi);
584

    
585
      strncpy(f.name, name, sizeof(f.name)-1);
586
      f.index = i->ifi_index;
587
      f.mtu = mtu;
588

    
589
      fl = i->ifi_flags;
590
      if (fl & IFF_UP)
591
        f.flags |= IF_ADMIN_UP;
592
      if (fl & IFF_LOWER_UP)
593
        f.flags |= IF_LINK_UP;
594
      if (fl & IFF_LOOPBACK)                /* Loopback */
595
        f.flags |= IF_MULTIACCESS | IF_LOOPBACK | IF_IGNORE;
596
      else if (fl & IFF_POINTOPOINT)        /* PtP */
597
        f.flags |= IF_MULTICAST;
598
      else if (fl & IFF_BROADCAST)        /* Broadcast */
599
        f.flags |= IF_MULTIACCESS | IF_BROADCAST | IF_MULTICAST;
600
      else
601
        f.flags |= IF_MULTIACCESS;        /* NBMA */
602

    
603
      if (fl & IFF_MULTICAST)
604
        f.flags |= IF_MULTICAST;
605

    
606
      ifi = if_update(&f);
607

    
608
      if (!scan)
609
        if_end_partial_update(ifi);
610
    }
611
}
612

    
613
static void
614
nl_parse_addr4(struct ifaddrmsg *i, int scan, int new)
615
{
616
  struct rtattr *a[BIRD_IFA_MAX];
617
  struct iface *ifi;
618
  int scope;
619

    
620
  if (!nl_parse_attrs(IFA_RTA(i), ifa_attr_want4, a, sizeof(a)))
621
    return;
622

    
623
  if (!a[IFA_LOCAL])
624
    {
625
      log(L_ERR "KIF: Malformed message received (missing IFA_LOCAL)");
626
      return;
627
    }
628
  if (!a[IFA_ADDRESS])
629
    {
630
      log(L_ERR "KIF: Malformed message received (missing IFA_ADDRESS)");
631
      return;
632
    }
633

    
634
  ifi = if_find_by_index(i->ifa_index);
635
  if (!ifi)
636
    {
637
      log(L_ERR "KIF: Received address message for unknown interface %d", i->ifa_index);
638
      return;
639
    }
640

    
641
  struct ifa ifa;
642
  bzero(&ifa, sizeof(ifa));
643
  ifa.iface = ifi;
644
  if (i->ifa_flags & IFA_F_SECONDARY)
645
    ifa.flags |= IA_SECONDARY;
646

    
647
  ifa.ip = rta_get_ipa(a[IFA_LOCAL]);
648

    
649
  if (i->ifa_prefixlen > BITS_PER_IP_ADDRESS)
650
    {
651
      log(L_ERR "KIF: Invalid prefix length for interface %s: %d", ifi->name, i->ifa_prefixlen);
652
      new = 0;
653
    }
654
  if (i->ifa_prefixlen == BITS_PER_IP_ADDRESS)
655
    {
656
      ifa.brd = rta_get_ipa(a[IFA_ADDRESS]);
657
      net_fill_ip4(&ifa.prefix, rta_get_ip4(a[IFA_ADDRESS]), i->ifa_prefixlen);
658

    
659
      /* It is either a host address or a peer address */
660
      if (ipa_equal(ifa.ip, ifa.brd))
661
        ifa.flags |= IA_HOST;
662
      else
663
        {
664
          ifa.flags |= IA_PEER;
665
          ifa.opposite = ifa.brd;
666
        }
667
    }
668
  else
669
    {
670
      net_fill_ip4(&ifa.prefix, ipa_to_ip4(ifa.ip), i->ifa_prefixlen);
671
      net_normalize(&ifa.prefix);
672

    
673
      if (i->ifa_prefixlen == BITS_PER_IP_ADDRESS - 1)
674
        ifa.opposite = ipa_opposite_m1(ifa.ip);
675

    
676
      if (i->ifa_prefixlen == BITS_PER_IP_ADDRESS - 2)
677
        ifa.opposite = ipa_opposite_m2(ifa.ip);
678

    
679
      if ((ifi->flags & IF_BROADCAST) && a[IFA_BROADCAST])
680
        {
681
          ip4_addr xbrd = rta_get_ip4(a[IFA_BROADCAST]);
682
          ip4_addr ybrd = ip4_or(ipa_to_ip4(ifa.ip), ip4_not(ip4_mkmask(i->ifa_prefixlen)));
683

    
684
          if (ip4_equal(xbrd, net4_prefix(&ifa.prefix)) || ip4_equal(xbrd, ybrd))
685
            ifa.brd = ipa_from_ip4(xbrd);
686
          else if (ifi->flags & IF_TMP_DOWN) /* Complain only during the first scan */
687
            {
688
              log(L_ERR "KIF: Invalid broadcast address %I for %s", xbrd, ifi->name);
689
              ifa.brd = ipa_from_ip4(ybrd);
690
            }
691
        }
692
    }
693

    
694
  scope = ipa_classify(ifa.ip);
695
  if (scope < 0)
696
    {
697
      log(L_ERR "KIF: Invalid interface address %I for %s", ifa.ip, ifi->name);
698
      return;
699
    }
700
  ifa.scope = scope & IADDR_SCOPE_MASK;
701

    
702
  DBG("KIF: IF%d(%s): %s IPA %I, flg %x, net %N, brd %I, opp %I\n",
703
      ifi->index, ifi->name,
704
      new ? "added" : "removed",
705
      ifa.ip, ifa.flags, ifa.prefix, ifa.brd, ifa.opposite);
706

    
707
  if (new)
708
    ifa_update(&ifa);
709
  else
710
    ifa_delete(&ifa);
711

    
712
  if (!scan)
713
    if_end_partial_update(ifi);
714
}
715

    
716
static void
717
nl_parse_addr6(struct ifaddrmsg *i, int scan, int new)
718
{
719
  struct rtattr *a[BIRD_IFA_MAX];
720
  struct iface *ifi;
721
  int scope;
722

    
723
  if (!nl_parse_attrs(IFA_RTA(i), ifa_attr_want6, a, sizeof(a)))
724
    return;
725

    
726
  if (!a[IFA_ADDRESS])
727
    {
728
      log(L_ERR "KIF: Malformed message received (missing IFA_ADDRESS)");
729
      return;
730
    }
731

    
732
  ifi = if_find_by_index(i->ifa_index);
733
  if (!ifi)
734
    {
735
      log(L_ERR "KIF: Received address message for unknown interface %d", i->ifa_index);
736
      return;
737
    }
738

    
739
  struct ifa ifa;
740
  bzero(&ifa, sizeof(ifa));
741
  ifa.iface = ifi;
742
  if (i->ifa_flags & IFA_F_SECONDARY)
743
    ifa.flags |= IA_SECONDARY;
744

    
745
  /* IFA_LOCAL can be unset for IPv6 interfaces */
746

    
747
  ifa.ip = rta_get_ipa(a[IFA_LOCAL] ? : a[IFA_ADDRESS]);
748

    
749
  if (i->ifa_prefixlen > BITS_PER_IP_ADDRESS)
750
    {
751
      log(L_ERR "KIF: Invalid prefix length for interface %s: %d", ifi->name, i->ifa_prefixlen);
752
      new = 0;
753
    }
754
  if (i->ifa_prefixlen == BITS_PER_IP_ADDRESS)
755
    {
756
      ifa.brd = rta_get_ipa(a[IFA_ADDRESS]);
757
      net_fill_ip6(&ifa.prefix, rta_get_ip6(a[IFA_ADDRESS]), i->ifa_prefixlen);
758

    
759
      /* It is either a host address or a peer address */
760
      if (ipa_equal(ifa.ip, ifa.brd))
761
        ifa.flags |= IA_HOST;
762
      else
763
        {
764
          ifa.flags |= IA_PEER;
765
          ifa.opposite = ifa.brd;
766
        }
767
    }
768
  else
769
    {
770
      net_fill_ip6(&ifa.prefix, ipa_to_ip6(ifa.ip), i->ifa_prefixlen);
771
      net_normalize(&ifa.prefix);
772

    
773
      if (i->ifa_prefixlen == BITS_PER_IP_ADDRESS - 1)
774
        ifa.opposite = ipa_opposite_m1(ifa.ip);
775
    }
776

    
777
  scope = ipa_classify(ifa.ip);
778
  if (scope < 0)
779
    {
780
      log(L_ERR "KIF: Invalid interface address %I for %s", ifa.ip, ifi->name);
781
      return;
782
    }
783
  ifa.scope = scope & IADDR_SCOPE_MASK;
784

    
785
  DBG("KIF: IF%d(%s): %s IPA %I, flg %x, net %N, brd %I, opp %I\n",
786
      ifi->index, ifi->name,
787
      new ? "added" : "removed",
788
      ifa.ip, ifa.flags, ifa.prefix, ifa.brd, ifa.opposite);
789

    
790
  if (new)
791
    ifa_update(&ifa);
792
  else
793
    ifa_delete(&ifa);
794

    
795
  if (!scan)
796
    if_end_partial_update(ifi);
797
}
798

    
799
static void
800
nl_parse_addr(struct nlmsghdr *h, int scan)
801
{
802
  struct ifaddrmsg *i;
803

    
804
  if (!(i = nl_checkin(h, sizeof(*i))))
805
    return;
806

    
807
  int new = (h->nlmsg_type == RTM_NEWADDR);
808

    
809
  switch (i->ifa_family)
810
    {
811
#ifndef IPV6
812
      case AF_INET:
813
        return nl_parse_addr4(i, scan, new);
814
#else
815
      case AF_INET6:
816
        return nl_parse_addr6(i, scan, new);
817
#endif
818
    }
819
}
820

    
821
void
822
kif_do_scan(struct kif_proto *p UNUSED)
823
{
824
  struct nlmsghdr *h;
825

    
826
  if_start_update();
827

    
828
  nl_request_dump(AF_UNSPEC, RTM_GETLINK);
829
  while (h = nl_get_scan())
830
    if (h->nlmsg_type == RTM_NEWLINK || h->nlmsg_type == RTM_DELLINK)
831
      nl_parse_link(h, 1);
832
    else
833
      log(L_DEBUG "nl_scan_ifaces: Unknown packet received (type=%d)", h->nlmsg_type);
834

    
835
  nl_request_dump(BIRD_AF, RTM_GETADDR);
836
  while (h = nl_get_scan())
837
    if (h->nlmsg_type == RTM_NEWADDR || h->nlmsg_type == RTM_DELADDR)
838
      nl_parse_addr(h, 1);
839
    else
840
      log(L_DEBUG "nl_scan_ifaces: Unknown packet received (type=%d)", h->nlmsg_type);
841

    
842
  if_end_update();
843
}
844

    
845
/*
846
 *        Routes
847
 */
848

    
849
static inline u32
850
krt_table_id(struct krt_proto *p)
851
{
852
  return KRT_CF->sys.table_id;
853
}
854

    
855
static HASH(struct krt_proto) nl_table_map;
856

    
857
#define RTH_FN(k)        u32_hash(k)
858
#define RTH_EQ(k1,k2)        k1 == k2
859
#define RTH_KEY(p)        krt_table_id(p)
860
#define RTH_NEXT(p)        p->sys.hash_next
861

    
862
#define RTH_REHASH                rth_rehash
863
#define RTH_PARAMS                /8, *2, 2, 2, 6, 20
864

    
865
HASH_DEFINE_REHASH_FN(RTH, struct krt_proto)
866

    
867
int
868
krt_capable(rte *e)
869
{
870
  rta *a = e->attrs;
871

    
872
  if (a->cast != RTC_UNICAST)
873
    return 0;
874

    
875
  switch (a->dest)
876
    {
877
    case RTD_ROUTER:
878
    case RTD_DEVICE:
879
      if (a->iface == NULL)
880
        return 0;
881
    case RTD_BLACKHOLE:
882
    case RTD_UNREACHABLE:
883
    case RTD_PROHIBIT:
884
    case RTD_MULTIPATH:
885
      break;
886
    default:
887
      return 0;
888
    }
889
  return 1;
890
}
891

    
892
static inline int
893
nh_bufsize(struct mpnh *nh)
894
{
895
  int rv = 0;
896
  for (; nh != NULL; nh = nh->next)
897
    rv += RTNH_LENGTH(RTA_LENGTH(sizeof(ip_addr)));
898
  return rv;
899
}
900

    
901
static int
902
nl_send_route(struct krt_proto *p, rte *e, struct ea_list *eattrs, int new)
903
{
904
  eattr *ea;
905
  net *net = e->net;
906
  rta *a = e->attrs;
907
  struct {
908
    struct nlmsghdr h;
909
    struct rtmsg r;
910
    char buf[128 + KRT_METRICS_MAX*8 + nh_bufsize(a->nexthops)];
911
  } r;
912

    
913
  DBG("nl_send_route(%N,new=%d)\n", net->n.addr, new);
914

    
915
  bzero(&r.h, sizeof(r.h));
916
  bzero(&r.r, sizeof(r.r));
917
  r.h.nlmsg_type = new ? RTM_NEWROUTE : RTM_DELROUTE;
918
  r.h.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
919
  r.h.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | (new ? NLM_F_CREATE|NLM_F_EXCL : 0);
920

    
921
  int af = AF_UNSPEC;
922

    
923
  switch(net->n.addr->type) {
924
    case NET_IP4:
925
      af = AF_INET;
926
      break;
927
    case NET_IP6:
928
      af = AF_INET6;
929
      break;
930
    default:
931
      bug("should not send vpn route to kernel");
932
  }
933

    
934
  r.r.rtm_family = af;
935
  r.r.rtm_dst_len = net_pxlen(net->n.addr);
936
  r.r.rtm_protocol = RTPROT_BIRD;
937
  r.r.rtm_scope = RT_SCOPE_UNIVERSE;
938
  nl_add_attr_ipa(&r.h, sizeof(r), RTA_DST, net_prefix(net->n.addr), af);
939

    
940
  if (krt_table_id(p) < 256)
941
    r.r.rtm_table = krt_table_id(p);
942
  else
943
    nl_add_attr_u32(&r.h, sizeof(r), RTA_TABLE, krt_table_id(p));
944

    
945
  /* For route delete, we do not specify route attributes */
946
  if (!new)
947
    return nl_exchange(&r.h);
948

    
949

    
950
  if (ea = ea_find(eattrs, EA_KRT_METRIC))
951
    nl_add_attr_u32(&r.h, sizeof(r), RTA_PRIORITY, ea->u.data);
952

    
953
  if (ea = ea_find(eattrs, EA_KRT_PREFSRC))
954
    nl_add_attr_ipa(&r.h, sizeof(r), RTA_PREFSRC, *(ip_addr *)ea->u.ptr->data, af);
955

    
956
  if (ea = ea_find(eattrs, EA_KRT_REALM))
957
    nl_add_attr_u32(&r.h, sizeof(r), RTA_FLOW, ea->u.data);
958

    
959

    
960
  u32 metrics[KRT_METRICS_MAX];
961
  metrics[0] = 0;
962

    
963
  struct ea_walk_state ews = { .eattrs = eattrs };
964
  while (ea = ea_walk(&ews, EA_KRT_METRICS, KRT_METRICS_MAX))
965
  {
966
    int id = ea->id - EA_KRT_METRICS;
967
    metrics[0] |= 1 << id;
968
    metrics[id] = ea->u.data;
969
  }
970

    
971
  if (metrics[0])
972
    nl_add_metrics(&r.h, sizeof(r), metrics, KRT_METRICS_MAX);
973

    
974

    
975
  /* a->iface != NULL checked in krt_capable() for router and device routes */
976

    
977
  switch (a->dest)
978
    {
979
    case RTD_ROUTER:
980
      r.r.rtm_type = RTN_UNICAST;
981
      nl_add_attr_u32(&r.h, sizeof(r), RTA_OIF, a->iface->index);
982
      nl_add_attr_ipa(&r.h, sizeof(r), RTA_GATEWAY, a->gw, af);
983
      break;
984
    case RTD_DEVICE:
985
      r.r.rtm_type = RTN_UNICAST;
986
      nl_add_attr_u32(&r.h, sizeof(r), RTA_OIF, a->iface->index);
987
      break;
988
    case RTD_BLACKHOLE:
989
      r.r.rtm_type = RTN_BLACKHOLE;
990
      break;
991
    case RTD_UNREACHABLE:
992
      r.r.rtm_type = RTN_UNREACHABLE;
993
      break;
994
    case RTD_PROHIBIT:
995
      r.r.rtm_type = RTN_PROHIBIT;
996
      break;
997
    case RTD_MULTIPATH:
998
      r.r.rtm_type = RTN_UNICAST;
999
      nl_add_multipath(&r.h, sizeof(r), a->nexthops);
1000
      break;
1001
    default:
1002
      bug("krt_capable inconsistent with nl_send_route");
1003
    }
1004

    
1005
  return nl_exchange(&r.h);
1006
}
1007

    
1008
void
1009
krt_replace_rte(struct krt_proto *p, net *n, rte *new, rte *old, struct ea_list *eattrs)
1010
{
1011
  int err = 0;
1012

    
1013
  /*
1014
   * NULL for eattr of the old route is a little hack, but we don't
1015
   * get proper eattrs for old in rt_notify() anyway. NULL means no
1016
   * extended route attributes and therefore matches if the kernel
1017
   * route has any of them.
1018
   */
1019

    
1020
  if (old)
1021
    nl_send_route(p, old, NULL, 0);
1022

    
1023
  if (new)
1024
    err = nl_send_route(p, new, eattrs, 1);
1025

    
1026
  if (err < 0)
1027
    n->n.flags |= KRF_SYNC_ERROR;
1028
  else
1029
    n->n.flags &= ~KRF_SYNC_ERROR;
1030
}
1031

    
1032

    
1033
#define SKIP(ARG...) do { DBG("KRT: Ignoring route - " ARG); return; } while(0)
1034

    
1035
static void
1036
nl_parse_route(struct nlmsghdr *h, int scan)
1037
{
1038
  struct krt_proto *p;
1039
  struct rtmsg *i;
1040
  struct rtattr *a[BIRD_RTA_MAX];
1041
  int new = h->nlmsg_type == RTM_NEWROUTE;
1042

    
1043
  net_addr dst = { 0 };
1044
  u32 oif = ~0;
1045
  u32 table;
1046
  int src;
1047

    
1048
  int ipv6 = 0;
1049

    
1050
  if (!(i = nl_checkin(h, sizeof(*i))))
1051
    return;
1052

    
1053
  switch (i->rtm_family)
1054
    {
1055
#ifndef IPV6
1056
      case AF_INET:
1057
        if (!nl_parse_attrs(RTM_RTA(i), rtm_attr_want4, a, sizeof(a)))
1058
          return;
1059
        break;
1060
#else
1061
      case AF_INET6:
1062
        if (!nl_parse_attrs(RTM_RTA(i), rtm_attr_want6, a, sizeof(a)))
1063
          return;
1064
        ipv6 = 1;
1065
        break;
1066
#endif
1067
      default:
1068
        return;
1069
    }
1070

    
1071
  if (a[RTA_DST])
1072
    net_fill_ipa(&dst, rta_get_ipa(a[RTA_DST]), i->rtm_dst_len);
1073

    
1074
  if (a[RTA_OIF])
1075
    oif = rta_get_u32(a[RTA_OIF]);
1076

    
1077
  if (a[RTA_TABLE])
1078
    table = rta_get_u32(a[RTA_TABLE]);
1079
  else
1080
    table = i->rtm_table;
1081

    
1082
  p = HASH_FIND(nl_table_map, RTH, table); /* Do we know this table? */
1083
  DBG("KRT: Got %I/%d, type=%d, oif=%d, table=%d, prid=%d, proto=%s\n", dst, i->rtm_dst_len, i->rtm_type, oif, table, i->rtm_protocol, p ? p->p.name : "(none)");
1084
  if (!p)
1085
    SKIP("unknown table %d\n", table);
1086

    
1087

    
1088
  if (a[RTA_IIF])
1089
    SKIP("IIF set\n");
1090
  if (i->rtm_tos != 0)                        /* We don't support TOS */
1091
    SKIP("TOS %02x\n", i->rtm_tos);
1092

    
1093
  if (scan && !new)
1094
    SKIP("RTM_DELROUTE in scan\n");
1095

    
1096
  int c = net_classify(&dst);
1097
  if ((c < 0) || !(c & IADDR_HOST) || ((c & IADDR_SCOPE_MASK) <= SCOPE_LINK))
1098
    SKIP("strange class/scope\n");
1099

    
1100
  // ignore rtm_scope, it is not a real scope
1101
  // if (i->rtm_scope != RT_SCOPE_UNIVERSE)
1102
  //   SKIP("scope %u\n", i->rtm_scope);
1103

    
1104
  switch (i->rtm_protocol)
1105
    {
1106
    case RTPROT_UNSPEC:
1107
      SKIP("proto unspec\n");
1108

    
1109
    case RTPROT_REDIRECT:
1110
      src = KRT_SRC_REDIRECT;
1111
      break;
1112

    
1113
    case RTPROT_KERNEL:
1114
      src = KRT_SRC_KERNEL;
1115
      return;
1116

    
1117
    case RTPROT_BIRD:
1118
      if (!scan)
1119
        SKIP("echo\n");
1120
      src = KRT_SRC_BIRD;
1121
      break;
1122

    
1123
    case RTPROT_BOOT:
1124
    default:
1125
      src = KRT_SRC_ALIEN;
1126
    }
1127

    
1128
  net *net = net_get(p->p.table, &dst);
1129

    
1130
  rta ra = {
1131
    .src= p->p.main_source,
1132
    .source = RTS_INHERIT,
1133
    .scope = SCOPE_UNIVERSE,
1134
    .cast = RTC_UNICAST
1135
  };
1136

    
1137
  switch (i->rtm_type)
1138
    {
1139
    case RTN_UNICAST:
1140

    
1141
      if (a[RTA_MULTIPATH] && (i->rtm_family == AF_INET))
1142
        {
1143
          ra.dest = RTD_MULTIPATH;
1144
          ra.nexthops = nl_parse_multipath(p, a[RTA_MULTIPATH]);
1145
          if (!ra.nexthops)
1146
            {
1147
              log(L_ERR "KRT: Received strange multipath route %N", net->n.addr);
1148
              return;
1149
            }
1150

    
1151
          break;
1152
        }
1153

    
1154
      ra.iface = if_find_by_index(oif);
1155
      if (!ra.iface)
1156
        {
1157
          log(L_ERR "KRT: Received route %N with unknown ifindex %u", net->n.addr, oif);
1158
          return;
1159
        }
1160

    
1161
      if (a[RTA_GATEWAY])
1162
        {
1163
          neighbor *ng;
1164
          ra.dest = RTD_ROUTER;
1165
          memcpy(&ra.gw, RTA_DATA(a[RTA_GATEWAY]), sizeof(ra.gw));
1166
          ipa_ntoh(ra.gw);
1167

    
1168
          /* Silently skip strange 6to4 routes */
1169
          if (ipv6 && ipa_in_net(ra.gw, IPA_NONE, 96))
1170
            return;
1171

    
1172
          ng = neigh_find2(&p->p, &ra.gw, ra.iface,
1173
                           (i->rtm_flags & RTNH_F_ONLINK) ? NEF_ONLINK : 0);
1174
          if (!ng || (ng->scope == SCOPE_HOST))
1175
            {
1176
              log(L_ERR "KRT: Received route %N with strange next-hop %I", net->n.addr, ra.gw);
1177
              return;
1178
            }
1179
        }
1180
      else
1181
        {
1182
          ra.dest = RTD_DEVICE;
1183
        }
1184

    
1185
      break;
1186
    case RTN_BLACKHOLE:
1187
      ra.dest = RTD_BLACKHOLE;
1188
      break;
1189
    case RTN_UNREACHABLE:
1190
      ra.dest = RTD_UNREACHABLE;
1191
      break;
1192
    case RTN_PROHIBIT:
1193
      ra.dest = RTD_PROHIBIT;
1194
      break;
1195
    /* FIXME: What about RTN_THROW? */
1196
    default:
1197
      SKIP("type %d\n", i->rtm_type);
1198
      return;
1199
    }
1200

    
1201
  rte *e = rte_get_temp(&ra);
1202
  e->net = net;
1203
  e->u.krt.src = src;
1204
  e->u.krt.proto = i->rtm_protocol;
1205
  e->u.krt.type = i->rtm_type;
1206
  e->u.krt.metric = 0;
1207

    
1208
  if (a[RTA_PRIORITY])
1209
    e->u.krt.metric = rta_get_u32(a[RTA_PRIORITY]);
1210

    
1211
  if (a[RTA_PREFSRC])
1212
    {
1213
      ip_addr ps = rta_get_ipa(a[RTA_PREFSRC]);
1214

    
1215
      ea_list *ea = alloca(sizeof(ea_list) + sizeof(eattr));
1216
      ea->next = ra.eattrs;
1217
      ra.eattrs = ea;
1218
      ea->flags = EALF_SORTED;
1219
      ea->count = 1;
1220
      ea->attrs[0].id = EA_KRT_PREFSRC;
1221
      ea->attrs[0].flags = 0;
1222
      ea->attrs[0].type = EAF_TYPE_IP_ADDRESS;
1223
      ea->attrs[0].u.ptr = alloca(sizeof(struct adata) + sizeof(ps));
1224
      ea->attrs[0].u.ptr->length = sizeof(ps);
1225
      memcpy(ea->attrs[0].u.ptr->data, &ps, sizeof(ps));
1226
    }
1227

    
1228
  if (a[RTA_FLOW])
1229
    {
1230
      ea_list *ea = alloca(sizeof(ea_list) + sizeof(eattr));
1231
      ea->next = ra.eattrs;
1232
      ra.eattrs = ea;
1233
      ea->flags = EALF_SORTED;
1234
      ea->count = 1;
1235
      ea->attrs[0].id = EA_KRT_REALM;
1236
      ea->attrs[0].flags = 0;
1237
      ea->attrs[0].type = EAF_TYPE_INT;
1238
      ea->attrs[0].u.data = rta_get_u32(a[RTA_FLOW]);
1239
    }
1240

    
1241
  if (a[RTA_METRICS])
1242
    {
1243
      u32 metrics[KRT_METRICS_MAX];
1244
      ea_list *ea = alloca(sizeof(ea_list) + KRT_METRICS_MAX * sizeof(eattr));
1245
      int t, n = 0;
1246

    
1247
      if (nl_parse_metrics(a[RTA_METRICS], metrics, ARRAY_SIZE(metrics)) < 0)
1248
        {
1249
          log(L_ERR "KRT: Received route %N with strange RTA_METRICS attribute", net->n.addr);
1250
          return;
1251
        }
1252

    
1253
      for (t = 1; t < KRT_METRICS_MAX; t++)
1254
        if (metrics[0] & (1 << t))
1255
          {
1256
            ea->attrs[n].id = EA_CODE(EAP_KRT, KRT_METRICS_OFFSET + t);
1257
            ea->attrs[n].flags = 0;
1258
            ea->attrs[n].type = EAF_TYPE_INT; /* FIXME: Some are EAF_TYPE_BITFIELD */
1259
            ea->attrs[n].u.data = metrics[t];
1260
            n++;
1261
          }
1262

    
1263
      if (n > 0)
1264
        {
1265
          ea->next = ra.eattrs;
1266
          ea->flags = EALF_SORTED;
1267
          ea->count = n;
1268
          ra.eattrs = ea;
1269
        }
1270
    }
1271

    
1272
  if (scan)
1273
    krt_got_route(p, e);
1274
  else
1275
    krt_got_route_async(p, e, new);
1276
}
1277

    
1278
void
1279
krt_do_scan(struct krt_proto *p UNUSED)        /* CONFIG_ALL_TABLES_AT_ONCE => p is NULL */
1280
{
1281
  struct nlmsghdr *h;
1282

    
1283
  nl_request_dump(BIRD_AF, RTM_GETROUTE);
1284
  while (h = nl_get_scan())
1285
    if (h->nlmsg_type == RTM_NEWROUTE || h->nlmsg_type == RTM_DELROUTE)
1286
      nl_parse_route(h, 1);
1287
    else
1288
      log(L_DEBUG "nl_scan_fire: Unknown packet received (type=%d)", h->nlmsg_type);
1289
}
1290

    
1291
/*
1292
 *        Asynchronous Netlink interface
1293
 */
1294

    
1295
static sock *nl_async_sk;                /* BIRD socket for asynchronous notifications */
1296
static byte *nl_async_rx_buffer;        /* Receive buffer */
1297

    
1298
static void
1299
nl_async_msg(struct nlmsghdr *h)
1300
{
1301
  switch (h->nlmsg_type)
1302
    {
1303
    case RTM_NEWROUTE:
1304
    case RTM_DELROUTE:
1305
      DBG("KRT: Received async route notification (%d)\n", h->nlmsg_type);
1306
      nl_parse_route(h, 0);
1307
      break;
1308
    case RTM_NEWLINK:
1309
    case RTM_DELLINK:
1310
      DBG("KRT: Received async link notification (%d)\n", h->nlmsg_type);
1311
      if (kif_proto)
1312
        nl_parse_link(h, 0);
1313
      break;
1314
    case RTM_NEWADDR:
1315
    case RTM_DELADDR:
1316
      DBG("KRT: Received async address notification (%d)\n", h->nlmsg_type);
1317
      if (kif_proto)
1318
        nl_parse_addr(h, 0);
1319
      break;
1320
    default:
1321
      DBG("KRT: Received unknown async notification (%d)\n", h->nlmsg_type);
1322
    }
1323
}
1324

    
1325
static int
1326
nl_async_hook(sock *sk, int size UNUSED)
1327
{
1328
  struct iovec iov = { nl_async_rx_buffer, NL_RX_SIZE };
1329
  struct sockaddr_nl sa;
1330
  struct msghdr m = { (struct sockaddr *) &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
1331
  struct nlmsghdr *h;
1332
  int x;
1333
  uint len;
1334

    
1335
  x = recvmsg(sk->fd, &m, 0);
1336
  if (x < 0)
1337
    {
1338
      if (errno == ENOBUFS)
1339
        {
1340
          /*
1341
           *  Netlink reports some packets have been thrown away.
1342
           *  One day we might react to it by asking for route table
1343
           *  scan in near future.
1344
           */
1345
          return 1;        /* More data are likely to be ready */
1346
        }
1347
      else if (errno != EWOULDBLOCK)
1348
        log(L_ERR "Netlink recvmsg: %m");
1349
      return 0;
1350
    }
1351
  if (sa.nl_pid)                /* It isn't from the kernel */
1352
    {
1353
      DBG("Non-kernel packet\n");
1354
      return 1;
1355
    }
1356
  h = (void *) nl_async_rx_buffer;
1357
  len = x;
1358
  if (m.msg_flags & MSG_TRUNC)
1359
    {
1360
      log(L_WARN "Netlink got truncated asynchronous message");
1361
      return 1;
1362
    }
1363
  while (NLMSG_OK(h, len))
1364
    {
1365
      nl_async_msg(h);
1366
      h = NLMSG_NEXT(h, len);
1367
    }
1368
  if (len)
1369
    log(L_WARN "nl_async_hook: Found packet remnant of size %d", len);
1370
  return 1;
1371
}
1372

    
1373
static void
1374
nl_open_async(void)
1375
{
1376
  sock *sk;
1377
  struct sockaddr_nl sa;
1378
  int fd;
1379

    
1380
  if (nl_async_sk)
1381
    return;
1382

    
1383
  DBG("KRT: Opening async netlink socket\n");
1384

    
1385
  fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1386
  if (fd < 0)
1387
    {
1388
      log(L_ERR "Unable to open asynchronous rtnetlink socket: %m");
1389
      return;
1390
    }
1391

    
1392
  bzero(&sa, sizeof(sa));
1393
  sa.nl_family = AF_NETLINK;
1394
#ifdef IPV6
1395
  sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_ROUTE;
1396
#else
1397
  sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE;
1398
#endif
1399
  if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
1400
    {
1401
      log(L_ERR "Unable to bind asynchronous rtnetlink socket: %m");
1402
      close(fd);
1403
      return;
1404
    }
1405

    
1406
  nl_async_rx_buffer = xmalloc(NL_RX_SIZE);
1407

    
1408
  sk = nl_async_sk = sk_new(krt_pool);
1409
  sk->type = SK_MAGIC;
1410
  sk->rx_hook = nl_async_hook;
1411
  sk->fd = fd;
1412
  if (sk_open(sk) < 0)
1413
    bug("Netlink: sk_open failed");
1414
}
1415

    
1416

    
1417
/*
1418
 *        Interface to the UNIX krt module
1419
 */
1420

    
1421
void
1422
krt_sys_io_init(void)
1423
{
1424
  HASH_INIT(nl_table_map, krt_pool, 6);
1425
}
1426

    
1427
int
1428
krt_sys_start(struct krt_proto *p)
1429
{
1430
  struct krt_proto *old = HASH_FIND(nl_table_map, RTH, krt_table_id(p));
1431

    
1432
  if (old)
1433
    {
1434
      log(L_ERR "%s: Kernel table %u already registered by %s",
1435
          p->p.name, krt_table_id(p), old->p.name);
1436
      return 0;
1437
    }
1438

    
1439
  HASH_INSERT2(nl_table_map, RTH, krt_pool, p);
1440

    
1441
  nl_open();
1442
  nl_open_async();
1443

    
1444
  return 1;
1445
}
1446

    
1447
void
1448
krt_sys_shutdown(struct krt_proto *p)
1449
{
1450
  HASH_REMOVE2(nl_table_map, RTH, krt_pool, p);
1451
}
1452

    
1453
int
1454
krt_sys_reconfigure(struct krt_proto *p UNUSED, struct krt_config *n, struct krt_config *o)
1455
{
1456
  return n->sys.table_id == o->sys.table_id;
1457
}
1458

    
1459
void
1460
krt_sys_init_config(struct krt_config *cf)
1461
{
1462
  cf->sys.table_id = RT_TABLE_MAIN;
1463
}
1464

    
1465
void
1466
krt_sys_copy_config(struct krt_config *d, struct krt_config *s)
1467
{
1468
  d->sys.table_id = s->sys.table_id;
1469
}
1470

    
1471
static const char *krt_metrics_names[KRT_METRICS_MAX] = {
1472
  NULL, "lock", "mtu", "window", "rtt", "rttvar", "sstresh", "cwnd", "advmss",
1473
  "reordering", "hoplimit", "initcwnd", "features", "rto_min", "initrwnd", "quickack"
1474
};
1475

    
1476
static const char *krt_features_names[KRT_FEATURES_MAX] = {
1477
  "ecn", NULL, NULL, "allfrag"
1478
};
1479

    
1480
int
1481
krt_sys_get_attr(eattr *a, byte *buf, int buflen UNUSED)
1482
{
1483
  switch (a->id)
1484
  {
1485
  case EA_KRT_PREFSRC:
1486
    bsprintf(buf, "prefsrc");
1487
    return GA_NAME;
1488

    
1489
  case EA_KRT_REALM:
1490
    bsprintf(buf, "realm");
1491
    return GA_NAME;
1492

    
1493
  case EA_KRT_LOCK:
1494
    buf += bsprintf(buf, "lock:");
1495
    ea_format_bitfield(a, buf, buflen, krt_metrics_names, 2, KRT_METRICS_MAX);
1496
    return GA_FULL;
1497

    
1498
  case EA_KRT_FEATURES:
1499
    buf += bsprintf(buf, "features:");
1500
    ea_format_bitfield(a, buf, buflen, krt_features_names, 0, KRT_FEATURES_MAX);
1501
    return GA_FULL;
1502

    
1503
  default:;
1504
    int id = (int)EA_ID(a->id) - KRT_METRICS_OFFSET;
1505
    if (id > 0 && id < KRT_METRICS_MAX)
1506
    {
1507
      bsprintf(buf, "%s", krt_metrics_names[id]);
1508
      return GA_NAME;
1509
    }
1510

    
1511
    return GA_UNKNOWN;
1512
  }
1513
}
1514

    
1515

    
1516

    
1517
void
1518
kif_sys_start(struct kif_proto *p UNUSED)
1519
{
1520
  nl_open();
1521
  nl_open_async();
1522
}
1523

    
1524
void
1525
kif_sys_shutdown(struct kif_proto *p UNUSED)
1526
{
1527
}