attrs.c 54.3 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 *	BIRD -- BGP Attributes
 *
 *	(c) 2000 Martin Mares <mj@ucw.cz>
 *
 *	Can be freely distributed and used under the terms of the GNU GPL.
 */

Martin Mareš's avatar
Martin Mareš committed
9
#undef LOCAL_DEBUG
10

11 12
#include <stdlib.h>

13 14 15 16
#include "nest/bird.h"
#include "nest/iface.h"
#include "nest/protocol.h"
#include "nest/route.h"
17
#include "nest/attrs.h"
18
#include "conf/conf.h"
19 20 21
#include "lib/resource.h"
#include "lib/string.h"
#include "lib/unaligned.h"
22 23

#include "bgp.h"
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
/*
 *   UPDATE message error handling
 *
 * All checks from RFC 4271 6.3 are done as specified with these exceptions:
 *  - The semantic check of an IP address from NEXT_HOP attribute is missing.
 *  - Checks of some optional attribute values are missing.
 *  - Syntactic and semantic checks of NLRIs (done in DECODE_PREFIX())
 *    are probably inadequate.
 *
 * Loop detection based on AS_PATH causes updates to be withdrawn. RFC
 * 4271 does not explicitly specifiy the behavior in that case.
 *
 * Loop detection related to route reflection (based on ORIGINATOR_ID
 * and CLUSTER_LIST) causes updates to be withdrawn. RFC 4456 8
 * specifies that such updates should be ignored, but that is generally
 * a bad idea.
 *
 * Error checking of optional transitive attributes is done according to
 * draft-ietf-idr-optional-transitive-03, but errors are handled always
 * as withdraws.
 *
 * Unexpected AS_CONFED_* segments in AS_PATH are logged and removed,
 * but unknown segments cause a session drop with Malformed AS_PATH
 * error (see validate_path()). The behavior in such case is not
 * explicitly specified by RFC 4271. RFC 5065 specifies that
 * inconsistent AS_CONFED_* segments should cause a session drop, but
 * implementations that pass invalid AS_CONFED_* segments are
 * widespread.
 *
54 55 56
 * Error handling of AS4_* attributes is done as specified by RFC 6793. There
 * are several possible inconsistencies between AGGREGATOR and AS4_AGGREGATOR
 * that are not handled by that RFC, these are logged and ignored (see
57 58 59
 * bgp_reconstruct_4b_attrs()).
 */

Ondřej Zajíček's avatar
Ondřej Zajíček committed
60

Martin Mareš's avatar
Martin Mareš committed
61 62 63 64 65
static byte bgp_mandatory_attrs[] = { BA_ORIGIN, BA_AS_PATH
#ifndef IPV6
,BA_NEXT_HOP
#endif
};
66 67

struct attr_desc {
68
  char *name;
69 70 71
  int expected_length;
  int expected_flags;
  int type;
72
  int allow_in_ebgp;
73
  int (*validate)(struct bgp_proto *p, byte *attr, int len);
74
  void (*format)(eattr *ea, byte *buf, int buflen);
75 76
};

77 78 79
#define IGNORE -1
#define WITHDRAW -2

80
static int
81
bgp_check_origin(struct bgp_proto *p UNUSED, byte *a, int len UNUSED)
82
{
83
  if (*a > 2)
84 85 86 87 88
    return 6;
  return 0;
}

static void
89
bgp_format_origin(eattr *a, byte *buf, int buflen UNUSED)
90 91 92 93 94 95 96
{
  static char *bgp_origin_names[] = { "IGP", "EGP", "Incomplete" };

  bsprintf(buf, bgp_origin_names[a->u.data]);
}

static int
97
path_segment_contains(byte *p, int bs, u32 asn)
98
{
99 100 101 102 103
  int i;
  int len = p[1];
  p += 2;

  for(i=0; i<len; i++)
104
    {
105 106 107 108
      u32 asn2 = (bs == 4) ? get_u32(p) : get_u16(p);
      if (asn2 == asn)
	return 1;
      p += bs;
109
    }
110

111 112 113
  return 0;
}

114
/* Validates path attribute, removes AS_CONFED_* segments, and also returns path length */
115
static int
Pavel Tvrdík's avatar
Pavel Tvrdík committed
116
validate_path(struct bgp_proto *p, int as_path, int bs, byte *idata, uint *ilength)
117 118 119
{
  int res = 0;
  u8 *a, *dst;
120
  int len, plen;
121 122 123 124 125 126 127 128 129 130 131 132 133

  dst = a = idata;
  len = *ilength;

  while (len)
    {
      if (len < 2)
	return -1;

      plen = 2 + bs * a[1];
      if (len < plen)
	return -1;

134 135 136 137 138 139 140
      if (a[1] == 0)
        {
	  log(L_WARN "%s: %s_PATH attribute contains empty segment, skipping it",
	      p->p.name, as_path ? "AS" : "AS4");
	  goto skip;
	}

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
      switch (a[0])
	{
	case AS_PATH_SET:
	  res++;
	  break;

	case AS_PATH_SEQUENCE:
	  res += a[1];
	  break;

	case AS_PATH_CONFED_SEQUENCE:
	case AS_PATH_CONFED_SET:
	  if (as_path && path_segment_contains(a, bs, p->remote_as))
	    {
	      log(L_WARN "%s: AS_CONFED_* segment with peer ASN found, misconfigured confederation?", p->p.name);
	      return -1;
	    }

	  log(L_WARN "%s: %s_PATH attribute contains AS_CONFED_* segment, skipping segment",
	      p->p.name, as_path ? "AS" : "AS4");
161
	  goto skip;
162 163 164 165 166

	default:
	  return -1;
	}

167 168 169
      if (dst != a)
	memmove(dst, a, plen);
      dst += plen;
170

171
    skip:
172 173 174 175 176 177 178 179 180 181
      len -= plen;
      a += plen;
    }

  *ilength = dst - idata;
  return res;
}

static inline int
validate_as_path(struct bgp_proto *p, byte *a, int *len)
182
{
183 184 185 186 187 188 189
  return validate_path(p, 1, p->as4_session ? 4 : 2, a, len);
}

static inline int
validate_as4_path(struct bgp_proto *p, struct adata *path)
{
  return validate_path(p, 0, 4, path->data, &path->length);
190 191
}

192
static int
193
bgp_check_next_hop(struct bgp_proto *p UNUSED, byte *a UNUSED6, int len UNUSED6)
194
{
Martin Mareš's avatar
Martin Mareš committed
195
#ifdef IPV6
196
  return IGNORE;
Martin Mareš's avatar
Martin Mareš committed
197
#else
198 199 200 201 202 203 204 205
  ip_addr addr;

  memcpy(&addr, a, len);
  ipa_ntoh(addr);
  if (ipa_classify(addr) & IADDR_HOST)
    return 0;
  else
    return 8;
Martin Mareš's avatar
Martin Mareš committed
206 207 208
#endif
}

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
static void
bgp_format_next_hop(eattr *a, byte *buf, int buflen UNUSED)
{
  ip_addr *ipp = (ip_addr *) a->u.ptr->data;
#ifdef IPV6
  /* in IPv6, we might have two addresses in NEXT HOP */
  if ((a->u.ptr->length == NEXT_HOP_LENGTH) && ipa_nonzero(ipp[1]))
    {
      bsprintf(buf, "%I %I", ipp[0], ipp[1]);
      return;
    }
#endif

  bsprintf(buf, "%I", ipp[0]);
}

225
static int
226
bgp_check_aggregator(struct bgp_proto *p, byte *a UNUSED, int len)
227
{
228
  int exp_len = p->as4_session ? 8 : 6;
229
  
230
  return (len == exp_len) ? 0 : WITHDRAW;
231 232
}

233 234 235 236 237 238 239
static void
bgp_format_aggregator(eattr *a, byte *buf, int buflen UNUSED)
{
  struct adata *ad =  a->u.ptr;
  byte *data = ad->data;
  u32 as;

240 241
  as = get_u32(data);
  data += 4;
242

243
  bsprintf(buf, "%d.%d.%d.%d AS%u", data[0], data[1], data[2], data[3], as);
244 245
}

246 247 248 249 250 251
static int
bgp_check_community(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
{
  return ((len % 4) == 0) ? 0 : WITHDRAW;
}

252
static int
253
bgp_check_cluster_list(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
254 255 256 257
{
  return ((len % 4) == 0) ? 0 : 5;
}

258
static void
259
bgp_format_cluster_list(eattr *a, byte *buf, int buflen)
260
{
261 262
  /* Truncates cluster lists larger than buflen, probably not a problem */
  int_set_format(a->u.ptr, 0, -1, buf, buflen);
263 264
}

Martin Mareš's avatar
Martin Mareš committed
265
static int
Martin Mareš's avatar
Martin Mareš committed
266
bgp_check_reach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
Martin Mareš's avatar
Martin Mareš committed
267 268 269 270 271
{
#ifdef IPV6
  p->mp_reach_start = a;
  p->mp_reach_len = len;
#endif
272
  return IGNORE;
Martin Mareš's avatar
Martin Mareš committed
273 274 275
}

static int
Martin Mareš's avatar
Martin Mareš committed
276
bgp_check_unreach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
Martin Mareš's avatar
Martin Mareš committed
277 278 279 280 281
{
#ifdef IPV6
  p->mp_unreach_start = a;
  p->mp_unreach_len = len;
#endif
282
  return IGNORE;
283 284
}

285 286 287 288 289 290
static int
bgp_check_ext_community(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
{
  return ((len % 8) == 0) ? 0 : WITHDRAW;
}

291 292 293 294 295 296
static int
bgp_check_large_community(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
{
  return ((len % 12) == 0) ? 0 : WITHDRAW;
}

297

298
static struct attr_desc bgp_attr_table[] = {
Martin Mareš's avatar
Martin Mareš committed
299
  { NULL, -1, 0, 0, 0,								/* Undefined */
300
    NULL, NULL },
Martin Mareš's avatar
Martin Mareš committed
301
  { "origin", 1, BAF_TRANSITIVE, EAF_TYPE_INT, 1,				/* BA_ORIGIN */
302
    bgp_check_origin, bgp_format_origin },
Martin Mareš's avatar
Martin Mareš committed
303
  { "as_path", -1, BAF_TRANSITIVE, EAF_TYPE_AS_PATH, 1,				/* BA_AS_PATH */
304
    NULL, NULL }, /* is checked by validate_as_path() as a special case */
Martin Mareš's avatar
Martin Mareš committed
305
  { "next_hop", 4, BAF_TRANSITIVE, EAF_TYPE_IP_ADDRESS, 1,			/* BA_NEXT_HOP */
306
    bgp_check_next_hop, bgp_format_next_hop },
307
  { "med", 4, BAF_OPTIONAL, EAF_TYPE_INT, 1,					/* BA_MULTI_EXIT_DISC */
308
    NULL, NULL },
309
  { "local_pref", 4, BAF_TRANSITIVE, EAF_TYPE_INT, 1,				/* BA_LOCAL_PREF */
310
    NULL, NULL },
Martin Mareš's avatar
Martin Mareš committed
311
  { "atomic_aggr", 0, BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,			/* BA_ATOMIC_AGGR */
312
    NULL, NULL },
313
  { "aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,	/* BA_AGGREGATOR */
314
    bgp_check_aggregator, bgp_format_aggregator },
Martin Mareš's avatar
Martin Mareš committed
315
  { "community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_INT_SET, 1,	/* BA_COMMUNITY */
316
    bgp_check_community, NULL },
317
  { "originator_id", 4, BAF_OPTIONAL, EAF_TYPE_ROUTER_ID, 0,			/* BA_ORIGINATOR_ID */
318 319
    NULL, NULL },
  { "cluster_list", -1, BAF_OPTIONAL, EAF_TYPE_INT_SET, 0,			/* BA_CLUSTER_LIST */
320
    bgp_check_cluster_list, bgp_format_cluster_list }, 
321
  { .name = NULL },								/* BA_DPA */
322 323
  { .name = NULL },								/* BA_ADVERTISER */
  { .name = NULL },								/* BA_RCID_PATH */
Martin Mareš's avatar
Martin Mareš committed
324 325 326 327
  { "mp_reach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1,			/* BA_MP_REACH_NLRI */
    bgp_check_reach_nlri, NULL },
  { "mp_unreach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1,			/* BA_MP_UNREACH_NLRI */
    bgp_check_unreach_nlri, NULL },
328 329
  { "ext_community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_EC_SET, 1,	/* BA_EXT_COMMUNITY */
    bgp_check_ext_community, NULL },
330
  { "as4_path", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,		/* BA_AS4_PATH */
331 332
    NULL, NULL },
  { "as4_aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,	/* BA_AS4_PATH */
333 334 335 336
    NULL, NULL },
  [BA_LARGE_COMMUNITY] =
  { "large_community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_LC_SET, 1,
    bgp_check_large_community, NULL }
337 338
};

339 340
/* BA_AS4_PATH is type EAF_TYPE_OPAQUE and not type EAF_TYPE_AS_PATH.
 * It does not matter as this attribute does not appear on routes in the routing table.
341 342
 */

343 344
#define ATTR_KNOWN(code) ((code) < ARRAY_SIZE(bgp_attr_table) && bgp_attr_table[code].name)

345 346 347 348 349 350 351 352 353 354
static inline struct adata *
bgp_alloc_adata(struct linpool *pool, unsigned len)
{
  struct adata *ad = lp_alloc(pool, sizeof(struct adata) + len);
  ad->length = len;
  return ad;
}

static void
bgp_set_attr(eattr *e, unsigned attr, uintptr_t val)
355 356 357 358 359 360
{
  ASSERT(ATTR_KNOWN(attr));
  e->id = EA_CODE(EAP_BGP, attr);
  e->type = bgp_attr_table[attr].type;
  e->flags = bgp_attr_table[attr].expected_flags;
  if (e->type & EAF_EMBEDDED)
361
    e->u.data = val;
362
  else
363
    e->u.ptr = (struct adata *) val;
364 365
}

366 367 368 369 370 371 372 373 374 375
static byte *
bgp_set_attr_wa(eattr *e, struct linpool *pool, unsigned attr, unsigned len)
{
  struct adata *ad = bgp_alloc_adata(pool, len);
  bgp_set_attr(e, attr, (uintptr_t) ad);
  return ad->data;
}

void
bgp_attach_attr(ea_list **to, struct linpool *pool, unsigned attr, uintptr_t val)
376 377 378 379 380 381
{
  ea_list *a = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
  a->next = *to;
  *to = a;
  a->flags = EALF_SORTED;
  a->count = 1;
382 383 384 385 386 387 388 389 390
  bgp_set_attr(a->attrs, attr, val);
}

byte *
bgp_attach_attr_wa(ea_list **to, struct linpool *pool, unsigned attr, unsigned len)
{
  struct adata *ad = bgp_alloc_adata(pool, len);
  bgp_attach_attr(to, pool, attr, (uintptr_t) ad);
  return ad->data;
391 392
}

393
static int
Pavel Tvrdík's avatar
Pavel Tvrdík committed
394
bgp_encode_attr_hdr(byte *dst, uint flags, unsigned code, int len)
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
{
  int wlen;

  DBG("\tAttribute %02x (%d bytes, flags %02x)\n", code, len, flags);

  if (len < 256)
    {
      *dst++ = flags;
      *dst++ = code;
      *dst++ = len;
      wlen = 3;
    }
  else
    {
      *dst++ = flags | BAF_EXT_LEN;
      *dst++ = code;
      put_u16(dst, len);
      wlen = 4;
    }

  return wlen;
}

static void
aggregator_convert_to_old(struct adata *aggr, byte *dst, int *new_used)
{
  byte *src = aggr->data;
  *new_used = 0;

  u32 as = get_u32(src);
  if (as > 0xFFFF) 
    {
      as = AS_TRANS;
      *new_used = 1;
    }
  put_u16(dst, as);

  /* Copy IPv4 address */
  memcpy(dst + 2, src + 4, 4);
}

static void
aggregator_convert_to_new(struct adata *aggr, byte *dst)
{
  byte *src = aggr->data;

  u32 as   = get_u16(src);
  put_u32(dst, as);

  /* Copy IPv4 address */
  memcpy(dst + 4, src + 2, 4);
}

static int
bgp_get_attr_len(eattr *a)
{
  int len;
  if (ATTR_KNOWN(EA_ID(a->id)))
    {
      int code = EA_ID(a->id);
      struct attr_desc *desc = &bgp_attr_table[code];
      len = desc->expected_length;
      if (len < 0)
	{
	  ASSERT(!(a->type & EAF_EMBEDDED));
	  len = a->u.ptr->length;
	}
    }
  else
    {
      ASSERT((a->type & EAF_TYPE_MASK) == EAF_TYPE_OPAQUE);
      len = a->u.ptr->length;
    }
  
  return len;
}

Martin Mareš's avatar
Martin Mareš committed
472 473
/**
 * bgp_encode_attrs - encode BGP attributes
474
 * @p: BGP instance
Martin Mareš's avatar
Martin Mareš committed
475 476 477 478 479 480 481
 * @w: buffer
 * @attrs: a list of extended attributes
 * @remains: remaining space in the buffer
 *
 * The bgp_encode_attrs() function takes a list of extended attributes
 * and converts it to its BGP representation (a part of an Update message).
 *
482
 * Result: Length of the attribute block generated or -1 if not enough space.
Martin Mareš's avatar
Martin Mareš committed
483
 */
Pavel Tvrdík's avatar
Pavel Tvrdík committed
484
uint
485
bgp_encode_attrs(struct bgp_proto *p, byte *w, ea_list *attrs, int remains)
486
{
Pavel Tvrdík's avatar
Pavel Tvrdík committed
487
  uint i, code, type, flags;
488
  byte *start = w;
489
  int len, rv;
490

491
  for(i=0; i<attrs->count; i++)
492
    {
493
      eattr *a = &attrs->attrs[i];
494 495
      ASSERT(EA_PROTO(a->id) == EAP_BGP);
      code = EA_ID(a->id);
496

497 498 499 500 501
#ifdef IPV6
      /* When talking multiprotocol BGP, the NEXT_HOP attributes are used only temporarily. */
      if (code == BA_NEXT_HOP)
	continue;
#endif
502 503 504 505 506

      /* When AS4-aware BGP speaker is talking to non-AS4-aware BGP speaker,
       * we have to convert our 4B AS_PATH to 2B AS_PATH and send our AS_PATH 
       * as optional AS4_PATH attribute.
       */
507
      if ((code == BA_AS_PATH) && (! p->as4_session))
508 509
	{
	  len = a->u.ptr->length;
510 511 512 513 514 515 516 517 518 519 520 521

	  if (remains < (len + 4))
	    goto err_no_buffer;

	  /* Using temporary buffer because don't know a length of created attr
	   * and therefore a length of a header. Perhaps i should better always
	   * use BAF_EXT_LEN. */
	  
	  byte buf[len];
	  int new_used;
	  int nl = as_path_convert_to_old(a->u.ptr, buf, &new_used);

Ondřej Zajíček's avatar
Ondřej Zajíček committed
522
	  DBG("BGP: Encoding old AS_PATH\n");
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
	  rv = bgp_encode_attr_hdr(w, BAF_TRANSITIVE, BA_AS_PATH, nl);
	  ADVANCE(w, remains, rv);
	  memcpy(w, buf, nl);
	  ADVANCE(w, remains, nl);

	  if (! new_used)
	    continue;

	  if (remains < (len + 4))
	    goto err_no_buffer;

	  /* We should discard AS_CONFED_SEQUENCE or AS_CONFED_SET path segments 
	   * here but we don't support confederations and such paths we already
	   * discarded in bgp_check_as_path().
	   */

Ondřej Zajíček's avatar
Ondřej Zajíček committed
539
	  DBG("BGP: Encoding AS4_PATH\n");
540 541 542 543 544 545
	  rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AS4_PATH, len);
	  ADVANCE(w, remains, rv);
	  memcpy(w, a->u.ptr->data, len);
	  ADVANCE(w, remains, len);

	  continue;
546
	}
547 548

      /* The same issue with AGGREGATOR attribute */
549
      if ((code == BA_AGGREGATOR) && (! p->as4_session))
550
	{
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	  int new_used;

	  len = 6;
	  if (remains < (len + 3))
	    goto err_no_buffer;

	  rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AGGREGATOR, len);
	  ADVANCE(w, remains, rv);
	  aggregator_convert_to_old(a->u.ptr, w, &new_used);
	  ADVANCE(w, remains, len);

	  if (! new_used)
	    continue;

	  len = 8;
	  if (remains < (len + 3))
	    goto err_no_buffer;

	  rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AS4_AGGREGATOR, len);
	  ADVANCE(w, remains, rv);
	  memcpy(w, a->u.ptr->data, len);
	  ADVANCE(w, remains, len);

	  continue;
575
	}
576 577 578

      /* Standard path continues here ... */

579
      type = a->type & EAF_TYPE_MASK;
580 581 582
      flags = a->flags & (BAF_OPTIONAL | BAF_TRANSITIVE | BAF_PARTIAL);
      len = bgp_get_attr_len(a);

583
      /* Skip empty sets */ 
584
      if (((type == EAF_TYPE_INT_SET) || (type == EAF_TYPE_EC_SET) || (type == EAF_TYPE_LC_SET)) && (len == 0))
585 586
	continue; 

587 588 589 590 591 592
      if (remains < len + 4)
	goto err_no_buffer;

      rv = bgp_encode_attr_hdr(w, flags, code, len);
      ADVANCE(w, remains, rv);

593
      switch (type)
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
	{
	case EAF_TYPE_INT:
	case EAF_TYPE_ROUTER_ID:
	  if (len == 4)
	    put_u32(w, a->u.data);
	  else
	    *w = a->u.data;
	  break;
	case EAF_TYPE_IP_ADDRESS:
	  {
	    ip_addr ip = *(ip_addr *)a->u.ptr->data;
	    ipa_hton(ip);
	    memcpy(w, &ip, len);
	    break;
	  }
609
	case EAF_TYPE_INT_SET:
610
	case EAF_TYPE_LC_SET:
611
	case EAF_TYPE_EC_SET:
612
	  {
613
	    u32 *z = int_set_get_data(a->u.ptr);
614 615 616 617 618
	    int i;
	    for(i=0; i<len; i+=4)
	      put_u32(w+i, *z++);
	    break;
	  }
619 620 621 622 623 624 625
	case EAF_TYPE_OPAQUE:
	case EAF_TYPE_AS_PATH:
	  memcpy(w, a->u.ptr->data, len);
	  break;
	default:
	  bug("bgp_encode_attrs: unknown attribute type %02x", a->type);
	}
626
      ADVANCE(w, remains, len);
627
    }
628
  return w - start;
629 630

 err_no_buffer:
631
  return -1;
632
}
633

634
/*
Martin Mareš's avatar
Martin Mareš committed
635 636 637 638
static void
bgp_init_prefix(struct fib_node *N)
{
  struct bgp_prefix *p = (struct bgp_prefix *) N;
639
  p->bucket_node.next = NULL;
Martin Mareš's avatar
Martin Mareš committed
640
}
641
*/
Martin Mareš's avatar
Martin Mareš committed
642

643 644 645 646 647 648
static int
bgp_compare_u32(const u32 *x, const u32 *y)
{
  return (*x < *y) ? -1 : (*x > *y) ? 1 : 0;
}

649 650
static inline void
bgp_normalize_int_set(u32 *dest, u32 *src, unsigned cnt)
651 652
{
  memcpy(dest, src, sizeof(u32) * cnt);
653
  qsort(dest, cnt, sizeof(u32), (int(*)(const void *, const void *)) bgp_compare_u32);
654 655
}

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
static int
bgp_compare_ec(const u32 *xp, const u32 *yp)
{
  u64 x = ec_get(xp, 0);
  u64 y = ec_get(yp, 0);
  return (x < y) ? -1 : (x > y) ? 1 : 0;
}

static inline void
bgp_normalize_ec_set(struct adata *ad, u32 *src, int internal)
{
  u32 *dst = int_set_get_data(ad);

  /* Remove non-transitive communities (EC_TBIT active) on external sessions */
  if (! internal)
    {
      int len = int_set_get_size(ad);
      u32 *t = dst;
      int i;

      for (i=0; i < len; i += 2)
	{
	  if (src[i] & EC_TBIT)
	    continue;
	  
	  *t++ = src[i];
	  *t++ = src[i+1];
	}

      ad->length = (t - dst) * 4;
    }
  else
    memcpy(dst, src, ad->length);

  qsort(dst, ad->length / 8, 8, (int(*)(const void *, const void *)) bgp_compare_ec);
}

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
static int
bgp_compare_lc(const u32 *x, const u32 *y)
{
  if (x[0] != y[0])
    return (x[0] > y[0]) ? 1 : -1;
  if (x[1] != y[1])
    return (x[1] > y[1]) ? 1 : -1;
  if (x[2] != y[2])
    return (x[2] > y[2]) ? 1 : -1;
  return 0;
}

static inline void
bgp_normalize_lc_set(u32 *dest, u32 *src, unsigned cnt)
{
  memcpy(dest, src, LCOMM_LENGTH * cnt);
  qsort(dest, cnt, LCOMM_LENGTH, (int(*)(const void *, const void *)) bgp_compare_lc);
}

712 713 714
static void
bgp_rehash_buckets(struct bgp_proto *p)
{
Martin Mareš's avatar
Martin Mareš committed
715
  struct bgp_bucket **old = p->bucket_hash;
716 717 718 719 720 721 722 723 724 725
  struct bgp_bucket **new;
  unsigned oldn = p->hash_size;
  unsigned i, e, mask;
  struct bgp_bucket *b;

  p->hash_size = p->hash_limit;
  DBG("BGP: Rehashing bucket table from %d to %d\n", oldn, p->hash_size);
  p->hash_limit *= 4;
  if (p->hash_limit >= 65536)
    p->hash_limit = ~0;
Martin Mareš's avatar
Martin Mareš committed
726
  new = p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
727 728 729 730
  mask = p->hash_size - 1;
  for (i=0; i<oldn; i++)
    while (b = old[i])
      {
Martin Mareš's avatar
Martin Mareš committed
731
	old[i] = b->hash_next;
732
	e = b->hash & mask;
Martin Mareš's avatar
Martin Mareš committed
733 734 735 736
	b->hash_next = new[e];
	if (b->hash_next)
	  b->hash_next->hash_prev = b;
	b->hash_prev = NULL;
737 738 739 740 741 742 743 744 745 746
	new[e] = b;
      }
  mb_free(old);
}

static struct bgp_bucket *
bgp_new_bucket(struct bgp_proto *p, ea_list *new, unsigned hash)
{
  struct bgp_bucket *b;
  unsigned ea_size = sizeof(ea_list) + new->count * sizeof(eattr);
Ondřej Filip's avatar
Ondřej Filip committed
747
  unsigned ea_size_aligned = BIRD_ALIGN(ea_size, CPU_STRUCT_ALIGN);
748
  unsigned size = sizeof(struct bgp_bucket) + ea_size_aligned;
749 750 751 752 753 754 755 756 757
  unsigned i;
  byte *dest;
  unsigned index = hash & (p->hash_size - 1);

  /* Gather total size of non-inline attributes */
  for (i=0; i<new->count; i++)
    {
      eattr *a = &new->attrs[i];
      if (!(a->type & EAF_EMBEDDED))
Ondřej Filip's avatar
Ondřej Filip committed
758
	size += BIRD_ALIGN(sizeof(struct adata) + a->u.ptr->length, CPU_STRUCT_ALIGN);
759 760 761 762
    }

  /* Create the bucket and hash it */
  b = mb_alloc(p->p.pool, size);
Martin Mareš's avatar
Martin Mareš committed
763 764 765 766 767
  b->hash_next = p->bucket_hash[index];
  if (b->hash_next)
    b->hash_next->hash_prev = b;
  p->bucket_hash[index] = b;
  b->hash_prev = NULL;
768
  b->hash = hash;
769 770
  add_tail(&p->bucket_queue, &b->send_node);
  init_list(&b->prefixes);
771 772 773 774 775 776
  memcpy(b->eattrs, new, ea_size);
  dest = ((byte *)b->eattrs) + ea_size_aligned;

  /* Copy values of non-inline attributes */
  for (i=0; i<new->count; i++)
    {
Martin Mareš's avatar
Martin Mareš committed
777
      eattr *a = &b->eattrs->attrs[i];
778 779 780 781 782 783
      if (!(a->type & EAF_EMBEDDED))
	{
	  struct adata *oa = a->u.ptr;
	  struct adata *na = (struct adata *) dest;
	  memcpy(na, oa, sizeof(struct adata) + oa->length);
	  a->u.ptr = na;
Ondřej Filip's avatar
Ondřej Filip committed
784
	  dest += BIRD_ALIGN(sizeof(struct adata) + na->length, CPU_STRUCT_ALIGN);
785 786 787 788 789 790 791 792 793 794 795 796
	}
    }

  /* If needed, rehash */
  p->hash_count++;
  if (p->hash_count > p->hash_limit)
    bgp_rehash_buckets(p);

  return b;
}

static struct bgp_bucket *
797
bgp_get_bucket(struct bgp_proto *p, net *n, ea_list *attrs, int originate)
798
{
Martin Mareš's avatar
Martin Mareš committed
799
  ea_list *new;
800
  unsigned i, cnt, hash, code;
801 802 803 804
  eattr *a, *d;
  u32 seen = 0;
  struct bgp_bucket *b;

805 806 807
  /* Merge the attribute list */
  new = alloca(ea_scan(attrs));
  ea_merge(attrs, new);
808
  ea_sort(new);
809 810 811 812 813 814 815 816 817 818

  /* Normalize attributes */
  d = new->attrs;
  cnt = new->count;
  new->count = 0;
  for(i=0; i<cnt; i++)
    {
      a = &new->attrs[i];
      if (EA_PROTO(a->id) != EAP_BGP)
	continue;
819
      code = EA_ID(a->id);
820
      if (ATTR_KNOWN(code))
821
	{
822 823 824 825 826 827 828
	  if (!p->is_internal)
	    {
	      if (!bgp_attr_table[code].allow_in_ebgp)
		continue;
	      if ((code == BA_LOCAL_PREF) && !p->cf->allow_local_pref)
		continue;
	    }
829 830
	  /* The flags might have been zero if the attr was added by filters */
	  a->flags = (a->flags & BAF_PARTIAL) | bgp_attr_table[code].expected_flags;
831 832 833 834 835 836 837 838
	  if (code < 32)
	    seen |= 1 << code;
	}
      else
	{
	  /* Don't re-export unknown non-transitive attributes */
	  if (!(a->flags & BAF_TRANSITIVE))
	    continue;
839
	}
840
      *d = *a;
841 842
      if ((d->type & EAF_ORIGINATED) && !originate && (d->flags & BAF_TRANSITIVE) && (d->flags & BAF_OPTIONAL))
	d->flags |= BAF_PARTIAL;
843 844
      switch (d->type & EAF_TYPE_MASK)
	{
845
	case EAF_TYPE_INT_SET:
846 847 848
	  {
	    struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
	    z->length = d->u.ptr->length;
849 850 851 852 853 854 855 856 857
	    bgp_normalize_int_set((u32 *) z->data, (u32 *) d->u.ptr->data, z->length / 4);
	    d->u.ptr = z;
	    break;
	  }
	case EAF_TYPE_EC_SET:
	  {
	    struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
	    z->length = d->u.ptr->length;
	    bgp_normalize_ec_set(z, (u32 *) d->u.ptr->data, p->is_internal);
858 859 860
	    d->u.ptr = z;
	    break;
	  }
861 862 863 864 865 866 867 868
	case EAF_TYPE_LC_SET:
	  {
	    struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
	    z->length = d->u.ptr->length;
	    bgp_normalize_lc_set((u32 *) z->data, (u32 *) d->u.ptr->data, z->length / LCOMM_LENGTH);
	    d->u.ptr = z;
	    break;
	  }
869
	default: ;
870 871 872 873 874 875 876
	}
      d++;
      new->count++;
    }

  /* Hash */
  hash = ea_hash(new);
Martin Mareš's avatar
Martin Mareš committed
877
  for(b=p->bucket_hash[hash & (p->hash_size - 1)]; b; b=b->hash_next)
878 879 880 881 882 883 884
    if (b->hash == hash && ea_same(b->eattrs, new))
      {
	DBG("Found bucket.\n");
	return b;
      }

  /* Ensure that there are all mandatory attributes */
885
  for(i=0; i<ARRAY_SIZE(bgp_mandatory_attrs); i++)
886 887
    if (!(seen & (1 << bgp_mandatory_attrs[i])))
      {
888
	log(L_ERR "%s: Mandatory attribute %s missing in route %I/%d", p->p.name, bgp_attr_table[bgp_mandatory_attrs[i]].name, n->n.prefix, n->n.pxlen);
889 890 891
	return NULL;
      }

892 893
  /* Check if next hop is valid */
  a = ea_find(new, EA_CODE(EAP_BGP, BA_NEXT_HOP));
894
  if (!a || ipa_equal(p->cf->remote_ip, *(ip_addr *)a->u.ptr->data))
895 896 897 898
    {
      log(L_ERR "%s: Invalid NEXT_HOP attribute in route %I/%d", p->p.name, n->n.prefix, n->n.pxlen);
      return NULL;
    }
899

900 901 902 903 904
  /* Create new bucket */
  DBG("Creating bucket.\n");
  return bgp_new_bucket(p, new, hash);
}

905 906 907 908 909 910 911 912 913 914 915 916
void
bgp_free_bucket(struct bgp_proto *p, struct bgp_bucket *buck)
{
  if (buck->hash_next)
    buck->hash_next->hash_prev = buck->hash_prev;
  if (buck->hash_prev)
    buck->hash_prev->hash_next = buck->hash_next;
  else
    p->bucket_hash[buck->hash & (p->hash_size-1)] = buck->hash_next;
  mb_free(buck);
}

917 918 919

/* Prefix hash table */

Ondřej Zajíček's avatar
Ondřej Zajíček committed
920 921 922 923 924 925 926 927
#define PXH_KEY(n1)		n1->n.prefix, n1->n.pxlen, n1->path_id
#define PXH_NEXT(n)		n->next
#define PXH_EQ(p1,l1,i1,p2,l2,i2) ipa_equal(p1, p2) && l1 == l2 && i1 == i2
#define PXH_FN(p,l,i)		ipa_hash32(p) ^ u32_hash((l << 16) ^ i)

#define PXH_REHASH		bgp_pxh_rehash
#define PXH_PARAMS		/8, *2, 2, 2, 8, 20

928

Ondřej Zajíček's avatar
Ondřej Zajíček committed
929
HASH_DEFINE_REHASH_FN(PXH, struct bgp_prefix)
930 931 932 933

void
bgp_init_prefix_table(struct bgp_proto *p, u32 order)
{
Ondřej Zajíček's avatar
Ondřej Zajíček committed
934
  HASH_INIT(p->prefix_hash, p->p.pool, order);
935

Ondřej Zajíček's avatar
Ondřej Zajíček committed
936
  p->prefix_slab = sl_new(p->p.pool, sizeof(struct bgp_prefix));
937 938
}

939 940 941 942 943 944 945 946 947
void
bgp_free_prefix_table(struct bgp_proto *p)
{
  HASH_FREE(p->prefix_hash);

  rfree(p->prefix_slab);
  p->prefix_slab = NULL;
}

948 949 950
static struct bgp_prefix *
bgp_get_prefix(struct bgp_proto *p, ip_addr prefix, int pxlen, u32 path_id)
{
Ondřej Zajíček's avatar
Ondřej Zajíček committed
951
  struct bgp_prefix *bp = HASH_FIND(p->prefix_hash, PXH, prefix, pxlen, path_id);
952

Ondřej Zajíček's avatar
Ondřej Zajíček committed
953 954
  if (bp)
    return bp;
955 956 957 958 959 960 961

  bp = sl_alloc(p->prefix_slab);
  bp->n.prefix = prefix;
  bp->n.pxlen = pxlen;
  bp->path_id = path_id;
  bp->bucket_node.next = NULL;

Ondřej Zajíček's avatar
Ondřej Zajíček committed
962
  HASH_INSERT2(p->prefix_hash, PXH, p->p.pool, bp);
963 964 965 966 967 968 969

  return bp;
}

void
bgp_free_prefix(struct bgp_proto *p, struct bgp_prefix *bp)
{
Ondřej Zajíček's avatar
Ondřej Zajíček committed
970
  HASH_REMOVE2(p->prefix_hash, PXH, p->p.pool, bp);
971 972 973 974
  sl_free(p->prefix_slab, bp);
}


Martin Mareš's avatar
Martin Mareš committed
975
void
976
bgp_rt_notify(struct proto *P, rtable *tbl UNUSED, net *n, rte *new, rte *old UNUSED, ea_list *attrs)
Martin Mareš's avatar
Martin Mareš committed
977
{
978
  struct bgp_proto *p = (struct bgp_proto *) P;
979 980
  struct bgp_bucket *buck;
  struct bgp_prefix *px;
981 982
  rte *key;
  u32 path_id;
983

984
  DBG("BGP: Got route %I/%d %s\n", n->n.prefix, n->n.pxlen, new ? "up" : "down");
985 986 987

  if (new)
    {
988
      key = new;
989
      buck = bgp_get_bucket(p, n, attrs, new->attrs->source != RTS_BGP);
990 991 992
      if (!buck)			/* Inconsistent attribute list */
	return;
    }
993 994
  else
    {
995
      key = old;
996 997 998 999 1000 1001
      if (!(buck = p->withdraw_bucket))
	{
	  buck = p->withdraw_bucket = mb_alloc(P->pool, sizeof(struct bgp_bucket));
	  init_list(&buck->prefixes);
	}
    }
1002 1003
  path_id = p->add_path_tx ? key->attrs->src->global_id : 0;
  px = bgp_get_prefix(p, n->n.prefix, n->n.pxlen, path_id);
1004 1005 1006 1007 1008 1009 1010
  if (px->bucket_node.next)
    {
      DBG("\tRemoving old entry.\n");
      rem_node(&px->bucket_node);
    }
  add_tail(&buck->prefixes, &px->bucket_node);
  bgp_schedule_packet(p->conn, PKT_UPDATE);
Martin Mareš's avatar
Martin Mareš committed
1011 1012
}

1013 1014
static int
bgp_create_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool)
Martin Mareš's avatar
Martin Mareš committed
1015
{
1016
  ea_list *ea = lp_alloc(pool, sizeof(ea_list) + 4*sizeof(eattr));
Martin Mareš's avatar
Martin Mareš committed
1017
  rta *rta = e->attrs;
1018
  byte *z;
Martin Mareš's avatar
Martin Mareš committed
1019

1020 1021
  ea->next = *attrs;
  *attrs = ea;
Martin Mareš's avatar
Martin Mareš committed
1022
  ea->flags = EALF_SORTED;
1023
  ea->count = 4;
Martin Mareš's avatar
Martin Mareš committed
1024

1025
  bgp_set_attr(ea->attrs, BA_ORIGIN,
Ondřej Filip's avatar
Ondřej Filip committed
1026
       ((rta->source == RTS_OSPF_EXT1) || (rta->source == RTS_OSPF_EXT2)) ? ORIGIN_INCOMPLETE : ORIGIN_IGP);
Martin Mareš's avatar
Martin Mareš committed
1027 1028

  if (p->is_internal)
1029
    bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 0);
Martin Mareš's avatar
Martin Mareš committed
1030 1031
  else
    {
1032
      z = bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 6);
1033
      z[0] = AS_PATH_SEQUENCE;
Martin Mareš's avatar
Martin Mareš committed
1034
      z[1] = 1;				/* 1 AS */
1035
      put_u32(z+2, p->local_as);
Martin Mareš's avatar
Martin Mareš committed
1036 1037
    }

1038 1039
  /* iBGP -> use gw, eBGP multi-hop -> use source_addr,
     eBGP single-hop -> use gw if on the same iface */
1040
  z = bgp_set_attr_wa(ea->attrs+2, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
1041
  if (p->cf->next_hop_self ||
1042
      rta->dest != RTD_ROUTER ||
1043
      ipa_equal(rta->gw, IPA_NONE) ||
1044
      ipa_is_link_local(rta->gw) ||
1045 1046
      (!p->is_internal && !p->cf->next_hop_keep &&
       (!p->neigh || (rta->iface != p->neigh->iface))))
1047
    set_next_hop(z, p->source_addr);
Martin Mareš's avatar
Martin Mareš committed
1048
  else
1049
    set_next_hop(z, rta->gw);
1050

1051
  bgp_set_attr(ea->attrs+3, BA_LOCAL_PREF, p->cf->default_local_pref);
Martin Mareš's avatar
Martin Mareš committed
1052

1053
  return 0;				/* Leave decision to the filters */
Martin Mareš's avatar
Martin Mareš committed
1054 1055
}

1056 1057 1058 1059

static inline int
bgp_as_path_loopy(struct bgp_proto *p, rta *a)
{
1060
  int num = p->cf->allow_local_as + 1;
1061
  eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1062
  return (e && (num > 0) && as_path_contains(e->u.ptr, p->local_as, num));
1063 1064 1065 1066
}

static inline int
bgp_originator_id_loopy(struct bgp_proto *p, rta *a)
1067
{
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
  return (e && (e->u.data == p->local_id));
}

static inline int
bgp_cluster_list_loopy(struct bgp_proto *p, rta *a)
{
  eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
  return (e && p->rr_client && int_set_contains(e->u.ptr, p->rr_cluster_id));
}


static inline void
bgp_path_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 as)
{
  eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
  bgp_attach_attr(attrs, pool, BA_AS_PATH, (uintptr_t) as_path_prepend(pool, a->u.ptr, as));
}

static inline void
bgp_cluster_list_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 cid)
{
  eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
1091
  bgp_attach_attr(attrs, pool, BA_CLUSTER_LIST, (uintptr_t) int_set_prepend(pool, a ? a->u.ptr : NULL, cid));
Martin Mareš's avatar
Martin Mareš committed
1092 1093
}

1094
static int
1095
bgp_update_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool, int rr)
Martin Mareš's avatar
Martin Mareš committed
1096
{
1097 1098
  eattr *a;

1099
  if (!p->is_internal && !p->rs_client)
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    {
      bgp_path_prepend(e, attrs, pool, p->local_as);

      /* The MULTI_EXIT_DISC attribute received from a neighboring AS MUST NOT be
       * propagated to other neighboring ASes.
       * Perhaps it would be better to undefine it.
       */
      a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
      if (a)
	bgp_attach_attr(attrs, pool, BA_MULTI_EXIT_DISC, 0);
    }
Martin Mareš's avatar
Martin Mareš committed
1111

1112
  /* iBGP -> keep next_hop, eBGP multi-hop -> use source_addr,
1113 1114
   * eBGP single-hop -> keep next_hop if on the same iface.
   * If the next_hop is zero (i.e. link-local), keep only if on the same iface.
1115 1116
   *
   * Note that same-iface-check uses iface from route, which is based on gw.
1117
   */
1118
  a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
1119
  if (a && !p->cf->next_hop_self && 
1120 1121
      (p->cf->next_hop_keep ||
       (p->is_internal && ipa_nonzero(*((ip_addr *) a->u.ptr->data))) ||
1122
       (p->neigh && (e->attrs->iface == p->neigh->iface))))
1123 1124 1125 1126 1127 1128
    {
      /* Leave the original next hop attribute, will check later where does it point */
    }
  else
    {
      /* Need to create new one */
1129 1130
      byte *b = bgp_attach_attr_wa(attrs, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
      set_next_hop(b, p->source_addr);
1131 1132 1133 1134 1135
    }

  if (rr)
    {
      /* Handling route reflection, RFC 4456 */
1136
      struct bgp_proto *src = (struct bgp_proto *) e->attrs->src->proto;
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

      a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
      if (!a)
	bgp_attach_attr(attrs, pool, BA_ORIGINATOR_ID, src->remote_id);

      /* We attach proper cluster ID according to whether the route is entering or leaving the cluster */
      bgp_cluster_list_prepend(e, attrs, pool, src->rr_client ? src->rr_cluster_id : p->rr_cluster_id);

      /* Two RR clients with different cluster ID, hmmm */
      if (src->rr_client && p->rr_client && (src->rr_cluster_id != p->rr_cluster_id))
	bgp_cluster_list_prepend(e, attrs, pool, p->rr_cluster_id);
1148
    }
Martin Mareš's avatar
Martin Mareš committed
1149

1150
  return 0;				/* Leave decision to the filters */
Martin Mareš's avatar
Martin Mareš committed
1151 1152
}

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
static int
bgp_community_filter(struct bgp_proto *p, rte *e)
{
  eattr *a;
  struct adata *d;

  /* Check if we aren't forbidden to export the route by communities */
  a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_COMMUNITY));
  if (a)
    {
      d = a->u.ptr;
      if (int_set_contains(d, BGP_COMM_NO_ADVERTISE))
	{
	  DBG("\tNO_ADVERTISE\n");
	  return 1;
	}
      if (!p->is_internal &&
	  (int_set_contains(d, BGP_COMM_NO_EXPORT) ||
	   int_set_contains(d, BGP_COMM_NO_EXPORT_SUBCONFED)))
	{
	  DBG("\tNO_EXPORT\n");
	  return 1;
	}
1176 1177 1178

      if (!p->conn->peer_llgr_aware && int_set_contains(d, BGP_COMM_LLGR_STALE))
	return 1;
1179 1180 1181 1182 1183
    }

  return 0;
}

Martin Mareš's avatar
Martin Mareš committed
1184 1185 1186 1187 1188
int
bgp_import_control(struct proto *P, rte **new, ea_list **attrs, struct linpool *pool)
{
  rte *e = *new;
  struct bgp_proto *p = (struct bgp_proto *) P;
1189 1190
  struct bgp_proto *new_bgp = (e->attrs->src->proto->proto == &proto_bgp) ?
    (struct bgp_proto *) e->attrs->src->proto : NULL;
Martin Mareš's avatar
Martin Mareš committed
1191

1192
  if (p == new_bgp)			/* Poison reverse updates */
Martin Mareš's avatar
Martin Mareš committed
1193 1194 1195
    return -1;
  if (new_bgp)
    {
1196 1197 1198 1199 1200
      /* We should check here for cluster list loop, because the receiving BGP instance
	 might have different cluster ID  */
      if (bgp_cluster_list_loopy(p, e->attrs))
	return -1;

1201
      if (p->cf->interpret_communities && bgp_community_filter(p, e))
1202 1203
	return -1;

Martin Mareš's avatar
Martin Mareš committed
1204
      if (p->local_as == new_bgp->local_as && p->is_internal && new_bgp->is_internal)
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
	{
	  /* Redistribution of internal routes with IBGP */
	  if (p->rr_client || new_bgp->rr_client)
	    /* Route reflection, RFC 4456 */
	    return bgp_update_attrs(p, e, attrs, pool, 1);
	  else
	    return -1;
	}
      else
	return bgp_update_attrs(p, e, attrs, pool, 0);
Martin Mareš's avatar
Martin Mareš committed
1215 1216
    }
  else
1217
    return bgp_create_attrs(p, e, attrs, pool);
Martin Mareš's avatar
Martin Mareš committed
1218 1219
}

1220 1221 1222 1223 1224 1225
static inline u32
bgp_get_neighbor(rte *r)
{
  eattr *e = ea_find(r->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
  u32 as;

1226
  if (e && as_path_get_first(e->u.ptr, &as))
1227 1228
    return as;
  else
1229
    return ((struct bgp_proto *) r->attrs->src->proto)->remote_as;
1230 1231
}

1232 1233 1234 1235 1236 1237 1238
static inline int
rte_resolvable(rte *rt)
{
  int rd = rt->attrs->dest;  
  return (rd == RTD_ROUTER) || (rd == RTD_DEVICE) || (rd == RTD_MULTIPATH);
}

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
static inline int
rte_stale(rte *r)
{
  if (r->u.bgp.stale < 0)
  {
    /* If staleness is unknown, compute and cache it */
    eattr *a = ea_find(r->attrs->eattrs, EA_CODE(EAP_BGP, BA_COMMUNITY));
    r->u.bgp.stale = a && int_set_contains(a->u.ptr, BGP_COMM_LLGR_STALE);
  }

  return r->u.bgp.stale;
}

Martin Mareš's avatar
Martin Mareš committed
1252 1253 1254
int
bgp_rte_better(rte *new, rte *old)
{
1255 1256
  struct bgp_proto *new_bgp = (struct bgp_proto *) new->attrs->src->proto;
  struct bgp_proto *old_bgp = (struct bgp_proto *) old->attrs->src->proto;
1257 1258
  eattr *x, *y;
  u32 n, o;
Martin Mareš's avatar
Martin Mareš committed
1259

1260 1261 1262 1263 1264 1265 1266 1267
  /* Skip suppressed routes (see bgp_rte_recalculate()) */
  n = new->u.bgp.suppressed;
  o = old->u.bgp.suppressed;
  if (n > o)
    return 0;
  if (n < o)
    return 1;

1268
  /* RFC 4271 9.1.2.1. Route resolvability test */
1269 1270
  n = rte_resolvable(new);
  o = rte_resolvable(old);
1271 1272 1273 1274 1275
  if (n > o)
    return 1;
  if (n < o)
    return 0;

1276 1277 1278 1279 1280 1281 1282 1283
  /* LLGR draft - depreference stale routes */
  n = rte_stale(new);
  o = rte_stale(old);
  if (n > o)
    return 0;
  if (n < o)
    return 1;

Martin Mareš's avatar
Martin Mareš committed
1284
  /* Start with local preferences */
1285 1286 1287 1288 1289 1290 1291 1292 1293
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
  n = x ? x->u.data : new_bgp->cf->default_local_pref;
  o = y ? y->u.data : old_bgp->cf->default_local_pref;
  if (n > o)
    return 1;
  if (n < o)
    return 0;

1294
  /* RFC 4271 9.1.2.2. a)  Use AS path lengths */
1295
  if (new_bgp->cf->compare_path_lengths || old_bgp->cf->compare_path_lengths)
Martin Mareš's avatar
Martin Mareš committed
1296
    {
1297 1298
      x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
      y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1299 1300
      n = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
      o = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
1301
      if (n < o)
Martin Mareš's avatar
Martin Mareš committed
1302
	return 1;
1303
      if (n > o)
Martin Mareš's avatar
Martin Mareš committed
1304 1305 1306
	return 0;
    }

1307
  /* RFC 4271 9.1.2.2. b) Use origins */
1308 1309
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1310 1311
  n = x ? x->u.data : ORIGIN_INCOMPLETE;
  o = y ? y->u.data : ORIGIN_INCOMPLETE;
1312 1313 1314 1315 1316
  if (n < o)
    return 1;
  if (n > o)
    return 0;

1317
  /* RFC 4271 9.1.2.2. c) Compare MED's */
1318 1319 1320 1321 1322 1323 1324 1325 1326
  /* Proper RFC 4271 path selection cannot be interpreted as finding
   * the best path in some ordering. It is implemented partially in
   * bgp_rte_recalculate() when deterministic_med option is
   * active. Without that option, the behavior is just an
   * approximation, which in specific situations may lead to
   * persistent routing loops, because it is nondeterministic - it
   * depends on the order in which routes appeared. But it is also the
   * same behavior as used by default in Cisco routers, so it is
   * probably not a big issue.
1327 1328 1329
   */
  if (new_bgp->cf->med_metric || old_bgp->cf->med_metric ||
      (bgp_get_neighbor(new) == bgp_get_neighbor(old)))
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    {
      x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
      y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
      n = x ? x->u.data : new_bgp->cf->default_med;
      o = y ? y->u.data : old_bgp->cf->default_med;
      if (n < o)
	return 1;
      if (n > o)
	return 0;
    }
1340

1341
  /* RFC 4271 9.1.2.2. d) Prefer external peers */
Martin Mareš's avatar
Martin Mareš committed
1342 1343 1344 1345 1346
  if (new_bgp->is_internal > old_bgp->is_internal)
    return 0;
  if (new_bgp->is_internal < old_bgp->is_internal)
    return 1;

1347 1348 1349 1350 1351 1352 1353
  /* RFC 4271 9.1.2.2. e) Compare IGP metrics */
  n = new_bgp->cf->igp_metric ? new->attrs->igp_metric : 0;
  o = old_bgp->cf->igp_metric ? old->attrs->igp_metric : 0;
  if (n < o)
    return 1;
  if (n > o)
    return 0;
1354 1355 1356 1357 1358 1359 1360

  /* RFC 4271 9.1.2.2. f) Compare BGP identifiers */
  /* RFC 4456 9. a) Use ORIGINATOR_ID instead of local neighor ID */
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
  n = x ? x->u.data : new_bgp->remote_id;
  o = y ? y->u.data : old_bgp->remote_id;
1361 1362 1363 1364 1365 1366 1367 1368

  /* RFC 5004 - prefer older routes */
  /* (if both are external and from different peer) */
  if ((new_bgp->cf->prefer_older || old_bgp->cf->prefer_older) &&
      !new_bgp->is_internal && n != o)
    return 0;

  /* rest of RFC 4271 9.1.2.2. f) */
1369 1370 1371 1372
  if (n < o)
    return 1;
  if (n > o)
    return 0;
1373

1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
  /* RFC 4456 9. b) Compare cluster list lengths */
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
  n = x ? int_set_get_size(x->u.ptr) : 0;
  o = y ? int_set_get_size(y->u.ptr) : 0;
  if (n < o)
    return 1;
  if (n > o)
    return 0;

1384 1385 1386 1387
  /* RFC 4271 9.1.2.2. g) Compare peer IP adresses */
  return (ipa_compare(new_bgp->cf->remote_ip, old_bgp->cf->remote_ip) < 0);
}

1388

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
int
bgp_rte_mergable(rte *pri, rte *sec)
{
  struct bgp_proto *pri_bgp = (struct bgp_proto *) pri->attrs->src->proto;
  struct bgp_proto *sec_bgp = (struct bgp_proto *) sec->attrs->src->proto;
  eattr *x, *y;
  u32 p, s;

  /* Skip suppressed routes (see bgp_rte_recalculate()) */
  if (pri->u.bgp.suppressed != sec->u.bgp.suppressed)
    return 0;

  /* RFC 4271 9.1.2.1. Route resolvability test */
  if (!rte_resolvable(sec))
    return 0;

1405 1406 1407 1408
  /* LLGR draft - depreference stale routes */
  if (rte_stale(pri) != rte_stale(sec))
    return 0;

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
  /* Start with local preferences */
  x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
  y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
  p = x ? x->u.data : pri_bgp->cf->default_local_pref;
  s = y ? y->u.data : sec_bgp->cf->default_local_pref;
  if (p != s)
    return 0;

  /* RFC 4271 9.1.2.2. a)  Use AS path lengths */
  if (pri_bgp->cf->compare_path_lengths || sec_bgp->cf->compare_path_lengths)
    {
      x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
      y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
      p = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
      s = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;

      if (p != s)
	return 0;

//      if (DELTA(p, s) > pri_bgp->cf->relax_multipath)
//	return 0;
    }

  /* RFC 4271 9.1.2.2. b) Use origins */
  x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
  y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
  p = x ? x->u.data : ORIGIN_INCOMPLETE;
  s = y ? y->u.data : ORIGIN_INCOMPLETE;
  if (p != s)
    return 0;

  /* RFC 4271 9.1.2.2. c) Compare MED's */
  if (pri_bgp->cf->med_metric || sec_bgp->cf->med_metric ||
      (bgp_get_neighbor(pri) == bgp_get_neighbor(sec)))
    {
      x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
      y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
      p = x ? x->u.data : pri_bgp->cf->default_med;
      s = y ? y->u.data : sec_bgp->cf->default_med;
      if (p != s)
	return 0;
    }

  /* RFC 4271 9.1.2.2. d) Prefer external peers */
  if (pri_bgp->is_internal != sec_bgp->is_internal)
    return 0;

  /* RFC 4271 9.1.2.2. e) Compare IGP metrics */
  p = pri_bgp->cf->igp_metric ? pri->attrs->igp_metric : 0;
  s = sec_bgp->cf->igp_metric ? sec->attrs->igp_metric : 0;
  if (p != s)
    return 0;

  /* Remaining criteria are ignored */

  return 1;
}



1469 1470 1471 1472 1473 1474 1475 1476 1477
static inline int
same_group(rte *r, u32 lpref, u32 lasn)
{
  return (r->pref == lpref) && (bgp_get_neighbor(r) == lasn);
}

static inline int
use_deterministic_med(rte *r)
{
1478
  struct proto *P = r->attrs->src->proto;
1479
  return (P->proto == &proto_bgp) && ((struct bgp_proto *) P)->cf->deterministic_med;
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
}

int
bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best)
{
  rte *r, *s;
  rte *key = new ? new : old;
  u32 lpref = key->pref;
  u32 lasn = bgp_get_neighbor(key);
  int old_is_group_best = 0;

  /*
   * Proper RFC 4271 path selection is a bit complicated, it cannot be
   * implemented just by rte_better(), because it is not a linear
   * ordering. But it can be splitted to two levels, where the lower
   * level chooses the best routes in each group of routes from the
   * same neighboring AS and higher level chooses the best route (with
   * a slightly different ordering) between the best-in-group routes.
   *
   * When deterministic_med is disabled, we just ignore this issue and
   * choose the best route by bgp_rte_better() alone. If enabled, the
   * lower level of the route selection is done here (for the group
   * to which the changed route belongs), all routes in group are
   * marked as suppressed, just chosen best-in-group is not.
   *
   * Global best route selection then implements higher level by
   * choosing between non-suppressed routes (as they are always
   * preferred over suppressed routes). Routes from BGP protocols
   * that do not set deterministic_med are just never suppressed. As
   * they do not participate in the lower level selection, it is OK
   * that this fn is not called for them.
   *
   * The idea is simple, the implementation is more problematic,
   * mostly because of optimizations in rte_recalculate() that 
   * avoids full recalculation in most cases.
   *
   * We can assume that at least one of new, old is non-NULL and both
   * are from the same protocol with enabled deterministic_med. We
   * group routes by both neighbor AS (lasn) and preference (lpref),
   * because bgp_rte_better() does not handle preference itself.
   */

  /* If new and old are from different groups, we just process that
     as two independent events */
  if (new && old && !same_group(old, <