packets.c 43.8 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 *	BIRD -- BGP Packet Processing
 *
 *	(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 13 14
#include "nest/bird.h"
#include "nest/iface.h"
#include "nest/protocol.h"
#include "nest/route.h"
15
#include "nest/attrs.h"
16
#include "nest/mrtdump.h"
17
#include "conf/conf.h"
18 19
#include "lib/unaligned.h"
#include "lib/socket.h"
20

Ondřej Zajíček's avatar
Ondřej Zajíček committed
21 22
#include "nest/cli.h"

23
#include "bgp.h"
24

25 26 27 28 29 30

#define BGP_RR_REQUEST		0
#define BGP_RR_BEGIN		1
#define BGP_RR_END		2


31 32
static struct tbf rl_rcv_update = TBF_DEFAULT_LOG_LIMITS;
static struct tbf rl_snd_update = TBF_DEFAULT_LOG_LIMITS;
33

34 35 36 37 38 39 40
/* Table for state -> RFC 6608 FSM error subcodes */
static byte fsm_err_subcode[BS_MAX] = {
  [BS_OPENSENT] = 1,
  [BS_OPENCONFIRM] = 2,
  [BS_ESTABLISHED] = 3
};

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
/*
 * MRT Dump format is not semantically specified.
 * We will use these values in appropriate fields:
 *
 * Local AS, Remote AS - configured AS numbers for given BGP instance.
 * Local IP, Remote IP - IP addresses of the TCP connection (0 if no connection)
 *
 * We dump two kinds of MRT messages: STATE_CHANGE (for BGP state
 * changes) and MESSAGE (for received BGP messages).
 *
 * STATE_CHANGE uses always AS4 variant, but MESSAGE uses AS4 variant
 * only when AS4 session is established and even in that case MESSAGE
 * does not use AS4 variant for initial OPEN message. This strange
 * behavior is here for compatibility with Quagga and Bgpdump,
 */

static byte *
mrt_put_bgp4_hdr(byte *buf, struct bgp_conn *conn, int as4)
{
  struct bgp_proto *p = conn->bgp;

  if (as4)
    {
      put_u32(buf+0, p->remote_as);
      put_u32(buf+4, p->local_as);
      buf+=8;
    }
  else
    {
      put_u16(buf+0, (p->remote_as <= 0xFFFF) ? p->remote_as : AS_TRANS);
      put_u16(buf+2, (p->local_as <= 0xFFFF)  ? p->local_as  : AS_TRANS);
      buf+=4;
    }

75
  put_u16(buf+0, (p->neigh && p->neigh->iface) ? p->neigh->iface->index : 0);
76 77
  put_u16(buf+2, BGP_AF);
  buf+=4;
78 79
  buf = put_ipa(buf, conn->sk ? conn->sk->daddr : IPA_NONE);
  buf = put_ipa(buf, conn->sk ? conn->sk->saddr : IPA_NONE);
80 81 82 83 84 85 86

  return buf;
}

static void
mrt_dump_bgp_packet(struct bgp_conn *conn, byte *pkt, unsigned len)
{
87
  byte *buf = alloca(128+len);	/* 128 is enough for MRT headers */
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  byte *bp = buf + MRTDUMP_HDR_LENGTH;
  int as4 = conn->bgp->as4_session;

  bp = mrt_put_bgp4_hdr(bp, conn, as4);
  memcpy(bp, pkt, len);
  bp += len;
  mrt_dump_message(&conn->bgp->p, BGP4MP, as4 ? BGP4MP_MESSAGE_AS4 : BGP4MP_MESSAGE,
		   buf, bp-buf);
}

static inline u16
convert_state(unsigned state)
{
  /* Convert state from our BS_* values to values used in MRTDump */
  return (state == BS_CLOSE) ? 1 : state + 1;
}

void
mrt_dump_bgp_state_change(struct bgp_conn *conn, unsigned old, unsigned new)
{
  byte buf[128];
  byte *bp = buf + MRTDUMP_HDR_LENGTH;

  bp = mrt_put_bgp4_hdr(bp, conn, 1);
  put_u16(bp+0, convert_state(old));
  put_u16(bp+2, convert_state(new));
  bp += 4;
  mrt_dump_message(&conn->bgp->p, BGP4MP, BGP4MP_STATE_CHANGE_AS4, buf, bp-buf);
}

118 119 120
static byte *
bgp_create_notification(struct bgp_conn *conn, byte *buf)
{
Martin Mareš's avatar
Martin Mareš committed
121 122 123
  struct bgp_proto *p = conn->bgp;

  BGP_TRACE(D_PACKETS, "Sending NOTIFICATION(code=%d.%d)", conn->notify_code, conn->notify_subcode);
124 125
  buf[0] = conn->notify_code;
  buf[1] = conn->notify_subcode;
126 127
  memcpy(buf+2, conn->notify_data, conn->notify_size);
  return buf + 2 + conn->notify_size;
128 129
}

130 131
#ifdef IPV6
static byte *
132
bgp_put_cap_ipv6(struct bgp_proto *p UNUSED, byte *buf)
133 134 135 136 137 138 139 140 141
{
  *buf++ = 1;		/* Capability 1: Multiprotocol extensions */
  *buf++ = 4;		/* Capability data length */
  *buf++ = 0;		/* We support AF IPv6 */
  *buf++ = BGP_AF_IPV6;
  *buf++ = 0;		/* RFU */
  *buf++ = 1;		/* and SAFI 1 */
  return buf;
}
142 143 144 145

#else

static byte *
146
bgp_put_cap_ipv4(struct bgp_proto *p UNUSED, byte *buf)
147 148 149 150 151 152 153 154 155
{
  *buf++ = 1;		/* Capability 1: Multiprotocol extensions */
  *buf++ = 4;		/* Capability data length */
  *buf++ = 0;		/* We support AF IPv4 */
  *buf++ = BGP_AF_IPV4;
  *buf++ = 0;		/* RFU */
  *buf++ = 1;		/* and SAFI 1 */
  return buf;
}
156 157
#endif

158
static byte *
159
bgp_put_cap_rr(struct bgp_proto *p UNUSED, byte *buf)
160 161 162 163 164 165
{
  *buf++ = 2;		/* Capability 2: Support for route refresh */
  *buf++ = 0;		/* Capability data length */
  return buf;
}

166 167 168 169 170 171 172 173
static byte *
bgp_put_cap_ext_msg(struct bgp_proto *p UNUSED, byte *buf)
{
  *buf++ = 6;		/* Capability 6: Support for extended messages */
  *buf++ = 0;		/* Capability data length */
  return buf;
}

174
static byte *
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
bgp_put_cap_gr1(struct bgp_proto *p, byte *buf)
{
  *buf++ = 64;		/* Capability 64: Support for graceful restart */
  *buf++ = 6;		/* Capability data length */

  put_u16(buf, p->cf->gr_time);
  if (p->p.gr_recovery)
    buf[0] |= BGP_GRF_RESTART;
  buf += 2;

  *buf++ = 0;		/* Appropriate AF */
  *buf++ = BGP_AF;
  *buf++ = 1;		/* and SAFI 1 */
  *buf++ = p->p.gr_recovery ? BGP_GRF_FORWARDING : 0;

  return buf;
}

static byte *
194
bgp_put_cap_gr2(struct bgp_proto *p UNUSED, byte *buf)
195 196 197 198 199 200 201 202 203
{
  *buf++ = 64;		/* Capability 64: Support for graceful restart */
  *buf++ = 2;		/* Capability data length */
  put_u16(buf, 0);
  return buf + 2;
}

static byte *
bgp_put_cap_as4(struct bgp_proto *p, byte *buf)
204 205 206
{
  *buf++ = 65;		/* Capability 65: Support for 4-octet AS number */
  *buf++ = 4;		/* Capability data length */
207
  put_u32(buf, p->local_as);
208 209 210
  return buf + 4;
}

211
static byte *
212
bgp_put_cap_add_path(struct bgp_proto *p, byte *buf)
213 214 215 216 217 218 219 220
{
  *buf++ = 69;		/* Capability 69: Support for ADD-PATH */
  *buf++ = 4;		/* Capability data length */

  *buf++ = 0;		/* Appropriate AF */
  *buf++ = BGP_AF;
  *buf++ = 1;		/* SAFI 1 */

221
  *buf++ = p->cf->add_path;
222 223 224 225

  return buf;
}

226 227 228 229 230 231 232 233 234
static byte *
bgp_put_cap_err(struct bgp_proto *p UNUSED, byte *buf)
{
  *buf++ = 70;		/* Capability 70: Support for enhanced route refresh */
  *buf++ = 0;		/* Capability data length */
  return buf;
}


235 236 237
static byte *
bgp_create_open(struct bgp_conn *conn, byte *buf)
{
Martin Mareš's avatar
Martin Mareš committed
238
  struct bgp_proto *p = conn->bgp;
239 240
  byte *cap;
  int cap_len;
Martin Mareš's avatar
Martin Mareš committed
241 242 243

  BGP_TRACE(D_PACKETS, "Sending OPEN(ver=%d,as=%d,hold=%d,id=%08x)",
	    BGP_VERSION, p->local_as, p->cf->hold_time, p->local_id);
244
  buf[0] = BGP_VERSION;
245
  put_u16(buf+1, (p->local_as < 0xFFFF) ? p->local_as : AS_TRANS);
Martin Mareš's avatar
Martin Mareš committed
246 247
  put_u16(buf+3, p->cf->hold_time);
  put_u32(buf+5, p->local_id);
248 249 250 251 252 253 254 255

  if (conn->start_state == BSS_CONNECT_NOCAP)
    {
      BGP_TRACE(D_PACKETS, "Skipping capabilities");
      buf[9] = 0;
      return buf + 10;
    }

256 257 258
  /* Skipped 3 B for length field and Capabilities parameter header */
  cap = buf + 12;

259 260
#ifndef IPV6
  if (p->cf->advertise_ipv4)
261
    cap = bgp_put_cap_ipv4(p, cap);
262 263
#endif

264
#ifdef IPV6
265
  cap = bgp_put_cap_ipv6(p, cap);
266
#endif
267

268
  if (p->cf->enable_refresh)
269 270 271 272 273 274
    cap = bgp_put_cap_rr(p, cap);

  if (p->cf->gr_mode == BGP_GR_ABLE)
    cap = bgp_put_cap_gr1(p, cap);
  else if (p->cf->gr_mode == BGP_GR_AWARE)
    cap = bgp_put_cap_gr2(p, cap);
275

276
  if (p->cf->enable_as4)
277
    cap = bgp_put_cap_as4(p, cap);
278

279
  if (p->cf->add_path)
280
    cap = bgp_put_cap_add_path(p, cap);
281

282 283 284
  if (p->cf->enable_refresh)
    cap = bgp_put_cap_err(p, cap);

285 286 287
  if (p->cf->enable_extended_messages)
    cap = bgp_put_cap_ext_msg(p, cap);

288 289 290 291 292 293 294 295 296 297 298 299 300
  cap_len = cap - buf - 12;
  if (cap_len > 0)
    {
      buf[9]  = cap_len + 2;	/* Optional params len */
      buf[10] = 2;		/* Option: Capability list */
      buf[11] = cap_len;	/* Option length */
      return cap;
    }
  else
    {
      buf[9] = 0;		/* No optional parameters */
      return buf + 10;
    }
301 302
}

Pavel Tvrdík's avatar
Pavel Tvrdík committed
303 304
static uint
bgp_encode_prefixes(struct bgp_proto *p, byte *w, struct bgp_bucket *buck, uint remains)
305 306 307 308 309
{
  byte *start = w;
  ip_addr a;
  int bytes;

Ondřej Zajíček's avatar
Ondřej Zajíček committed
310
  while (!EMPTY_LIST(buck->prefixes) && (remains >= (5+sizeof(ip_addr))))
311 312 313
    {
      struct bgp_prefix *px = SKIP_BACK(struct bgp_prefix, bucket_node, HEAD(buck->prefixes));
      DBG("\tDequeued route %I/%d\n", px->n.prefix, px->n.pxlen);
314 315 316 317 318

      if (p->add_path_tx)
	{
	  put_u32(w, px->path_id);
	  w += 4;
Ondřej Zajíček's avatar
Ondřej Zajíček committed
319
	  remains -= 4;
320 321
	}

322 323 324 325 326 327
      *w++ = px->n.pxlen;
      bytes = (px->n.pxlen + 7) / 8;
      a = px->n.prefix;
      ipa_hton(a);
      memcpy(w, &a, bytes);
      w += bytes;
328
      remains -= bytes + 1;
329
      rem_node(&px->bucket_node);
330 331
      bgp_free_prefix(p, px);
      // fib_delete(&p->prefix_fib, px);
332 333 334 335
    }
  return w - start;
}

336 337 338 339 340 341 342 343
static void
bgp_flush_prefixes(struct bgp_proto *p, struct bgp_bucket *buck)
{
  while (!EMPTY_LIST(buck->prefixes))
    {
      struct bgp_prefix *px = SKIP_BACK(struct bgp_prefix, bucket_node, HEAD(buck->prefixes));
      log(L_ERR "%s: - route %I/%d skipped", p->p.name, px->n.prefix, px->n.pxlen);
      rem_node(&px->bucket_node);
344 345
      bgp_free_prefix(p, px);
      // fib_delete(&p->prefix_fib, px);
346 347 348
    }
}

Martin Mareš's avatar
Martin Mareš committed
349 350
#ifndef IPV6		/* IPv4 version */

351 352 353
static byte *
bgp_create_update(struct bgp_conn *conn, byte *buf)
{
Martin Mareš's avatar
Martin Mareš committed
354
  struct bgp_proto *p = conn->bgp;
355
  struct bgp_bucket *buck;
356
  int remains = bgp_max_packet_length(p) - BGP_HEADER_LENGTH - 4;
357
  byte *w;
358 359
  int wd_size = 0;
  int r_size = 0;
360
  int a_size = 0;
361 362

  w = buf+2;
Martin Mareš's avatar
Martin Mareš committed
363
  if ((buck = p->withdraw_bucket) && !EMPTY_LIST(buck->prefixes))
364 365
    {
      DBG("Withdrawn routes:\n");
Martin Mareš's avatar
Martin Mareš committed
366
      wd_size = bgp_encode_prefixes(p, w, buck, remains);
367 368 369 370
      w += wd_size;
      remains -= wd_size;
    }
  put_u16(buf, wd_size);
371

372
  if (!wd_size)
373
    {
Martin Mareš's avatar
Martin Mareš committed
374
      while ((buck = (struct bgp_bucket *) HEAD(p->bucket_queue))->send_node.next)
375 376 377 378 379
	{
	  if (EMPTY_LIST(buck->prefixes))
	    {
	      DBG("Deleting empty bucket %p\n", buck);
	      rem_node(&buck->send_node);
Martin Mareš's avatar
Martin Mareš committed
380
	      bgp_free_bucket(p, buck);
381 382
	      continue;
	    }
383

384
	  DBG("Processing bucket %p\n", buck);
385
	  a_size = bgp_encode_attrs(p, w+2, buck->eattrs, remains - 1024);
386 387 388

	  if (a_size < 0)
	    {
389
	      log(L_ERR "%s: Attribute list too long, skipping corresponding routes", p->p.name);
390 391 392 393 394 395
	      bgp_flush_prefixes(p, buck);
	      rem_node(&buck->send_node);
	      bgp_free_bucket(p, buck);
	      continue;
	    }

396 397 398
	  put_u16(w, a_size);
	  w += a_size + 2;
	  r_size = bgp_encode_prefixes(p, w, buck, remains - a_size);
399 400 401 402
	  w += r_size;
	  break;
	}
    }
403
  if (!a_size)				/* Attributes not already encoded */
404 405 406 407
    {
      put_u16(w, 0);
      w += 2;
    }
408 409
  if (wd_size || r_size)
    {
410
      BGP_TRACE_RL(&rl_snd_update, D_PACKETS, "Sending UPDATE");
411 412 413 414
      return w;
    }
  else
    return NULL;
415 416
}

417 418 419 420
static byte *
bgp_create_end_mark(struct bgp_conn *conn, byte *buf)
{
  struct bgp_proto *p = conn->bgp;
421
  BGP_TRACE(D_PACKETS, "Sending END-OF-RIB");
422 423 424 425 426

  put_u32(buf, 0);
  return buf+4;
}

Martin Mareš's avatar
Martin Mareš committed
427 428
#else		/* IPv6 version */

429 430 431 432 433 434 435
static inline int
same_iface(struct bgp_proto *p, ip_addr *ip)
{
  neighbor *n = neigh_find(&p->p, ip, 0);
  return n && p->neigh && n->iface == p->neigh->iface;
}

Martin Mareš's avatar
Martin Mareš committed
436 437 438
static byte *
bgp_create_update(struct bgp_conn *conn, byte *buf)
{
439 440
  struct bgp_proto *p = conn->bgp;
  struct bgp_bucket *buck;
441
  int size, second, rem_stored;
442
  int remains = bgp_max_packet_length(p) - BGP_HEADER_LENGTH - 4;
443
  byte *w, *w_stored, *tmp, *tstart;
444
  ip_addr *ipp, ip, ip_ll;
445 446 447 448 449 450 451 452 453
  ea_list *ea;
  eattr *nh;

  put_u16(buf, 0);
  w = buf+4;

  if ((buck = p->withdraw_bucket) && !EMPTY_LIST(buck->prefixes))
    {
      DBG("Withdrawn routes:\n");
454
      tmp = bgp_attach_attr_wa(&ea, bgp_linpool, BA_MP_UNREACH_NLRI, remains-8);
455 456 457
      *tmp++ = 0;
      *tmp++ = BGP_AF_IPV6;
      *tmp++ = 1;
458
      ea->attrs[0].u.ptr->length = 3 + bgp_encode_prefixes(p, tmp, buck, remains-11);
459
      size = bgp_encode_attrs(p, w, ea, remains);
460
      ASSERT(size >= 0);
461 462 463
      w += size;
      remains -= size;
    }
464
  else
465 466 467 468 469 470 471 472 473 474
    {
      while ((buck = (struct bgp_bucket *) HEAD(p->bucket_queue))->send_node.next)
	{
	  if (EMPTY_LIST(buck->prefixes))
	    {
	      DBG("Deleting empty bucket %p\n", buck);
	      rem_node(&buck->send_node);
	      bgp_free_bucket(p, buck);
	      continue;
	    }
475

476
	  DBG("Processing bucket %p\n", buck);
477 478
	  rem_stored = remains;
	  w_stored = w;
479

480
	  size = bgp_encode_attrs(p, w, buck->eattrs, remains - 1024);
481 482
	  if (size < 0)
	    {
483
	      log(L_ERR "%s: Attribute list too long, skipping corresponding routes", p->p.name);
484 485 486 487 488
	      bgp_flush_prefixes(p, buck);
	      rem_node(&buck->send_node);
	      bgp_free_bucket(p, buck);
	      continue;
	    }
489 490
	  w += size;
	  remains -= size;
491

492
	  /* We have two addresses here in NEXT_HOP eattr. Really.
493
	     Unless NEXT_HOP was modified by filter */
494 495
	  nh = ea_find(buck->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
	  ASSERT(nh);
496
	  second = (nh->u.ptr->length == NEXT_HOP_LENGTH);
497 498 499 500
	  ipp = (ip_addr *) nh->u.ptr->data;
	  ip = ipp[0];
	  ip_ll = IPA_NONE;

501
	  if (ipa_equal(ip, p->source_addr))
502
	    ip_ll = p->local_link;
503 504
	  else
	    {
505 506 507 508
	      /* If we send a route with 'third party' next hop destinated 
	       * in the same interface, we should also send a link local 
	       * next hop address. We use the received one (stored in the 
	       * other part of BA_NEXT_HOP eattr). If we didn't received
509 510 511 512 513 514
	       * it (for example it is a static route), we can't use
	       * 'third party' next hop and we have to use local IP address
	       * as next hop. Sending original next hop address without
	       * link local address seems to be a natural way to solve that
	       * problem, but it is contrary to RFC 2545 and Quagga does not
	       * accept such routes.
515 516 517 518
	       *
	       * There are two cases, either we have global IP, or
	       * IPA_NONE if the neighbor is link-local. For IPA_NONE,
	       * we suppose it is on the same iface, see bgp_update_attrs().
519 520
	       */

521
	      if (ipa_zero(ip) || same_iface(p, &ip))
522
		{
523
		  if (second && ipa_nonzero(ipp[1]))
524 525 526
		    ip_ll = ipp[1];
		  else
		    {
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
		      switch (p->cf->missing_lladdr)
			{
			case MLL_SELF:
			  ip = p->source_addr;
			  ip_ll = p->local_link;
			  break;
			case MLL_DROP:
			  log(L_ERR "%s: Missing link-local next hop address, skipping corresponding routes", p->p.name);
			  w = w_stored;
			  remains = rem_stored;
			  bgp_flush_prefixes(p, buck);
			  rem_node(&buck->send_node);
			  bgp_free_bucket(p, buck);
			  continue;
			case MLL_IGNORE:
			  break;
			}
544 545
		    }
		}
546
	    }
547

548 549 550 551 552
	  tstart = tmp = bgp_attach_attr_wa(&ea, bgp_linpool, BA_MP_REACH_NLRI, remains-8);
	  *tmp++ = 0;
	  *tmp++ = BGP_AF_IPV6;
	  *tmp++ = 1;

553
	  if (ipa_is_link_local(ip))
554 555
	    ip = IPA_NONE;

556
	  if (ipa_nonzero(ip_ll))
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
	    {
	      *tmp++ = 32;
	      ipa_hton(ip);
	      memcpy(tmp, &ip, 16);
	      ipa_hton(ip_ll);
	      memcpy(tmp+16, &ip_ll, 16);
	      tmp += 32;
	    }
	  else
	    {
	      *tmp++ = 16;
	      ipa_hton(ip);
	      memcpy(tmp, &ip, 16);
	      tmp += 16;
	    }
572

573 574 575
	  *tmp++ = 0;			/* No SNPA information */
	  tmp += bgp_encode_prefixes(p, tmp, buck, remains - (8+3+32+1));
	  ea->attrs[0].u.ptr->length = tmp - tstart;
576 577 578
	  size = bgp_encode_attrs(p, w, ea, remains);
	  ASSERT(size >= 0);
	  w += size;
579 580 581 582 583 584 585
	  break;
	}
    }

  size = w - (buf+4);
  put_u16(buf+2, size);
  lp_flush(bgp_linpool);
586 587
  if (size)
    {
588
      BGP_TRACE_RL(&rl_snd_update, D_PACKETS, "Sending UPDATE");
589 590 591 592
      return w;
    }
  else
    return NULL;
Martin Mareš's avatar
Martin Mareš committed
593 594
}

595 596 597 598
static byte *
bgp_create_end_mark(struct bgp_conn *conn, byte *buf)
{
  struct bgp_proto *p = conn->bgp;
599
  BGP_TRACE(D_PACKETS, "Sending END-OF-RIB");
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614

  put_u16(buf+0, 0);
  put_u16(buf+2, 6);	/* length 4-9 */
  buf += 4;

  /* Empty MP_UNREACH_NLRI atribute */
  *buf++ = BAF_OPTIONAL;
  *buf++ = BA_MP_UNREACH_NLRI;
  *buf++ = 3;		/* Length 7-9 */
  *buf++ = 0;		/* AFI */
  *buf++ = BGP_AF_IPV6;
  *buf++ = 1;		/* SAFI */
  return buf;
}

Martin Mareš's avatar
Martin Mareš committed
615 616
#endif

617
static inline byte *
618 619 620 621 622
bgp_create_route_refresh(struct bgp_conn *conn, byte *buf)
{
  struct bgp_proto *p = conn->bgp;
  BGP_TRACE(D_PACKETS, "Sending ROUTE-REFRESH");

623
  /* Original original route refresh request, RFC 2918 */
624 625
  *buf++ = 0;
  *buf++ = BGP_AF;
626 627
  *buf++ = BGP_RR_REQUEST;
  *buf++ = 1;		/* SAFI */
628 629 630
  return buf;
}

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
static inline byte *
bgp_create_begin_refresh(struct bgp_conn *conn, byte *buf)
{
  struct bgp_proto *p = conn->bgp;
  BGP_TRACE(D_PACKETS, "Sending BEGIN-OF-RR");

  /* Demarcation of beginning of route refresh (BoRR), RFC 7313 */
  *buf++ = 0;
  *buf++ = BGP_AF;
  *buf++ = BGP_RR_BEGIN;
  *buf++ = 1;		/* SAFI */
  return buf;
}

static inline byte *
bgp_create_end_refresh(struct bgp_conn *conn, byte *buf)
{
  struct bgp_proto *p = conn->bgp;
  BGP_TRACE(D_PACKETS, "Sending END-OF-RR");

  /* Demarcation of ending of route refresh (EoRR), RFC 7313 */
  *buf++ = 0;
  *buf++ = BGP_AF;
  *buf++ = BGP_RR_END;
  *buf++ = 1;		/* SAFI */
  return buf;
}


660
static void
Pavel Tvrdík's avatar
Pavel Tvrdík committed
661
bgp_create_header(byte *buf, uint len, uint type)
662 663 664 665 666 667
{
  memset(buf, 0xff, 16);		/* Marker */
  put_u16(buf+16, len);
  buf[18] = type;
}

Martin Mareš's avatar
Martin Mareš committed
668 669 670 671 672 673 674 675 676 677
/**
 * bgp_fire_tx - transmit packets
 * @conn: connection
 *
 * Whenever the transmit buffers of the underlying TCP connection
 * are free and we have any packets queued for sending, the socket functions
 * call bgp_fire_tx() which takes care of selecting the highest priority packet
 * queued (Notification > Keepalive > Open > Update), assembling its header
 * and body and sending it to the connection.
 */
678
static int
679 680
bgp_fire_tx(struct bgp_conn *conn)
{
Martin Mareš's avatar
Martin Mareš committed
681
  struct bgp_proto *p = conn->bgp;
Pavel Tvrdík's avatar
Pavel Tvrdík committed
682
  uint s = conn->packets_to_send;
683
  sock *sk = conn->sk;
684
  byte *buf, *pkt, *end;
685 686
  int type;

687 688 689 690 691 692 693 694
  if (!sk)
    {
      conn->packets_to_send = 0;
      return 0;
    }
  buf = sk->tbuf;
  pkt = buf + BGP_HEADER_LENGTH;

695 696
  if (s & (1 << PKT_SCHEDULE_CLOSE))
    {
Ondřej Zajíček's avatar
Ondřej Zajíček committed
697 698
      /* We can finally close connection and enter idle state */
      bgp_conn_enter_idle_state(conn);
699
      return 0;
700 701 702 703 704 705 706 707 708 709 710 711
    }
  if (s & (1 << PKT_NOTIFICATION))
    {
      s = 1 << PKT_SCHEDULE_CLOSE;
      type = PKT_NOTIFICATION;
      end = bgp_create_notification(conn, pkt);
    }
  else if (s & (1 << PKT_KEEPALIVE))
    {
      s &= ~(1 << PKT_KEEPALIVE);
      type = PKT_KEEPALIVE;
      end = pkt;			/* Keepalives carry no data */
Martin Mareš's avatar
Martin Mareš committed
712
      BGP_TRACE(D_PACKETS, "Sending KEEPALIVE");
713
      bgp_start_timer(conn->keepalive_timer, conn->keepalive_time);
714 715 716 717 718 719 720
    }
  else if (s & (1 << PKT_OPEN))
    {
      s &= ~(1 << PKT_OPEN);
      type = PKT_OPEN;
      end = bgp_create_open(conn, pkt);
    }
721 722 723 724 725 726
  else if (s & (1 << PKT_ROUTE_REFRESH))
    {
      s &= ~(1 << PKT_ROUTE_REFRESH);
      type = PKT_ROUTE_REFRESH;
      end = bgp_create_route_refresh(conn, pkt);
    }
727 728 729 730 731 732
  else if (s & (1 << PKT_BEGIN_REFRESH))
    {
      s &= ~(1 << PKT_BEGIN_REFRESH);
      type = PKT_ROUTE_REFRESH;	/* BoRR is a subtype of RR */
      end = bgp_create_begin_refresh(conn, pkt);
    }
733 734 735
  else if (s & (1 << PKT_UPDATE))
    {
      type = PKT_UPDATE;
736
      end = bgp_create_update(conn, pkt);
737

738
      if (!end)
739 740 741
        {
	  /* No update to send, perhaps we need to send End-of-RIB or EoRR */

742
	  conn->packets_to_send = 0;
743

744 745 746 747 748 749 750 751 752 753 754 755 756
	  if (p->feed_state == BFS_LOADED)
	  {
	    type = PKT_UPDATE;
	    end = bgp_create_end_mark(conn, pkt);
	  }

	  else if (p->feed_state == BFS_REFRESHED)
	  {
	    type = PKT_ROUTE_REFRESH;
	    end = bgp_create_end_refresh(conn, pkt);
	  }

	  else /* Really nothing to send */
757 758
	    return 0;

759
	  p->feed_state = BFS_NONE;
760 761 762
	}
    }
  else
763
    return 0;
764

765 766
  conn->packets_to_send = s;
  bgp_create_header(buf, end - buf, type);
767
  return sk_send(sk, end - buf);
768 769
}

Martin Mareš's avatar
Martin Mareš committed
770 771 772 773 774 775 776
/**
 * bgp_schedule_packet - schedule a packet for transmission
 * @conn: connection
 * @type: packet type
 *
 * Schedule a packet of type @type to be sent as soon as possible.
 */
777 778 779 780 781
void
bgp_schedule_packet(struct bgp_conn *conn, int type)
{
  DBG("BGP: Scheduling packet type %d\n", type);
  conn->packets_to_send |= 1 << type;
782
  if (conn->sk && conn->sk->tpos == conn->sk->tbuf && !ev_active(conn->tx_ev))
Ondřej Zajíček's avatar
Ondřej Zajíček committed
783 784 785 786 787 788 789 790 791
    ev_schedule(conn->tx_ev);
}

void
bgp_kick_tx(void *vconn)
{
  struct bgp_conn *conn = vconn;

  DBG("BGP: kicking TX\n");
792
  while (bgp_fire_tx(conn) > 0)
Ondřej Zajíček's avatar
Ondřej Zajíček committed
793
    ;
794 795 796 797 798 799 800 801
}

void
bgp_tx(sock *sk)
{
  struct bgp_conn *conn = sk->data;

  DBG("BGP: TX hook\n");
802
  while (bgp_fire_tx(conn) > 0)
803 804 805
    ;
}

806 807 808 809 810
/* Capatibility negotiation as per RFC 2842 */

void
bgp_parse_capabilities(struct bgp_conn *conn, byte *opt, int len)
{
811
  // struct bgp_proto *p = conn->bgp;
812
  int i, cl;
813 814 815 816 817

  while (len > 0)
    {
      if (len < 2 || len < 2 + opt[1])
	goto err;
818

819 820 821 822
      cl = opt[1];

      switch (opt[0])
	{
823
	case 2:	/* Route refresh capability, RFC 2918 */
824 825 826 827
	  if (cl != 0)
	    goto err;
	  conn->peer_refresh_support = 1;
	  break;
828

829 830 831 832 833 834
	case 6: /* Extended message length capability, draft */
	  if (cl != 0)
	    goto err;
	  conn->peer_ext_messages_support = 1;
	  break;

835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
	case 64: /* Graceful restart capability, RFC 4724 */
	  if (cl % 4 != 2)
	    goto err;
	  conn->peer_gr_aware = 1;
	  conn->peer_gr_able = 0;
	  conn->peer_gr_time = get_u16(opt + 2) & 0x0fff;
	  conn->peer_gr_flags = opt[2] & 0xf0;
	  conn->peer_gr_aflags = 0;
	  for (i = 2; i < cl; i += 4)
	    if (opt[2+i+0] == 0 && opt[2+i+1] == BGP_AF && opt[2+i+2] == 1) /* Match AFI/SAFI */
	      {
		conn->peer_gr_able = 1;
		conn->peer_gr_aflags = opt[2+i+3];
	      }
	  break;

851
	case 65: /* AS4 capability, RFC 4893 */
852 853
	  if (cl != 4)
	    goto err;
854
	  conn->peer_as4_support = 1;
855
	  if (conn->bgp->cf->enable_as4)
856 857 858
	    conn->advertised_as = get_u32(opt + 2);
	  break;

859
	case 69: /* ADD-PATH capability, RFC 7911 */
860 861 862 863 864 865 866
	  if (cl % 4)
	    goto err;
	  for (i = 0; i < cl; i += 4)
	    if (opt[2+i+0] == 0 && opt[2+i+1] == BGP_AF && opt[2+i+2] == 1) /* Match AFI/SAFI */
	      conn->peer_add_path = opt[2+i+3];
	  if (conn->peer_add_path > ADD_PATH_FULL)
	    goto err;
867
	  break;
868

869 870 871 872
	case 70: /* Enhanced route refresh capability, RFC 7313 */
	  if (cl != 0)
	    goto err;
	  conn->peer_enhanced_refresh_support = 1;
873 874
	  break;

875 876 877 878 879 880 881
	  /* We can safely ignore all other capabilities */
	}
      len -= 2 + cl;
      opt += 2 + cl;
    }
  return;

882
 err:
883 884 885 886
  bgp_error(conn, 2, 0, NULL, 0);
  return;
}

887 888 889
static int
bgp_parse_options(struct bgp_conn *conn, byte *opt, int len)
{
890
  struct bgp_proto *p = conn->bgp;
891 892
  int ol;

893 894 895
  while (len > 0)
    {
      if (len < 2 || len < 2 + opt[1])
896
	{ bgp_error(conn, 2, 0, NULL, 0); return 0; }
897 898 899 900 901 902 903 904 905
#ifdef LOCAL_DEBUG
      {
	int i;
	DBG("\tOption %02x:", opt[0]);
	for(i=0; i<opt[1]; i++)
	  DBG(" %02x", opt[2+i]);
	DBG("\n");
      }
#endif
906 907

      ol = opt[1];
908 909 910
      switch (opt[0])
	{
	case 2:
911 912 913 914
	  if (conn->start_state == BSS_CONNECT_NOCAP)
	    BGP_TRACE(D_PACKETS, "Ignoring received capabilities");
	  else
	    bgp_parse_capabilities(conn, opt + 2, ol);
915
	  break;
916

917 918 919 920 921 922 923
	default:
	  /*
	   *  BGP specs don't tell us to send which option
	   *  we didn't recognize, but it's common practice
	   *  to do so. Also, capability negotiation with
	   *  Cisco routers doesn't work without that.
	   */
924
	  bgp_error(conn, 2, 4, opt, ol);
925 926
	  return 0;
	}
927 928
      len -= 2 + ol;
      opt += 2 + ol;
929 930 931 932
    }
  return 0;
}

933
static void
934
bgp_rx_open(struct bgp_conn *conn, byte *pkt, uint len)
935
{
936
  struct bgp_conn *other;
937
  struct bgp_proto *p = conn->bgp;
938
  unsigned hold;
939
  u16 base_as;
940 941 942 943
  u32 id;

  /* Check state */
  if (conn->state != BS_OPENSENT)
944
    { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
945 946

  /* Check message contents */
947
  if (len < 29 || len != 29U + pkt[28])
948
    { bgp_error(conn, 1, 2, pkt+16, 2); return; }
949
  if (pkt[19] != BGP_VERSION)
950
    { bgp_error(conn, 2, 1, pkt+19, 1); return; } /* RFC 1771 says 16 bits, draft-09 tells to use 8 */
951
  conn->advertised_as = base_as = get_u16(pkt+20);
952 953
  hold = get_u16(pkt+22);
  id = get_u32(pkt+24);
954 955
  BGP_TRACE(D_PACKETS, "Got OPEN(as=%d,hold=%d,id=%08x)", conn->advertised_as, hold, id);

956 957
  if (bgp_parse_options(conn, pkt+29, pkt[28]))
    return;
958 959 960 961

  if (hold > 0 && hold < 3)
    { bgp_error(conn, 2, 6, pkt+22, 2); return; }

962 963
  /* RFC 6286 2.2 - router ID is nonzero and AS-wide unique */
  if (!id || (p->is_internal && id == p->local_id))
964
    { bgp_error(conn, 2, 3, pkt+24, -4); return; }
965

966 967 968
  if ((conn->advertised_as != base_as) && (base_as != AS_TRANS))
    log(L_WARN "%s: Peer advertised inconsistent AS numbers", p->p.name);

969
  if (conn->advertised_as != p->remote_as)
970 971 972 973 974 975 976 977 978 979 980
    {
      if (conn->peer_as4_support)
	{
	  u32 val = htonl(conn->advertised_as);
	  bgp_error(conn, 2, 2, (byte *) &val, 4);
	}
      else
	bgp_error(conn, 2, 2, pkt+20, 2);

      return;
    }
981

982 983 984 985 986 987
  /* Check the other connection */
  other = (conn == &p->outgoing_conn) ? &p->incoming_conn : &p->outgoing_conn;
  switch (other->state)
    {
    case BS_CONNECT:
    case BS_ACTIVE:
988 989 990 991 992
      /* Stop outgoing connection attempts */
      bgp_conn_enter_idle_state(other);
      break;

    case BS_IDLE:
993
    case BS_OPENSENT:
Ondřej Zajíček's avatar
Ondřej Zajíček committed
994
    case BS_CLOSE:
995
      break;
996

997
    case BS_OPENCONFIRM:
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
      /*
       * Description of collision detection rules in RFC 4271 is confusing and
       * contradictory, but it is essentially:
       *
       * 1. Router with higher ID is dominant
       * 2. If both have the same ID, router with higher ASN is dominant [RFC6286]
       * 3. When both connections are in OpenConfirm state, one initiated by
       *    the dominant router is kept.
       *
       * The first line in the expression below evaluates whether the neighbor
       * is dominant, the second line whether the new connection was initiated
       * by the neighbor. If both are true (or both are false), we keep the new
       * connection, otherwise we keep the old one.
       */
      if (((p->local_id < id) || ((p->local_id == id) && (p->local_as < p->remote_as)))
	  == (conn == &p->incoming_conn))
        {
1015
	  /* Should close the other connection */
Martin Mareš's avatar
Martin Mareš committed
1016
	  BGP_TRACE(D_EVENTS, "Connection collision, giving up the other connection");
1017
	  bgp_error(other, 6, 7, NULL, 0);
1018 1019 1020 1021 1022
	  break;
	}
      /* Fall thru */
    case BS_ESTABLISHED:
      /* Should close this connection */
Martin Mareš's avatar
Martin Mareš committed
1023
      BGP_TRACE(D_EVENTS, "Connection collision, giving up this connection");
1024
      bgp_error(conn, 6, 7, NULL, 0);
1025 1026 1027 1028 1029
      return;
    default:
      bug("bgp_rx_open: Unknown state");
    }

1030
  /* Update our local variables */
Ondřej Zajíček's avatar
Ondřej Zajíček committed
1031
  conn->hold_time = MIN(hold, p->cf->hold_time);
1032 1033
  conn->keepalive_time = p->cf->keepalive_time ? : conn->hold_time / 3;
  p->remote_id = id;
1034 1035 1036
  p->as4_session = p->cf->enable_as4 && conn->peer_as4_support;
  p->add_path_rx = (p->cf->add_path & ADD_PATH_RX) && (conn->peer_add_path & ADD_PATH_TX);
  p->add_path_tx = (p->cf->add_path & ADD_PATH_TX) && (conn->peer_add_path & ADD_PATH_RX);
1037
  p->gr_ready = p->cf->gr_mode && conn->peer_gr_able;
1038
  p->ext_messages = p->cf->enable_extended_messages && conn->peer_ext_messages_support;
1039

1040
  /* Update RA mode */
1041 1042
  if (p->add_path_tx)
    p->p.accept_ra_types = RA_ANY;
1043 1044 1045 1046
  else if (p->cf->secondary)
    p->p.accept_ra_types = RA_ACCEPTED;
  else
    p->p.accept_ra_types = RA_OPTIMAL;
1047

Ondřej Zajíček's avatar
Ondřej Zajíček committed
1048
  DBG("BGP: Hold timer set to %d, keepalive to %d, AS to %d, ID to %x, AS4 session to %d\n", conn->hold_time, conn->keepalive_time, p->remote_as, p->remote_id, p->as4_session);
1049 1050 1051

  bgp_schedule_packet(conn, PKT_KEEPALIVE);
  bgp_start_timer(conn->hold_timer, conn->hold_time);
1052
  bgp_conn_enter_openconfirm_state(conn);
1053 1054
}

1055 1056 1057 1058

static inline void
bgp_rx_end_mark(struct bgp_proto *p)
{
1059 1060 1061 1062
  BGP_TRACE(D_PACKETS, "Got END-OF-RIB");

  if (p->load_state == BFS_LOADING)
    p->load_state = BFS_NONE;
1063 1064 1065 1066 1067 1068 1069 1070 1071

  if (p->p.gr_recovery)
    proto_graceful_restart_unlock(&p->p);

  if (p->gr_active)
    bgp_graceful_restart_done(p);
}


1072
#define DECODE_PREFIX(pp, ll) do {		\
1073 1074 1075 1076 1077 1078 1079
  if (p->add_path_rx)				\
  {						\
    if (ll < 5) { err=1; goto done; }		\
    path_id = get_u32(pp);			\
    pp += 4;					\
    ll -= 4;					\
  }						\
1080 1081 1082
  int b = *pp++;				\
  int q;					\
  ll--;						\
1083
  if (b > BITS_PER_IP_ADDRESS) { err=10; goto done; } \
1084
  q = (b+7) / 8;				\
1085
  if (ll < q) { err=1; goto done; }		\
1086
  memcpy(&prefix, pp, q);			\
1087 1088
  pp += q;					\
  ll -= q;					\
1089 1090
  ipa_ntoh(prefix);				\
  prefix = ipa_and(prefix, ipa_mkmask(b));	\
1091
  pxlen = b;					\
1092 1093
} while (0)

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

static inline void
bgp_rte_update(struct bgp_proto *p, ip_addr prefix, int pxlen,
	       u32 path_id, u32 *last_id, struct rte_src **src,
	       rta *a0, rta **a)
{
  if (path_id != *last_id)
    {
      *src = rt_get_source(&p->p, path_id);
      *last_id = path_id;

      if (*a)
	{
	  rta_free(*a);
	  *a = NULL;
	}
    }

  /* Prepare cached route attributes */
  if (!*a)
    {
      a0->src = *src;
1116 1117 1118

      /* Workaround for rta_lookup() breaking eattrs */
      ea_list *ea = a0->eattrs;
1119
      *a = rta_lookup(a0);
1120
      a0->eattrs = ea;
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    }

  net *n = net_get(p->p.table, prefix, pxlen);
  rte *e = rte_get_temp(rta_clone(*a));
  e->net = n;
  e->pflags = 0;
  e->u.bgp.suppressed = 0;
  rte_update2(p->p.main_ahook, n, e, *src);
}

static inline void
bgp_rte_withdraw(struct bgp_proto *p, ip_addr prefix, int pxlen,
		 u32 path_id, u32 *last_id, struct rte_src **src)
{
  if (path_id != *last_id)
    {
      *src = rt_find_source(&p->p, path_id);
      *last_id = path_id;
    }

  net *n = net_find(p->p.table, prefix, pxlen);
  rte_update2( p->p.main_ahook, n, NULL, *src);
}

Martin Mareš's avatar
Martin Mareš committed
1145
static inline int
1146
bgp_set_next_hop(struct bgp_proto *p, rta *a)
Martin Mareš's avatar
Martin Mareš committed
1147 1148
{
  struct eattr *nh = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
1149 1150 1151
  ip_addr *nexthop = (ip_addr *) nh->u.ptr->data;

#ifdef IPV6
1152
  int second = (nh->u.ptr->length == NEXT_HOP_LENGTH) && ipa_nonzero(nexthop[1]);
1153 1154

  /* First address should not be link-local, but may be zero in direct mode */
1155
  if (ipa_is_link_local(*nexthop))
1156
    *nexthop = IPA_NONE;
1157 1158 1159
#else
  int second = 0;
#endif
1160

1161
  if (p->cf->gw_mode == GW_DIRECT)
Martin Mareš's avatar
Martin Mareš committed
1162
    {
Ondřej Zajíček's avatar
Ondřej Zajíček committed
1163
      neighbor *ng = NULL;
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

      if (ipa_nonzero(*nexthop))
	ng = neigh_find(&p->p, nexthop, 0);
      else if (second)	/* GW_DIRECT -> single_hop -> p->neigh != NULL */
	ng = neigh_find2(&p->p, nexthop + 1, p->neigh->iface, 0);

      /* Fallback */
      if (!ng)
	ng = p->neigh;

1174 1175 1176 1177 1178 1179 1180
      if (ng->scope == SCOPE_HOST)
	return 0;

      a->dest = RTD_ROUTER;
      a->gw = ng->addr;
      a->iface = ng->iface;
      a->hostentry = NULL;
1181
      a->igp_metric = 0;
Martin Mareš's avatar
Martin Mareš committed
1182
    }
1183
  else /* GW_RECURSIVE */
1184 1185 1186 1187 1188 1189
    {
      if (ipa_zero(*nexthop))
	  return 0;

      rta_set_recursive_next_hop(p->p.table, a, p->igp_table, nexthop, nexthop + second);
    }
1190

Martin Mareš's avatar
Martin Mareš committed
1191 1192 1193 1194 1195
  return 1;
}

#ifndef IPV6		/* IPv4 version */

1196
static void
Martin Mareš's avatar
Martin Mareš committed
1197 1198 1199 1200
bgp_do_rx_update(struct bgp_conn *conn,
		 byte *withdrawn, int withdrawn_len,
		 byte *nlri, int nlri_len,
		 byte *attrs, int attr_len)
1201
{
Martin Mareš's avatar
Martin Mareš committed
1202
  struct bgp_proto *p = conn->bgp;
1203
  struct rte_src *src = p->p.main_source;
1204
  rta *a0, *a = NULL;
1205 1206
  ip_addr prefix;
  int pxlen, err = 0;
1207 1208
  u32 path_id = 0;
  u32 last_id = 0;
1209

1210 1211 1212 1213 1214 1215 1216
  /* Check for End-of-RIB marker */
  if (!withdrawn_len && !attr_len && !nlri_len)
    {
      bgp_rx_end_mark(p);
      return;
    }

1217 1218 1219 1220
  /* Withdraw routes */
  while (withdrawn_len)
    {
      DECODE_PREFIX(withdrawn, withdrawn_len);
1221
      DBG("Withdraw %I/%d\n", prefix, pxlen);
1222 1223

      bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
1224 1225
    }

1226 1227 1228
  if (!attr_len && !nlri_len)		/* shortcut */
    return;

1229
  a0 = bgp_decode_attrs(conn, attrs, attr_len, bgp_linpool, nlri_len);
1230 1231 1232 1233

  if (conn->state != BS_ESTABLISHED)	/* fatal error during decoding */
    return;

1234
  if (a0 && nlri_len && !bgp_set_next_hop(p, a0))
1235 1236 1237 1238
    a0 = NULL;

  last_id = 0;
  src = p->p.main_source;
1239 1240

  while (nlri_len)
1241
    {
1242 1243 1244
      DECODE_PREFIX(nlri, nlri_len);
      DBG("Add %I/%d\n", prefix, pxlen);

1245 1246 1247 1248
      if (a0)
	bgp_rte_update(p, prefix, pxlen, path_id, &last_id, &src, a0, &a);
      else /* Forced withdraw as a result of soft error */
	bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
1249
    }
1250

1251
 done:
Martin Mareš's avatar
Martin Mareš committed
1252 1253
  if (a)
    rta_free(a);
1254 1255 1256 1257

  if (err)
    bgp_error(conn, 3, err, NULL, 0);

1258
  return;
Martin Mareš's avatar
Martin Mareš committed
1259
}
1260

Martin Mareš's avatar
Martin Mareš committed
1261 1262 1263
#else			/* IPv6 version */

#define DO_NLRI(name)					\
1264
  x = p->name##_start;				\
Martin Mareš's avatar
Martin Mareš committed
1265 1266 1267
  len = len0 = p->name##_len;				\
  if (len)						\
    {							\
1268
      if (len < 3) { err=9; goto done; }		\
Martin Mareš's avatar
Martin Mareš committed
1269 1270 1271
      af = get_u16(x);					\
      x += 3;						\
      len -= 3;						\
1272
      DBG("\tNLRI AF=%d sub=%d len=%d\n", af, x[-1], len);\
Martin Mareš's avatar
Martin Mareš committed
1273 1274 1275 1276 1277
    }							\
  else							\
    af = 0;						\
  if (af == BGP_AF_IPV6)

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
static void
bgp_attach_next_hop(rta *a0, byte *x)
{
  ip_addr *nh = (ip_addr *) bgp_attach_attr_wa(&a0->eattrs, bgp_linpool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
  memcpy(nh, x+1, 16);
  ipa_ntoh(nh[0]);

  /* We store received link local address in the other part of BA_NEXT_HOP eattr. */
  if (*x == 32)
    {
      memcpy(nh+1, x+17, 16);
      ipa_ntoh(nh[1]);
    }
  else
    nh[1] = IPA_NONE;
}


Martin Mareš's avatar
Martin Mareš committed
1296 1297
static void
bgp_do_rx_update(struct bgp_conn *conn,
1298 1299
		 byte *withdrawn UNUSED, int withdrawn_len,
		 byte *nlri UNUSED, int nlri_len,
Martin Mareš's avatar
Martin Mareš committed
1300 1301 1302
		 byte *attrs, int attr_len)
{
  struct bgp_proto *p = conn->bgp;
1303
  struct rte_src *src = p->p.main_source;
1304
  byte *x;
Martin Mareš's avatar
Martin Mareš committed
1305
  int len, len0;
1306
  unsigned af;
1307
  rta *a0, *a = NULL;
1308 1309
  ip_addr prefix;
  int pxlen, err = 0;
1310 1311
  u32 path_id = 0;
  u32 last_id = 0;
Martin Mareš's avatar
Martin Mareš committed
1312 1313 1314 1315

  p->mp_reach_len = 0;
  p->mp_unreach_len = 0;
  a0 = bgp_decode_attrs(conn, attrs, attr_len, bgp_linpool, 0);
1316 1317

  if (conn->state != BS_ESTABLISHED)	/* fatal error during decoding */
Martin Mareš's avatar
Martin Mareš committed
1318 1319
    return;

1320
  /* Check for End-of-RIB marker */
1321
  if ((attr_len < 8) && !withdrawn_len && !nlri_len && !p->mp_reach_len &&
1322 1323 1324 1325 1326 1327
      (p->mp_unreach_len == 3) && (get_u16(p->mp_unreach_start) == BGP_AF_IPV6))
    {
      bgp_rx_end_mark(p);
      return;
    }

Martin Mareš's avatar
Martin Mareš committed
1328 1329 1330 1331 1332 1333
  DO_NLRI(mp_unreach)
    {
      while (len)
	{
	  DECODE_PREFIX(x, len);
	  DBG("Withdraw %I/%d\n", prefix, pxlen);
1334
	  bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
Martin Mareš's avatar
Martin Mareš committed
1335 1336 1337 1338 1339 1340 1341
	}
    }

  DO_NLRI(mp_reach)
    {
      /* Create fake NEXT_HOP attribute */
      if (len < 1 || (*x != 16 && *x != 32) || len < *x + 2)
1342
	{ err = 9; goto done; }
Martin Mareš's avatar
Martin Mareš committed
1343

1344 1345
      if (a0)
	bgp_attach_next_hop(a0, x);
1346 1347 1348 1349

      /* Also ignore one reserved byte */
      len -= *x + 2;
      x += *x + 2;
Martin Mareš's avatar
Martin Mareš committed
1350

1351 1352 1353 1354 1355
      if (a0 && ! bgp_set_next_hop(p, a0))
	a0 = NULL;

      last_id = 0;
      src = p->p.main_source;
1356 1357

      while (len)
Martin Mareš's avatar
Martin Mareš committed
1358
	{
1359 1360 1361
	  DECODE_PREFIX(x, len);
	  DBG("Add %I/%d\n", prefix, pxlen);

1362 1363 1364 1365
	  if (a0)
	    bgp_rte_update(p, prefix, pxlen, path_id, &last_id, &src, a0, &a);
	  else /* Forced withdraw as a result of soft error */
	    bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
Martin Mareš's avatar
Martin Mareš committed
1366 1367 1368
	}
    }

1369
 done:
1370 1371
  if (a)
    rta_free(a);
1372 1373 1374 1375

  if (err) /* Use subcode 9, not err */
    bgp_error(conn, 3, 9, NULL, 0);

Martin Mareš's avatar
Martin Mareš committed
1376 1377 1378 1379 1380 1381
  return;
}

#endif

static void
1382
bgp_rx_update(struct bgp_conn *conn, byte *pkt, uint len)
Martin Mareš's avatar
Martin Mareš committed
1383 1384 1385
{
  struct bgp_proto *p = conn->bgp;
  byte *withdrawn, *attrs, *nlri;
1386
  uint withdrawn_len, attr_len, nlri_len;
Martin Mareš's avatar
Martin Mareš committed
1387

1388 1389
  BGP_TRACE_RL(&rl_rcv_update, D_PACKETS, "Got UPDATE");

1390 1391 1392 1393
  /* Workaround for some BGP implementations that skip initial KEEPALIVE */
  if (conn->state == BS_OPENCONFIRM)
    bgp_conn_enter_established_state(conn);

Martin Mareš's avatar
Martin Mareš committed
1394
  if (conn->state != BS_ESTABLISHED)
1395
    { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
Martin Mareš's avatar
Martin Mareš committed
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  bgp_start_timer(conn->hold_timer, conn->hold_time);

  /* Find parts of the packet and check sizes */
  if (len < 23)
    {
      bgp_error(conn, 1, 2, pkt+16, 2);
      return;
    }
  withdrawn = pkt + 21;
  withdrawn_len = get_u16(pkt + 19);
  if (withdrawn_len + 23 > len)
    goto malformed;
  attrs = withdrawn + withdrawn_len + 2;
  attr_len = get_u16(attrs - 2);
  if (withdrawn_len + attr_len + 23 > len)
    goto malformed;
  nlri = attrs + attr_len;
  nlri_len = len - withdrawn_len - attr_len - 23;
  if (!attr_len && nlri_len)
    goto malformed;
  DBG("Sizes: withdrawn=%d, attrs=%d, NLRI=%d\n", withdrawn_len, attr_len, nlri_len);

  lp_flush(bgp_linpool);

  bgp_do_rx_update(conn, withdrawn, withdrawn_len, nlri, nlri_len, attrs, attr_len);
  return;

malformed:
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
  bgp_error(conn, 3, 1, NULL, 0);
}

static struct {
  byte major, minor;
  byte *msg;
} bgp_msg_table[] = {
  { 1, 0, "Invalid message header" },
  { 1, 1, "Connection not synchronized" },
  { 1, 2, "Bad message length" },
  { 1, 3, "Bad message type" },
  { 2, 0, "Invalid OPEN message" },
  { 2, 1, "Unsupported version number" },
  { 2, 2, "Bad peer AS" },
  { 2, 3, "Bad BGP identifier" },
  { 2, 4, "Unsupported optional parameter" },
  { 2, 5, "Authentication failure" },
  { 2, 6, "Unacceptable hold time" },
1442
  { 2, 7, "Required capability missing" }, /* [RFC5492] */
1443
  { 2, 8, "No supported AFI/SAFI" }, /* This error msg is nonstandard */
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
  { 3, 0, "Invalid UPDATE message" },
  { 3, 1, "Malformed attribute list" },
  { 3, 2, "Unrecognized well-known attribute" },
  { 3, 3, "Missing mandatory attribute" },
  { 3, 4, "Invalid attribute flags" },
  { 3, 5, "Invalid attribute length" },
  { 3, 6, "Invalid ORIGIN attribute" },
  { 3, 7, "AS routing loop" },		/* Deprecated */
  { 3, 8, "Invalid NEXT_HOP attribute" },
  { 3, 9, "Optional attribute error" },
  { 3, 10, "Invalid network field" },
  { 3, 11, "Malformed AS_PATH" },
  { 4, 0, "Hold timer expired" },
1457 1458 1459 1460
  { 5, 0, "Finite state machine error" }, /* Subcodes are according to [RFC6608] */
  { 5, 1, "Unexpected message in OpenSent state" },
  { 5, 2, "Unexpected message in OpenConfirm state" },
  { 5, 3, "Unexpected message in Established state" },
1461 1462 1463 1464 1465 1466 1467 1468
  { 6, 0, "Cease" }, /* Subcodes are according to [RFC4486] */
  { 6, 1, "Maximum number of prefixes reached" },
  { 6, 2, "Administrative shutdown" },
  { 6, 3, "Peer de-configured" },
  { 6, 4, "Administrative reset" },
  { 6, 5, "Connection rejected" },
  { 6, 6, "Other configuration change" },
  { 6, 7, "Connection collision resolution" },
1469 1470 1471
  { 6, 8, "Out of Resources" },
  { 7, 0, "Invalid ROUTE-REFRESH message" }, /* [RFC7313] */
  { 7, 1, "Invalid ROUTE-REFRESH message length" } /* [RFC7313] */
1472