]> git.ipfire.org Git - thirdparty/bird.git/blob - proto/bgp/attrs.c
Finalize RA_ACCEPTED handling.
[thirdparty/bird.git] / proto / bgp / attrs.c
1 /*
2 * BIRD -- BGP Attributes
3 *
4 * (c) 2000 Martin Mares <mj@ucw.cz>
5 *
6 * Can be freely distributed and used under the terms of the GNU GPL.
7 */
8
9 #undef LOCAL_DEBUG
10
11 #include <stdlib.h>
12
13 #include "nest/bird.h"
14 #include "nest/iface.h"
15 #include "nest/protocol.h"
16 #include "nest/route.h"
17 #include "nest/attrs.h"
18 #include "conf/conf.h"
19 #include "lib/resource.h"
20 #include "lib/string.h"
21 #include "lib/unaligned.h"
22
23 #include "bgp.h"
24
25 /*
26 * UPDATE message error handling
27 *
28 * All checks from RFC 4271 6.3 are done as specified with these exceptions:
29 * - The semantic check of an IP address from NEXT_HOP attribute is missing.
30 * - Checks of some optional attribute values are missing.
31 * - Syntactic and semantic checks of NLRIs (done in DECODE_PREFIX())
32 * are probably inadequate.
33 *
34 * Loop detection based on AS_PATH causes updates to be withdrawn. RFC
35 * 4271 does not explicitly specifiy the behavior in that case.
36 *
37 * Loop detection related to route reflection (based on ORIGINATOR_ID
38 * and CLUSTER_LIST) causes updates to be withdrawn. RFC 4456 8
39 * specifies that such updates should be ignored, but that is generally
40 * a bad idea.
41 *
42 * Error checking of optional transitive attributes is done according to
43 * draft-ietf-idr-optional-transitive-03, but errors are handled always
44 * as withdraws.
45 *
46 * Unexpected AS_CONFED_* segments in AS_PATH are logged and removed,
47 * but unknown segments cause a session drop with Malformed AS_PATH
48 * error (see validate_path()). The behavior in such case is not
49 * explicitly specified by RFC 4271. RFC 5065 specifies that
50 * inconsistent AS_CONFED_* segments should cause a session drop, but
51 * implementations that pass invalid AS_CONFED_* segments are
52 * widespread.
53 *
54 * Error handling of AS4_* attributes is done as specified by
55 * draft-ietf-idr-rfc4893bis-03. There are several possible
56 * inconsistencies between AGGREGATOR and AS4_AGGREGATOR that are not
57 * handled by that draft, these are logged and ignored (see
58 * bgp_reconstruct_4b_attrs()).
59 */
60
61 static byte bgp_mandatory_attrs[] = { BA_ORIGIN, BA_AS_PATH
62 #ifndef IPV6
63 ,BA_NEXT_HOP
64 #endif
65 };
66
67 struct attr_desc {
68 char *name;
69 int expected_length;
70 int expected_flags;
71 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 #define IGNORE -1
78 #define WITHDRAW -2
79
80 static int
81 bgp_check_origin(struct bgp_proto *p UNUSED, byte *a, int len UNUSED)
82 {
83 if (*a > 2)
84 return 6;
85 return 0;
86 }
87
88 static void
89 bgp_format_origin(eattr *a, byte *buf, int buflen UNUSED)
90 {
91 static char *bgp_origin_names[] = { "IGP", "EGP", "Incomplete" };
92
93 bsprintf(buf, bgp_origin_names[a->u.data]);
94 }
95
96 static int
97 path_segment_contains(byte *p, int bs, u32 asn)
98 {
99 int i;
100 int len = p[1];
101 p += 2;
102
103 for(i=0; i<len; i++)
104 {
105 u32 asn2 = (bs == 4) ? get_u32(p) : get_u16(p);
106 if (asn2 == asn)
107 return 1;
108 p += bs;
109 }
110
111 return 0;
112 }
113
114 /* Validates path attribute, removes AS_CONFED_* segments, and also returns path length */
115 static int
116 validate_path(struct bgp_proto *p, int as_path, int bs, byte *idata, unsigned int *ilength)
117 {
118 int res = 0;
119 u8 *a, *dst;
120 int len, plen, copy;
121
122 dst = a = idata;
123 len = *ilength;
124
125 while (len)
126 {
127 if (len < 2)
128 return -1;
129
130 plen = 2 + bs * a[1];
131 if (len < plen)
132 return -1;
133
134 switch (a[0])
135 {
136 case AS_PATH_SET:
137 copy = 1;
138 res++;
139 break;
140
141 case AS_PATH_SEQUENCE:
142 copy = 1;
143 res += a[1];
144 break;
145
146 case AS_PATH_CONFED_SEQUENCE:
147 case AS_PATH_CONFED_SET:
148 if (as_path && path_segment_contains(a, bs, p->remote_as))
149 {
150 log(L_WARN "%s: AS_CONFED_* segment with peer ASN found, misconfigured confederation?", p->p.name);
151 return -1;
152 }
153
154 log(L_WARN "%s: %s_PATH attribute contains AS_CONFED_* segment, skipping segment",
155 p->p.name, as_path ? "AS" : "AS4");
156 copy = 0;
157 break;
158
159 default:
160 return -1;
161 }
162
163 if (copy)
164 {
165 if (dst != a)
166 memmove(dst, a, plen);
167 dst += plen;
168 }
169
170 len -= plen;
171 a += plen;
172 }
173
174 *ilength = dst - idata;
175 return res;
176 }
177
178 static inline int
179 validate_as_path(struct bgp_proto *p, byte *a, int *len)
180 {
181 return validate_path(p, 1, p->as4_session ? 4 : 2, a, len);
182 }
183
184 static inline int
185 validate_as4_path(struct bgp_proto *p, struct adata *path)
186 {
187 return validate_path(p, 0, 4, path->data, &path->length);
188 }
189
190 static int
191 bgp_check_next_hop(struct bgp_proto *p UNUSED, byte *a, int len)
192 {
193 #ifdef IPV6
194 return IGNORE;
195 #else
196 ip_addr addr;
197
198 memcpy(&addr, a, len);
199 ipa_ntoh(addr);
200 if (ipa_classify(addr) & IADDR_HOST)
201 return 0;
202 else
203 return 8;
204 #endif
205 }
206
207 static void
208 bgp_format_next_hop(eattr *a, byte *buf, int buflen UNUSED)
209 {
210 ip_addr *ipp = (ip_addr *) a->u.ptr->data;
211 #ifdef IPV6
212 /* in IPv6, we might have two addresses in NEXT HOP */
213 if ((a->u.ptr->length == NEXT_HOP_LENGTH) && ipa_nonzero(ipp[1]))
214 {
215 bsprintf(buf, "%I %I", ipp[0], ipp[1]);
216 return;
217 }
218 #endif
219
220 bsprintf(buf, "%I", ipp[0]);
221 }
222
223 static int
224 bgp_check_aggregator(struct bgp_proto *p, byte *a UNUSED, int len)
225 {
226 int exp_len = p->as4_session ? 8 : 6;
227
228 return (len == exp_len) ? 0 : WITHDRAW;
229 }
230
231 static void
232 bgp_format_aggregator(eattr *a, byte *buf, int buflen UNUSED)
233 {
234 struct adata *ad = a->u.ptr;
235 byte *data = ad->data;
236 u32 as;
237
238 as = get_u32(data);
239 data += 4;
240
241 bsprintf(buf, "%d.%d.%d.%d AS%d", data[0], data[1], data[2], data[3], as);
242 }
243
244 static int
245 bgp_check_community(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
246 {
247 return ((len % 4) == 0) ? 0 : WITHDRAW;
248 }
249
250 static int
251 bgp_check_cluster_list(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
252 {
253 return ((len % 4) == 0) ? 0 : 5;
254 }
255
256 static void
257 bgp_format_cluster_list(eattr *a, byte *buf, int buflen)
258 {
259 /* Truncates cluster lists larger than buflen, probably not a problem */
260 int_set_format(a->u.ptr, 0, -1, buf, buflen);
261 }
262
263 static int
264 bgp_check_reach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
265 {
266 #ifdef IPV6
267 p->mp_reach_start = a;
268 p->mp_reach_len = len;
269 #endif
270 return IGNORE;
271 }
272
273 static int
274 bgp_check_unreach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
275 {
276 #ifdef IPV6
277 p->mp_unreach_start = a;
278 p->mp_unreach_len = len;
279 #endif
280 return IGNORE;
281 }
282
283 static int
284 bgp_check_ext_community(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
285 {
286 return ((len % 8) == 0) ? 0 : WITHDRAW;
287 }
288
289
290 static struct attr_desc bgp_attr_table[] = {
291 { NULL, -1, 0, 0, 0, /* Undefined */
292 NULL, NULL },
293 { "origin", 1, BAF_TRANSITIVE, EAF_TYPE_INT, 1, /* BA_ORIGIN */
294 bgp_check_origin, bgp_format_origin },
295 { "as_path", -1, BAF_TRANSITIVE, EAF_TYPE_AS_PATH, 1, /* BA_AS_PATH */
296 NULL, NULL }, /* is checked by validate_as_path() as a special case */
297 { "next_hop", 4, BAF_TRANSITIVE, EAF_TYPE_IP_ADDRESS, 1, /* BA_NEXT_HOP */
298 bgp_check_next_hop, bgp_format_next_hop },
299 { "med", 4, BAF_OPTIONAL, EAF_TYPE_INT, 1, /* BA_MULTI_EXIT_DISC */
300 NULL, NULL },
301 { "local_pref", 4, BAF_TRANSITIVE, EAF_TYPE_INT, 0, /* BA_LOCAL_PREF */
302 NULL, NULL },
303 { "atomic_aggr", 0, BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_ATOMIC_AGGR */
304 NULL, NULL },
305 { "aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_AGGREGATOR */
306 bgp_check_aggregator, bgp_format_aggregator },
307 { "community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_INT_SET, 1, /* BA_COMMUNITY */
308 bgp_check_community, NULL },
309 { "originator_id", 4, BAF_OPTIONAL, EAF_TYPE_ROUTER_ID, 0, /* BA_ORIGINATOR_ID */
310 NULL, NULL },
311 { "cluster_list", -1, BAF_OPTIONAL, EAF_TYPE_INT_SET, 0, /* BA_CLUSTER_LIST */
312 bgp_check_cluster_list, bgp_format_cluster_list },
313 { .name = NULL }, /* BA_DPA */
314 { .name = NULL }, /* BA_ADVERTISER */
315 { .name = NULL }, /* BA_RCID_PATH */
316 { "mp_reach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1, /* BA_MP_REACH_NLRI */
317 bgp_check_reach_nlri, NULL },
318 { "mp_unreach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1, /* BA_MP_UNREACH_NLRI */
319 bgp_check_unreach_nlri, NULL },
320 { "ext_community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_EC_SET, 1, /* BA_EXT_COMMUNITY */
321 bgp_check_ext_community, NULL },
322 { "as4_path", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_AS4_PATH */
323 NULL, NULL },
324 { "as4_aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_AS4_PATH */
325 NULL, NULL }
326 };
327
328 /* BA_AS4_PATH is type EAF_TYPE_OPAQUE and not type EAF_TYPE_AS_PATH.
329 * It does not matter as this attribute does not appear on routes in the routing table.
330 */
331
332 #define ATTR_KNOWN(code) ((code) < ARRAY_SIZE(bgp_attr_table) && bgp_attr_table[code].name)
333
334 static inline struct adata *
335 bgp_alloc_adata(struct linpool *pool, unsigned len)
336 {
337 struct adata *ad = lp_alloc(pool, sizeof(struct adata) + len);
338 ad->length = len;
339 return ad;
340 }
341
342 static void
343 bgp_set_attr(eattr *e, unsigned attr, uintptr_t val)
344 {
345 ASSERT(ATTR_KNOWN(attr));
346 e->id = EA_CODE(EAP_BGP, attr);
347 e->type = bgp_attr_table[attr].type;
348 e->flags = bgp_attr_table[attr].expected_flags;
349 if (e->type & EAF_EMBEDDED)
350 e->u.data = val;
351 else
352 e->u.ptr = (struct adata *) val;
353 }
354
355 static byte *
356 bgp_set_attr_wa(eattr *e, struct linpool *pool, unsigned attr, unsigned len)
357 {
358 struct adata *ad = bgp_alloc_adata(pool, len);
359 bgp_set_attr(e, attr, (uintptr_t) ad);
360 return ad->data;
361 }
362
363 void
364 bgp_attach_attr(ea_list **to, struct linpool *pool, unsigned attr, uintptr_t val)
365 {
366 ea_list *a = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
367 a->next = *to;
368 *to = a;
369 a->flags = EALF_SORTED;
370 a->count = 1;
371 bgp_set_attr(a->attrs, attr, val);
372 }
373
374 byte *
375 bgp_attach_attr_wa(ea_list **to, struct linpool *pool, unsigned attr, unsigned len)
376 {
377 struct adata *ad = bgp_alloc_adata(pool, len);
378 bgp_attach_attr(to, pool, attr, (uintptr_t) ad);
379 return ad->data;
380 }
381
382 static int
383 bgp_encode_attr_hdr(byte *dst, unsigned int flags, unsigned code, int len)
384 {
385 int wlen;
386
387 DBG("\tAttribute %02x (%d bytes, flags %02x)\n", code, len, flags);
388
389 if (len < 256)
390 {
391 *dst++ = flags;
392 *dst++ = code;
393 *dst++ = len;
394 wlen = 3;
395 }
396 else
397 {
398 *dst++ = flags | BAF_EXT_LEN;
399 *dst++ = code;
400 put_u16(dst, len);
401 wlen = 4;
402 }
403
404 return wlen;
405 }
406
407 static void
408 aggregator_convert_to_old(struct adata *aggr, byte *dst, int *new_used)
409 {
410 byte *src = aggr->data;
411 *new_used = 0;
412
413 u32 as = get_u32(src);
414 if (as > 0xFFFF)
415 {
416 as = AS_TRANS;
417 *new_used = 1;
418 }
419 put_u16(dst, as);
420
421 /* Copy IPv4 address */
422 memcpy(dst + 2, src + 4, 4);
423 }
424
425 static void
426 aggregator_convert_to_new(struct adata *aggr, byte *dst)
427 {
428 byte *src = aggr->data;
429
430 u32 as = get_u16(src);
431 put_u32(dst, as);
432
433 /* Copy IPv4 address */
434 memcpy(dst + 4, src + 2, 4);
435 }
436
437 static int
438 bgp_get_attr_len(eattr *a)
439 {
440 int len;
441 if (ATTR_KNOWN(EA_ID(a->id)))
442 {
443 int code = EA_ID(a->id);
444 struct attr_desc *desc = &bgp_attr_table[code];
445 len = desc->expected_length;
446 if (len < 0)
447 {
448 ASSERT(!(a->type & EAF_EMBEDDED));
449 len = a->u.ptr->length;
450 }
451 }
452 else
453 {
454 ASSERT((a->type & EAF_TYPE_MASK) == EAF_TYPE_OPAQUE);
455 len = a->u.ptr->length;
456 }
457
458 return len;
459 }
460
461 #define ADVANCE(w, r, l) do { r -= l; w += l; } while (0)
462
463 /**
464 * bgp_encode_attrs - encode BGP attributes
465 * @p: BGP instance
466 * @w: buffer
467 * @attrs: a list of extended attributes
468 * @remains: remaining space in the buffer
469 *
470 * The bgp_encode_attrs() function takes a list of extended attributes
471 * and converts it to its BGP representation (a part of an Update message).
472 *
473 * Result: Length of the attribute block generated or -1 if not enough space.
474 */
475 unsigned int
476 bgp_encode_attrs(struct bgp_proto *p, byte *w, ea_list *attrs, int remains)
477 {
478 unsigned int i, code, type, flags;
479 byte *start = w;
480 int len, rv;
481
482 for(i=0; i<attrs->count; i++)
483 {
484 eattr *a = &attrs->attrs[i];
485 ASSERT(EA_PROTO(a->id) == EAP_BGP);
486 code = EA_ID(a->id);
487
488 #ifdef IPV6
489 /* When talking multiprotocol BGP, the NEXT_HOP attributes are used only temporarily. */
490 if (code == BA_NEXT_HOP)
491 continue;
492 #endif
493
494 /* When AS4-aware BGP speaker is talking to non-AS4-aware BGP speaker,
495 * we have to convert our 4B AS_PATH to 2B AS_PATH and send our AS_PATH
496 * as optional AS4_PATH attribute.
497 */
498 if ((code == BA_AS_PATH) && (! p->as4_session))
499 {
500 len = a->u.ptr->length;
501
502 if (remains < (len + 4))
503 goto err_no_buffer;
504
505 /* Using temporary buffer because don't know a length of created attr
506 * and therefore a length of a header. Perhaps i should better always
507 * use BAF_EXT_LEN. */
508
509 byte buf[len];
510 int new_used;
511 int nl = as_path_convert_to_old(a->u.ptr, buf, &new_used);
512
513 DBG("BGP: Encoding old AS_PATH\n");
514 rv = bgp_encode_attr_hdr(w, BAF_TRANSITIVE, BA_AS_PATH, nl);
515 ADVANCE(w, remains, rv);
516 memcpy(w, buf, nl);
517 ADVANCE(w, remains, nl);
518
519 if (! new_used)
520 continue;
521
522 if (remains < (len + 4))
523 goto err_no_buffer;
524
525 /* We should discard AS_CONFED_SEQUENCE or AS_CONFED_SET path segments
526 * here but we don't support confederations and such paths we already
527 * discarded in bgp_check_as_path().
528 */
529
530 DBG("BGP: Encoding AS4_PATH\n");
531 rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AS4_PATH, len);
532 ADVANCE(w, remains, rv);
533 memcpy(w, a->u.ptr->data, len);
534 ADVANCE(w, remains, len);
535
536 continue;
537 }
538
539 /* The same issue with AGGREGATOR attribute */
540 if ((code == BA_AGGREGATOR) && (! p->as4_session))
541 {
542 int new_used;
543
544 len = 6;
545 if (remains < (len + 3))
546 goto err_no_buffer;
547
548 rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AGGREGATOR, len);
549 ADVANCE(w, remains, rv);
550 aggregator_convert_to_old(a->u.ptr, w, &new_used);
551 ADVANCE(w, remains, len);
552
553 if (! new_used)
554 continue;
555
556 len = 8;
557 if (remains < (len + 3))
558 goto err_no_buffer;
559
560 rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AS4_AGGREGATOR, len);
561 ADVANCE(w, remains, rv);
562 memcpy(w, a->u.ptr->data, len);
563 ADVANCE(w, remains, len);
564
565 continue;
566 }
567
568 /* Standard path continues here ... */
569
570 type = a->type & EAF_TYPE_MASK;
571 flags = a->flags & (BAF_OPTIONAL | BAF_TRANSITIVE | BAF_PARTIAL);
572 len = bgp_get_attr_len(a);
573
574 /* Skip empty sets */
575 if (((type == EAF_TYPE_INT_SET) || (type == EAF_TYPE_EC_SET)) && (len == 0))
576 continue;
577
578 if (remains < len + 4)
579 goto err_no_buffer;
580
581 rv = bgp_encode_attr_hdr(w, flags, code, len);
582 ADVANCE(w, remains, rv);
583
584 switch (type)
585 {
586 case EAF_TYPE_INT:
587 case EAF_TYPE_ROUTER_ID:
588 if (len == 4)
589 put_u32(w, a->u.data);
590 else
591 *w = a->u.data;
592 break;
593 case EAF_TYPE_IP_ADDRESS:
594 {
595 ip_addr ip = *(ip_addr *)a->u.ptr->data;
596 ipa_hton(ip);
597 memcpy(w, &ip, len);
598 break;
599 }
600 case EAF_TYPE_INT_SET:
601 case EAF_TYPE_EC_SET:
602 {
603 u32 *z = int_set_get_data(a->u.ptr);
604 int i;
605 for(i=0; i<len; i+=4)
606 put_u32(w+i, *z++);
607 break;
608 }
609 case EAF_TYPE_OPAQUE:
610 case EAF_TYPE_AS_PATH:
611 memcpy(w, a->u.ptr->data, len);
612 break;
613 default:
614 bug("bgp_encode_attrs: unknown attribute type %02x", a->type);
615 }
616 ADVANCE(w, remains, len);
617 }
618 return w - start;
619
620 err_no_buffer:
621 return -1;
622 }
623
624 static void
625 bgp_init_prefix(struct fib_node *N)
626 {
627 struct bgp_prefix *p = (struct bgp_prefix *) N;
628 p->bucket_node.next = NULL;
629 }
630
631 static int
632 bgp_compare_u32(const u32 *x, const u32 *y)
633 {
634 return (*x < *y) ? -1 : (*x > *y) ? 1 : 0;
635 }
636
637 static inline void
638 bgp_normalize_int_set(u32 *dest, u32 *src, unsigned cnt)
639 {
640 memcpy(dest, src, sizeof(u32) * cnt);
641 qsort(dest, cnt, sizeof(u32), (int(*)(const void *, const void *)) bgp_compare_u32);
642 }
643
644 static int
645 bgp_compare_ec(const u32 *xp, const u32 *yp)
646 {
647 u64 x = ec_get(xp, 0);
648 u64 y = ec_get(yp, 0);
649 return (x < y) ? -1 : (x > y) ? 1 : 0;
650 }
651
652 static inline void
653 bgp_normalize_ec_set(struct adata *ad, u32 *src, int internal)
654 {
655 u32 *dst = int_set_get_data(ad);
656
657 /* Remove non-transitive communities (EC_TBIT active) on external sessions */
658 if (! internal)
659 {
660 int len = int_set_get_size(ad);
661 u32 *t = dst;
662 int i;
663
664 for (i=0; i < len; i += 2)
665 {
666 if (src[i] & EC_TBIT)
667 continue;
668
669 *t++ = src[i];
670 *t++ = src[i+1];
671 }
672
673 ad->length = (t - dst) * 4;
674 }
675 else
676 memcpy(dst, src, ad->length);
677
678 qsort(dst, ad->length / 8, 8, (int(*)(const void *, const void *)) bgp_compare_ec);
679 }
680
681 static void
682 bgp_rehash_buckets(struct bgp_proto *p)
683 {
684 struct bgp_bucket **old = p->bucket_hash;
685 struct bgp_bucket **new;
686 unsigned oldn = p->hash_size;
687 unsigned i, e, mask;
688 struct bgp_bucket *b;
689
690 p->hash_size = p->hash_limit;
691 DBG("BGP: Rehashing bucket table from %d to %d\n", oldn, p->hash_size);
692 p->hash_limit *= 4;
693 if (p->hash_limit >= 65536)
694 p->hash_limit = ~0;
695 new = p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
696 mask = p->hash_size - 1;
697 for (i=0; i<oldn; i++)
698 while (b = old[i])
699 {
700 old[i] = b->hash_next;
701 e = b->hash & mask;
702 b->hash_next = new[e];
703 if (b->hash_next)
704 b->hash_next->hash_prev = b;
705 b->hash_prev = NULL;
706 new[e] = b;
707 }
708 mb_free(old);
709 }
710
711 static struct bgp_bucket *
712 bgp_new_bucket(struct bgp_proto *p, ea_list *new, unsigned hash)
713 {
714 struct bgp_bucket *b;
715 unsigned ea_size = sizeof(ea_list) + new->count * sizeof(eattr);
716 unsigned ea_size_aligned = BIRD_ALIGN(ea_size, CPU_STRUCT_ALIGN);
717 unsigned size = sizeof(struct bgp_bucket) + ea_size;
718 unsigned i;
719 byte *dest;
720 unsigned index = hash & (p->hash_size - 1);
721
722 /* Gather total size of non-inline attributes */
723 for (i=0; i<new->count; i++)
724 {
725 eattr *a = &new->attrs[i];
726 if (!(a->type & EAF_EMBEDDED))
727 size += BIRD_ALIGN(sizeof(struct adata) + a->u.ptr->length, CPU_STRUCT_ALIGN);
728 }
729
730 /* Create the bucket and hash it */
731 b = mb_alloc(p->p.pool, size);
732 b->hash_next = p->bucket_hash[index];
733 if (b->hash_next)
734 b->hash_next->hash_prev = b;
735 p->bucket_hash[index] = b;
736 b->hash_prev = NULL;
737 b->hash = hash;
738 add_tail(&p->bucket_queue, &b->send_node);
739 init_list(&b->prefixes);
740 memcpy(b->eattrs, new, ea_size);
741 dest = ((byte *)b->eattrs) + ea_size_aligned;
742
743 /* Copy values of non-inline attributes */
744 for (i=0; i<new->count; i++)
745 {
746 eattr *a = &b->eattrs->attrs[i];
747 if (!(a->type & EAF_EMBEDDED))
748 {
749 struct adata *oa = a->u.ptr;
750 struct adata *na = (struct adata *) dest;
751 memcpy(na, oa, sizeof(struct adata) + oa->length);
752 a->u.ptr = na;
753 dest += BIRD_ALIGN(sizeof(struct adata) + na->length, CPU_STRUCT_ALIGN);
754 }
755 }
756
757 /* If needed, rehash */
758 p->hash_count++;
759 if (p->hash_count > p->hash_limit)
760 bgp_rehash_buckets(p);
761
762 return b;
763 }
764
765 static struct bgp_bucket *
766 bgp_get_bucket(struct bgp_proto *p, net *n, ea_list *attrs, int originate)
767 {
768 ea_list *new;
769 unsigned i, cnt, hash, code;
770 eattr *a, *d;
771 u32 seen = 0;
772 struct bgp_bucket *b;
773
774 /* Merge the attribute list */
775 new = alloca(ea_scan(attrs));
776 ea_merge(attrs, new);
777 ea_sort(new);
778
779 /* Normalize attributes */
780 d = new->attrs;
781 cnt = new->count;
782 new->count = 0;
783 for(i=0; i<cnt; i++)
784 {
785 a = &new->attrs[i];
786 if (EA_PROTO(a->id) != EAP_BGP)
787 continue;
788 code = EA_ID(a->id);
789 if (ATTR_KNOWN(code))
790 {
791 if (!bgp_attr_table[code].allow_in_ebgp && !p->is_internal)
792 continue;
793 /* The flags might have been zero if the attr was added by filters */
794 a->flags = (a->flags & BAF_PARTIAL) | bgp_attr_table[code].expected_flags;
795 if (code < 32)
796 seen |= 1 << code;
797 }
798 else
799 {
800 /* Don't re-export unknown non-transitive attributes */
801 if (!(a->flags & BAF_TRANSITIVE))
802 continue;
803 }
804 *d = *a;
805 if ((d->type & EAF_ORIGINATED) && !originate && (d->flags & BAF_TRANSITIVE) && (d->flags & BAF_OPTIONAL))
806 d->flags |= BAF_PARTIAL;
807 switch (d->type & EAF_TYPE_MASK)
808 {
809 case EAF_TYPE_INT_SET:
810 {
811 struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
812 z->length = d->u.ptr->length;
813 bgp_normalize_int_set((u32 *) z->data, (u32 *) d->u.ptr->data, z->length / 4);
814 d->u.ptr = z;
815 break;
816 }
817 case EAF_TYPE_EC_SET:
818 {
819 struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
820 z->length = d->u.ptr->length;
821 bgp_normalize_ec_set(z, (u32 *) d->u.ptr->data, p->is_internal);
822 d->u.ptr = z;
823 break;
824 }
825 default: ;
826 }
827 d++;
828 new->count++;
829 }
830
831 /* Hash */
832 hash = ea_hash(new);
833 for(b=p->bucket_hash[hash & (p->hash_size - 1)]; b; b=b->hash_next)
834 if (b->hash == hash && ea_same(b->eattrs, new))
835 {
836 DBG("Found bucket.\n");
837 return b;
838 }
839
840 /* Ensure that there are all mandatory attributes */
841 for(i=0; i<ARRAY_SIZE(bgp_mandatory_attrs); i++)
842 if (!(seen & (1 << bgp_mandatory_attrs[i])))
843 {
844 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);
845 return NULL;
846 }
847
848 /* Check if next hop is valid */
849 a = ea_find(new, EA_CODE(EAP_BGP, BA_NEXT_HOP));
850 if (!a || ipa_equal(p->cf->remote_ip, *(ip_addr *)a->u.ptr->data))
851 {
852 log(L_ERR "%s: Invalid NEXT_HOP attribute in route %I/%d", p->p.name, n->n.prefix, n->n.pxlen);
853 return NULL;
854 }
855
856 /* Create new bucket */
857 DBG("Creating bucket.\n");
858 return bgp_new_bucket(p, new, hash);
859 }
860
861 void
862 bgp_free_bucket(struct bgp_proto *p, struct bgp_bucket *buck)
863 {
864 if (buck->hash_next)
865 buck->hash_next->hash_prev = buck->hash_prev;
866 if (buck->hash_prev)
867 buck->hash_prev->hash_next = buck->hash_next;
868 else
869 p->bucket_hash[buck->hash & (p->hash_size-1)] = buck->hash_next;
870 mb_free(buck);
871 }
872
873 void
874 bgp_rt_notify(struct proto *P, rtable *tbl UNUSED, net *n, rte *new, rte *old UNUSED, ea_list *attrs)
875 {
876 struct bgp_proto *p = (struct bgp_proto *) P;
877 struct bgp_bucket *buck;
878 struct bgp_prefix *px;
879
880 DBG("BGP: Got route %I/%d %s\n", n->n.prefix, n->n.pxlen, new ? "up" : "down");
881
882 if (new)
883 {
884 buck = bgp_get_bucket(p, n, attrs, new->attrs->source != RTS_BGP);
885 if (!buck) /* Inconsistent attribute list */
886 return;
887 }
888 else
889 {
890 if (!(buck = p->withdraw_bucket))
891 {
892 buck = p->withdraw_bucket = mb_alloc(P->pool, sizeof(struct bgp_bucket));
893 init_list(&buck->prefixes);
894 }
895 }
896 px = fib_get(&p->prefix_fib, &n->n.prefix, n->n.pxlen);
897 if (px->bucket_node.next)
898 {
899 DBG("\tRemoving old entry.\n");
900 rem_node(&px->bucket_node);
901 }
902 add_tail(&buck->prefixes, &px->bucket_node);
903 bgp_schedule_packet(p->conn, PKT_UPDATE);
904 }
905
906 static int
907 bgp_create_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool)
908 {
909 ea_list *ea = lp_alloc(pool, sizeof(ea_list) + 4*sizeof(eattr));
910 rta *rta = e->attrs;
911 byte *z;
912
913 ea->next = *attrs;
914 *attrs = ea;
915 ea->flags = EALF_SORTED;
916 ea->count = 4;
917
918 bgp_set_attr(ea->attrs, BA_ORIGIN,
919 ((rta->source == RTS_OSPF_EXT1) || (rta->source == RTS_OSPF_EXT2)) ? ORIGIN_INCOMPLETE : ORIGIN_IGP);
920
921 if (p->is_internal)
922 bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 0);
923 else
924 {
925 z = bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 6);
926 z[0] = AS_PATH_SEQUENCE;
927 z[1] = 1; /* 1 AS */
928 put_u32(z+2, p->local_as);
929 }
930
931 /* iBGP -> use gw, eBGP multi-hop -> use source_addr,
932 eBGP single-hop -> use gw if on the same iface */
933 z = bgp_set_attr_wa(ea->attrs+2, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
934 if (p->cf->next_hop_self ||
935 rta->dest != RTD_ROUTER ||
936 ipa_equal(rta->gw, IPA_NONE) ||
937 ipa_has_link_scope(rta->gw) ||
938 (!p->is_internal && (!p->neigh || (rta->iface != p->neigh->iface))))
939 set_next_hop(z, p->source_addr);
940 else
941 set_next_hop(z, rta->gw);
942
943 bgp_set_attr(ea->attrs+3, BA_LOCAL_PREF, p->cf->default_local_pref);
944
945 return 0; /* Leave decision to the filters */
946 }
947
948
949 static inline int
950 bgp_as_path_loopy(struct bgp_proto *p, rta *a)
951 {
952 eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
953 return (e && as_path_is_member(e->u.ptr, p->local_as));
954 }
955
956 static inline int
957 bgp_originator_id_loopy(struct bgp_proto *p, rta *a)
958 {
959 eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
960 return (e && (e->u.data == p->local_id));
961 }
962
963 static inline int
964 bgp_cluster_list_loopy(struct bgp_proto *p, rta *a)
965 {
966 eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
967 return (e && p->rr_client && int_set_contains(e->u.ptr, p->rr_cluster_id));
968 }
969
970
971 static inline void
972 bgp_path_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 as)
973 {
974 eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
975 bgp_attach_attr(attrs, pool, BA_AS_PATH, (uintptr_t) as_path_prepend(pool, a->u.ptr, as));
976 }
977
978 static inline void
979 bgp_cluster_list_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 cid)
980 {
981 eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
982 bgp_attach_attr(attrs, pool, BA_CLUSTER_LIST, (uintptr_t) int_set_add(pool, a ? a->u.ptr : NULL, cid));
983 }
984
985 static int
986 bgp_update_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool, int rr)
987 {
988 eattr *a;
989
990 if (!p->is_internal && !p->rs_client)
991 {
992 bgp_path_prepend(e, attrs, pool, p->local_as);
993
994 /* The MULTI_EXIT_DISC attribute received from a neighboring AS MUST NOT be
995 * propagated to other neighboring ASes.
996 * Perhaps it would be better to undefine it.
997 */
998 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
999 if (a)
1000 bgp_attach_attr(attrs, pool, BA_MULTI_EXIT_DISC, 0);
1001 }
1002
1003 /* iBGP -> keep next_hop, eBGP multi-hop -> use source_addr,
1004 * eBGP single-hop -> keep next_hop if on the same iface.
1005 * If the next_hop is zero (i.e. link-local), keep only if on the same iface.
1006 */
1007 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
1008 if (a && !p->cf->next_hop_self &&
1009 ((p->is_internal && ipa_nonzero(*((ip_addr *) a->u.ptr->data))) ||
1010 (p->neigh && (e->attrs->iface == p->neigh->iface))))
1011 {
1012 /* Leave the original next hop attribute, will check later where does it point */
1013 }
1014 else
1015 {
1016 /* Need to create new one */
1017 byte *b = bgp_attach_attr_wa(attrs, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
1018 set_next_hop(b, p->source_addr);
1019 }
1020
1021 if (rr)
1022 {
1023 /* Handling route reflection, RFC 4456 */
1024 struct bgp_proto *src = (struct bgp_proto *) e->attrs->proto;
1025
1026 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1027 if (!a)
1028 bgp_attach_attr(attrs, pool, BA_ORIGINATOR_ID, src->remote_id);
1029
1030 /* We attach proper cluster ID according to whether the route is entering or leaving the cluster */
1031 bgp_cluster_list_prepend(e, attrs, pool, src->rr_client ? src->rr_cluster_id : p->rr_cluster_id);
1032
1033 /* Two RR clients with different cluster ID, hmmm */
1034 if (src->rr_client && p->rr_client && (src->rr_cluster_id != p->rr_cluster_id))
1035 bgp_cluster_list_prepend(e, attrs, pool, p->rr_cluster_id);
1036 }
1037
1038 return 0; /* Leave decision to the filters */
1039 }
1040
1041 static int
1042 bgp_community_filter(struct bgp_proto *p, rte *e)
1043 {
1044 eattr *a;
1045 struct adata *d;
1046
1047 /* Check if we aren't forbidden to export the route by communities */
1048 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_COMMUNITY));
1049 if (a)
1050 {
1051 d = a->u.ptr;
1052 if (int_set_contains(d, BGP_COMM_NO_ADVERTISE))
1053 {
1054 DBG("\tNO_ADVERTISE\n");
1055 return 1;
1056 }
1057 if (!p->is_internal &&
1058 (int_set_contains(d, BGP_COMM_NO_EXPORT) ||
1059 int_set_contains(d, BGP_COMM_NO_EXPORT_SUBCONFED)))
1060 {
1061 DBG("\tNO_EXPORT\n");
1062 return 1;
1063 }
1064 }
1065
1066 return 0;
1067 }
1068
1069 int
1070 bgp_import_control(struct proto *P, rte **new, ea_list **attrs, struct linpool *pool)
1071 {
1072 rte *e = *new;
1073 struct bgp_proto *p = (struct bgp_proto *) P;
1074 struct bgp_proto *new_bgp = (e->attrs->proto->proto == &proto_bgp) ? (struct bgp_proto *) e->attrs->proto : NULL;
1075
1076 if (p == new_bgp) /* Poison reverse updates */
1077 return -1;
1078 if (new_bgp)
1079 {
1080 /* We should check here for cluster list loop, because the receiving BGP instance
1081 might have different cluster ID */
1082 if (bgp_cluster_list_loopy(p, e->attrs))
1083 return -1;
1084
1085 if (p->cf->interpret_communities && bgp_community_filter(p, e))
1086 return -1;
1087
1088 if (p->local_as == new_bgp->local_as && p->is_internal && new_bgp->is_internal)
1089 {
1090 /* Redistribution of internal routes with IBGP */
1091 if (p->rr_client || new_bgp->rr_client)
1092 /* Route reflection, RFC 4456 */
1093 return bgp_update_attrs(p, e, attrs, pool, 1);
1094 else
1095 return -1;
1096 }
1097 else
1098 return bgp_update_attrs(p, e, attrs, pool, 0);
1099 }
1100 else
1101 return bgp_create_attrs(p, e, attrs, pool);
1102 }
1103
1104 static inline u32
1105 bgp_get_neighbor(rte *r)
1106 {
1107 eattr *e = ea_find(r->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1108 u32 as;
1109
1110 if (e && as_path_get_first(e->u.ptr, &as))
1111 return as;
1112 else
1113 return ((struct bgp_proto *) r->attrs->proto)->remote_as;
1114 }
1115
1116 static inline int
1117 rte_resolvable(rte *rt)
1118 {
1119 int rd = rt->attrs->dest;
1120 return (rd == RTD_ROUTER) || (rd == RTD_DEVICE) || (rd == RTD_MULTIPATH);
1121 }
1122
1123 int
1124 bgp_rte_better(rte *new, rte *old)
1125 {
1126 struct bgp_proto *new_bgp = (struct bgp_proto *) new->attrs->proto;
1127 struct bgp_proto *old_bgp = (struct bgp_proto *) old->attrs->proto;
1128 eattr *x, *y;
1129 u32 n, o;
1130
1131 /* Skip suppressed routes (see bgp_rte_recalculate()) */
1132 n = new->u.bgp.suppressed;
1133 o = old->u.bgp.suppressed;
1134 if (n > o)
1135 return 0;
1136 if (n < o)
1137 return 1;
1138
1139 /* RFC 4271 9.1.2.1. Route resolvability test */
1140 n = rte_resolvable(new);
1141 o = rte_resolvable(old);
1142 if (n > o)
1143 return 1;
1144 if (n < o)
1145 return 0;
1146
1147 /* Start with local preferences */
1148 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
1149 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
1150 n = x ? x->u.data : new_bgp->cf->default_local_pref;
1151 o = y ? y->u.data : old_bgp->cf->default_local_pref;
1152 if (n > o)
1153 return 1;
1154 if (n < o)
1155 return 0;
1156
1157 /* RFC 4271 9.1.2.2. a) Use AS path lengths */
1158 if (new_bgp->cf->compare_path_lengths || old_bgp->cf->compare_path_lengths)
1159 {
1160 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1161 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1162 n = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
1163 o = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
1164 if (n < o)
1165 return 1;
1166 if (n > o)
1167 return 0;
1168 }
1169
1170 /* RFC 4271 9.1.2.2. b) Use origins */
1171 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1172 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1173 n = x ? x->u.data : ORIGIN_INCOMPLETE;
1174 o = y ? y->u.data : ORIGIN_INCOMPLETE;
1175 if (n < o)
1176 return 1;
1177 if (n > o)
1178 return 0;
1179
1180 /* RFC 4271 9.1.2.2. c) Compare MED's */
1181 /* Proper RFC 4271 path selection cannot be interpreted as finding
1182 * the best path in some ordering. It is implemented partially in
1183 * bgp_rte_recalculate() when deterministic_med option is
1184 * active. Without that option, the behavior is just an
1185 * approximation, which in specific situations may lead to
1186 * persistent routing loops, because it is nondeterministic - it
1187 * depends on the order in which routes appeared. But it is also the
1188 * same behavior as used by default in Cisco routers, so it is
1189 * probably not a big issue.
1190 */
1191 if (new_bgp->cf->med_metric || old_bgp->cf->med_metric ||
1192 (bgp_get_neighbor(new) == bgp_get_neighbor(old)))
1193 {
1194 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
1195 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
1196 n = x ? x->u.data : new_bgp->cf->default_med;
1197 o = y ? y->u.data : old_bgp->cf->default_med;
1198 if (n < o)
1199 return 1;
1200 if (n > o)
1201 return 0;
1202 }
1203
1204 /* RFC 4271 9.1.2.2. d) Prefer external peers */
1205 if (new_bgp->is_internal > old_bgp->is_internal)
1206 return 0;
1207 if (new_bgp->is_internal < old_bgp->is_internal)
1208 return 1;
1209
1210 /* RFC 4271 9.1.2.2. e) Compare IGP metrics */
1211 n = new_bgp->cf->igp_metric ? new->attrs->igp_metric : 0;
1212 o = old_bgp->cf->igp_metric ? old->attrs->igp_metric : 0;
1213 if (n < o)
1214 return 1;
1215 if (n > o)
1216 return 0;
1217
1218 /* RFC 4271 9.1.2.2. f) Compare BGP identifiers */
1219 /* RFC 4456 9. a) Use ORIGINATOR_ID instead of local neighor ID */
1220 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1221 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1222 n = x ? x->u.data : new_bgp->remote_id;
1223 o = y ? y->u.data : old_bgp->remote_id;
1224
1225 /* RFC 5004 - prefer older routes */
1226 /* (if both are external and from different peer) */
1227 if ((new_bgp->cf->prefer_older || old_bgp->cf->prefer_older) &&
1228 !new_bgp->is_internal && n != o)
1229 return 0;
1230
1231 /* rest of RFC 4271 9.1.2.2. f) */
1232 if (n < o)
1233 return 1;
1234 if (n > o)
1235 return 0;
1236
1237 /* RFC 4456 9. b) Compare cluster list lengths */
1238 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
1239 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
1240 n = x ? int_set_get_size(x->u.ptr) : 0;
1241 o = y ? int_set_get_size(y->u.ptr) : 0;
1242 if (n < o)
1243 return 1;
1244 if (n > o)
1245 return 0;
1246
1247 /* RFC 4271 9.1.2.2. g) Compare peer IP adresses */
1248 return (ipa_compare(new_bgp->cf->remote_ip, old_bgp->cf->remote_ip) < 0);
1249 }
1250
1251
1252 static inline int
1253 same_group(rte *r, u32 lpref, u32 lasn)
1254 {
1255 return (r->pref == lpref) && (bgp_get_neighbor(r) == lasn);
1256 }
1257
1258 static inline int
1259 use_deterministic_med(rte *r)
1260 {
1261 struct proto *P = r->attrs->proto;
1262 return (P->proto == &proto_bgp) && ((struct bgp_proto *) P)->cf->deterministic_med;
1263 }
1264
1265 int
1266 bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best)
1267 {
1268 rte *r, *s;
1269 rte *key = new ? new : old;
1270 u32 lpref = key->pref;
1271 u32 lasn = bgp_get_neighbor(key);
1272 int old_is_group_best = 0;
1273
1274 /*
1275 * Proper RFC 4271 path selection is a bit complicated, it cannot be
1276 * implemented just by rte_better(), because it is not a linear
1277 * ordering. But it can be splitted to two levels, where the lower
1278 * level chooses the best routes in each group of routes from the
1279 * same neighboring AS and higher level chooses the best route (with
1280 * a slightly different ordering) between the best-in-group routes.
1281 *
1282 * When deterministic_med is disabled, we just ignore this issue and
1283 * choose the best route by bgp_rte_better() alone. If enabled, the
1284 * lower level of the route selection is done here (for the group
1285 * to which the changed route belongs), all routes in group are
1286 * marked as suppressed, just chosen best-in-group is not.
1287 *
1288 * Global best route selection then implements higher level by
1289 * choosing between non-suppressed routes (as they are always
1290 * preferred over suppressed routes). Routes from BGP protocols
1291 * that do not set deterministic_med are just never suppressed. As
1292 * they do not participate in the lower level selection, it is OK
1293 * that this fn is not called for them.
1294 *
1295 * The idea is simple, the implementation is more problematic,
1296 * mostly because of optimizations in rte_recalculate() that
1297 * avoids full recalculation in most cases.
1298 *
1299 * We can assume that at least one of new, old is non-NULL and both
1300 * are from the same protocol with enabled deterministic_med. We
1301 * group routes by both neighbor AS (lasn) and preference (lpref),
1302 * because bgp_rte_better() does not handle preference itself.
1303 */
1304
1305 /* If new and old are from different groups, we just process that
1306 as two independent events */
1307 if (new && old && !same_group(old, lpref, lasn))
1308 {
1309 int i1, i2;
1310 i1 = bgp_rte_recalculate(table, net, NULL, old, old_best);
1311 i2 = bgp_rte_recalculate(table, net, new, NULL, old_best);
1312 return i1 || i2;
1313 }
1314
1315 /*
1316 * We could find the best-in-group and then make some shortcuts like
1317 * in rte_recalculate, but as we would have to walk through all
1318 * net->routes just to find it, it is probably not worth. So we
1319 * just have two simpler fast cases that use just the old route.
1320 * We also set suppressed flag to avoid using it in bgp_rte_better().
1321 */
1322
1323 if (new)
1324 new->u.bgp.suppressed = 1;
1325
1326 if (old)
1327 {
1328 old_is_group_best = !old->u.bgp.suppressed;
1329 old->u.bgp.suppressed = 1;
1330 int new_is_better = new && bgp_rte_better(new, old);
1331
1332 /* The first case - replace not best with worse (or remove not best) */
1333 if (!old_is_group_best && !new_is_better)
1334 return 0;
1335
1336 /* The second case - replace the best with better */
1337 if (old_is_group_best && new_is_better)
1338 {
1339 /* new is best-in-group, the see discussion below - this is
1340 a special variant of NBG && OBG. From OBG we can deduce
1341 that same_group(old_best) iff (old == old_best) */
1342 new->u.bgp.suppressed = 0;
1343 return (old == old_best);
1344 }
1345 }
1346
1347 /* The default case - find a new best-in-group route */
1348 r = new; /* new may not be in the list */
1349 for (s=net->routes; s; s=s->next)
1350 if (use_deterministic_med(s) && same_group(s, lpref, lasn))
1351 {
1352 s->u.bgp.suppressed = 1;
1353 if (!r || bgp_rte_better(s, r))
1354 r = s;
1355 }
1356
1357 /* Simple case - the last route in group disappears */
1358 if (!r)
1359 return 0;
1360
1361 /* Found best-in-group */
1362 r->u.bgp.suppressed = 0;
1363
1364 /*
1365 * There are generally two reasons why we have to force
1366 * recalculation (return 1): First, the new route may be wrongfully
1367 * chosen to be the best in the first case check in
1368 * rte_recalculate(), this may happen only if old_best is from the
1369 * same group. Second, another (different than new route)
1370 * best-in-group is chosen and that may be the proper best (although
1371 * rte_recalculate() without ignore that possibility).
1372 *
1373 * There are three possible cases according to whether the old route
1374 * was the best in group (OBG, stored in old_is_group_best) and
1375 * whether the new route is the best in group (NBG, tested by r == new).
1376 * These cases work even if old or new is NULL.
1377 *
1378 * NBG -> new is a possible candidate for the best route, so we just
1379 * check for the first reason using same_group().
1380 *
1381 * !NBG && OBG -> Second reason applies, return 1
1382 *
1383 * !NBG && !OBG -> Best in group does not change, old != old_best,
1384 * rte_better(new, old_best) is false and therefore
1385 * the first reason does not apply, return 0
1386 */
1387
1388 if (r == new)
1389 return old_best && same_group(old_best, lpref, lasn);
1390 else
1391 return old_is_group_best;
1392 }
1393
1394 static struct adata *
1395 bgp_aggregator_convert_to_new(struct adata *old, struct linpool *pool)
1396 {
1397 struct adata *newa = lp_alloc(pool, sizeof(struct adata) + 8);
1398 newa->length = 8;
1399 aggregator_convert_to_new(old, newa->data);
1400 return newa;
1401 }
1402
1403
1404 /* Take last req_as ASNs from path old2 (in 2B format), convert to 4B format
1405 * and append path old4 (in 4B format).
1406 */
1407 static struct adata *
1408 bgp_merge_as_paths(struct adata *old2, struct adata *old4, int req_as, struct linpool *pool)
1409 {
1410 byte buf[old2->length * 2];
1411
1412 int ol = as_path_convert_to_new(old2, buf, req_as);
1413 int nl = ol + (old4 ? old4->length : 0);
1414
1415 struct adata *newa = lp_alloc(pool, sizeof(struct adata) + nl);
1416 newa->length = nl;
1417 memcpy(newa->data, buf, ol);
1418 if (old4) memcpy(newa->data + ol, old4->data, old4->length);
1419
1420 return newa;
1421 }
1422
1423 static int
1424 as4_aggregator_valid(struct adata *aggr)
1425 {
1426 return aggr->length == 8;
1427 }
1428
1429
1430 /* Reconstruct 4B AS_PATH and AGGREGATOR according to RFC 4893 4.2.3 */
1431 static void
1432 bgp_reconstruct_4b_atts(struct bgp_proto *p, rta *a, struct linpool *pool)
1433 {
1434 eattr *p2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1435 eattr *p4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_PATH));
1436 eattr *a2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AGGREGATOR));
1437 eattr *a4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR));
1438 int a4_removed = 0;
1439
1440 if (a4 && !as4_aggregator_valid(a4->u.ptr))
1441 {
1442 log(L_WARN "%s: AS4_AGGREGATOR attribute is invalid, skipping attribute", p->p.name);
1443 a4 = NULL;
1444 a4_removed = 1;
1445 }
1446
1447 if (a2)
1448 {
1449 u32 a2_as = get_u16(a2->u.ptr->data);
1450
1451 if (a4)
1452 {
1453 if (a2_as != AS_TRANS)
1454 {
1455 /* Routes were aggregated by old router and therefore AS4_PATH
1456 * and AS4_AGGREGATOR is invalid
1457 *
1458 * Convert AS_PATH and AGGREGATOR to 4B format and finish.
1459 */
1460
1461 a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
1462 p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
1463
1464 return;
1465 }
1466 else
1467 {
1468 /* Common case, use AS4_AGGREGATOR attribute */
1469 a2->u.ptr = a4->u.ptr;
1470 }
1471 }
1472 else
1473 {
1474 /* Common case, use old AGGREGATOR attribute */
1475 a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
1476
1477 if ((a2_as == AS_TRANS) && !a4_removed)
1478 log(L_WARN "%s: AGGREGATOR attribute contain AS_TRANS, but AS4_AGGREGATOR is missing", p->p.name);
1479 }
1480 }
1481 else
1482 if (a4)
1483 log(L_WARN "%s: AS4_AGGREGATOR attribute received, but AGGREGATOR attribute is missing", p->p.name);
1484
1485 int p2_len = as_path_getlen_int(p2->u.ptr, 2);
1486 int p4_len = p4 ? validate_as4_path(p, p4->u.ptr) : -1;
1487
1488 if (p4 && (p4_len < 0))
1489 log(L_WARN "%s: AS4_PATH attribute is malformed, skipping attribute", p->p.name);
1490
1491 if ((p4_len <= 0) || (p2_len < p4_len))
1492 p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
1493 else
1494 p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, p4->u.ptr, p2_len - p4_len, pool);
1495 }
1496
1497 static void
1498 bgp_remove_as4_attrs(struct bgp_proto *p, rta *a)
1499 {
1500 unsigned id1 = EA_CODE(EAP_BGP, BA_AS4_PATH);
1501 unsigned id2 = EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR);
1502 ea_list **el = &(a->eattrs);
1503
1504 /* We know that ea_lists constructed in bgp_decode attrs have one attribute per ea_list struct */
1505 while (*el != NULL)
1506 {
1507 unsigned fid = (*el)->attrs[0].id;
1508
1509 if ((fid == id1) || (fid == id2))
1510 {
1511 *el = (*el)->next;
1512 if (p->as4_session)
1513 log(L_WARN "%s: Unexpected AS4_* attributes received", p->p.name);
1514 }
1515 else
1516 el = &((*el)->next);
1517 }
1518 }
1519
1520 /**
1521 * bgp_decode_attrs - check and decode BGP attributes
1522 * @conn: connection
1523 * @attr: start of attribute block
1524 * @len: length of attribute block
1525 * @pool: linear pool to make all the allocations in
1526 * @mandatory: 1 iff presence of mandatory attributes has to be checked
1527 *
1528 * This function takes a BGP attribute block (a part of an Update message), checks
1529 * its consistency and converts it to a list of BIRD route attributes represented
1530 * by a &rta.
1531 */
1532 struct rta *
1533 bgp_decode_attrs(struct bgp_conn *conn, byte *attr, unsigned int len, struct linpool *pool, int mandatory)
1534 {
1535 struct bgp_proto *bgp = conn->bgp;
1536 rta *a = lp_alloc(pool, sizeof(struct rta));
1537 unsigned int flags, code, l, i, type;
1538 int errcode;
1539 byte *z, *attr_start;
1540 byte seen[256/8];
1541 ea_list *ea;
1542 struct adata *ad;
1543 int withdraw = 0;
1544
1545 bzero(a, sizeof(rta));
1546 a->proto = &bgp->p;
1547 a->source = RTS_BGP;
1548 a->scope = SCOPE_UNIVERSE;
1549 a->cast = RTC_UNICAST;
1550 /* a->dest = RTD_ROUTER; -- set in bgp_set_next_hop() */
1551 a->from = bgp->cf->remote_ip;
1552
1553 /* Parse the attributes */
1554 bzero(seen, sizeof(seen));
1555 DBG("BGP: Parsing attributes\n");
1556 while (len)
1557 {
1558 if (len < 2)
1559 goto malformed;
1560 attr_start = attr;
1561 flags = *attr++;
1562 code = *attr++;
1563 len -= 2;
1564 if (flags & BAF_EXT_LEN)
1565 {
1566 if (len < 2)
1567 goto malformed;
1568 l = get_u16(attr);
1569 attr += 2;
1570 len -= 2;
1571 }
1572 else
1573 {
1574 if (len < 1)
1575 goto malformed;
1576 l = *attr++;
1577 len--;
1578 }
1579 if (l > len)
1580 goto malformed;
1581 len -= l;
1582 z = attr;
1583 attr += l;
1584 DBG("Attr %02x %02x %d\n", code, flags, l);
1585 if (seen[code/8] & (1 << (code%8)))
1586 goto malformed;
1587 if (ATTR_KNOWN(code))
1588 {
1589 struct attr_desc *desc = &bgp_attr_table[code];
1590 if (desc->expected_length >= 0 && desc->expected_length != (int) l)
1591 { errcode = 5; goto err; }
1592 if ((desc->expected_flags ^ flags) & (BAF_OPTIONAL | BAF_TRANSITIVE))
1593 { errcode = 4; goto err; }
1594 if (!desc->allow_in_ebgp && !bgp->is_internal)
1595 continue;
1596 if (desc->validate)
1597 {
1598 errcode = desc->validate(bgp, z, l);
1599 if (errcode > 0)
1600 goto err;
1601 if (errcode == IGNORE)
1602 continue;
1603 if (errcode <= WITHDRAW)
1604 {
1605 log(L_WARN "%s: Attribute %s is malformed, withdrawing update",
1606 bgp->p.name, desc->name);
1607 withdraw = 1;
1608 }
1609 }
1610 else if (code == BA_AS_PATH)
1611 {
1612 /* Special case as it might also trim the attribute */
1613 if (validate_as_path(bgp, z, &l) < 0)
1614 { errcode = 11; goto err; }
1615 }
1616 type = desc->type;
1617 }
1618 else /* Unknown attribute */
1619 {
1620 if (!(flags & BAF_OPTIONAL))
1621 { errcode = 2; goto err; }
1622 type = EAF_TYPE_OPAQUE;
1623 }
1624
1625 // Only OPTIONAL and TRANSITIVE attributes may have non-zero PARTIAL flag
1626 // if (!((flags & BAF_OPTIONAL) && (flags & BAF_TRANSITIVE)) && (flags & BAF_PARTIAL))
1627 // { errcode = 4; goto err; }
1628
1629 seen[code/8] |= (1 << (code%8));
1630 ea = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
1631 ea->next = a->eattrs;
1632 a->eattrs = ea;
1633 ea->flags = 0;
1634 ea->count = 1;
1635 ea->attrs[0].id = EA_CODE(EAP_BGP, code);
1636 ea->attrs[0].flags = flags;
1637 ea->attrs[0].type = type;
1638 if (type & EAF_EMBEDDED)
1639 ad = NULL;
1640 else
1641 {
1642 ad = lp_alloc(pool, sizeof(struct adata) + l);
1643 ea->attrs[0].u.ptr = ad;
1644 ad->length = l;
1645 memcpy(ad->data, z, l);
1646 }
1647 switch (type)
1648 {
1649 case EAF_TYPE_ROUTER_ID:
1650 case EAF_TYPE_INT:
1651 if (l == 1)
1652 ea->attrs[0].u.data = *z;
1653 else
1654 ea->attrs[0].u.data = get_u32(z);
1655 break;
1656 case EAF_TYPE_IP_ADDRESS:
1657 ipa_ntoh(*(ip_addr *)ad->data);
1658 break;
1659 case EAF_TYPE_INT_SET:
1660 case EAF_TYPE_EC_SET:
1661 {
1662 u32 *z = (u32 *) ad->data;
1663 for(i=0; i<ad->length/4; i++)
1664 z[i] = ntohl(z[i]);
1665 break;
1666 }
1667 }
1668 }
1669
1670 if (withdraw)
1671 goto withdraw;
1672
1673 #ifdef IPV6
1674 /* If we received MP_REACH_NLRI we should check mandatory attributes */
1675 if (bgp->mp_reach_len != 0)
1676 mandatory = 1;
1677 #endif
1678
1679 /* If there is no (reachability) NLRI, we should exit now */
1680 if (! mandatory)
1681 return a;
1682
1683 /* Check if all mandatory attributes are present */
1684 for(i=0; i < ARRAY_SIZE(bgp_mandatory_attrs); i++)
1685 {
1686 code = bgp_mandatory_attrs[i];
1687 if (!(seen[code/8] & (1 << (code%8))))
1688 {
1689 bgp_error(conn, 3, 3, &bgp_mandatory_attrs[i], 1);
1690 return NULL;
1691 }
1692 }
1693
1694 /* When receiving attributes from non-AS4-aware BGP speaker,
1695 * we have to reconstruct 4B AS_PATH and AGGREGATOR attributes
1696 */
1697 if (! bgp->as4_session)
1698 bgp_reconstruct_4b_atts(bgp, a, pool);
1699
1700 bgp_remove_as4_attrs(bgp, a);
1701
1702 /* If the AS path attribute contains our AS, reject the routes */
1703 if (bgp_as_path_loopy(bgp, a))
1704 goto withdraw;
1705
1706 /* Two checks for IBGP loops caused by route reflection, RFC 4456 */
1707 if (bgp_originator_id_loopy(bgp, a) ||
1708 bgp_cluster_list_loopy(bgp, a))
1709 goto withdraw;
1710
1711 /* If there's no local preference, define one */
1712 if (!(seen[0] & (1 << BA_LOCAL_PREF)))
1713 bgp_attach_attr(&a->eattrs, pool, BA_LOCAL_PREF, bgp->cf->default_local_pref);
1714
1715 return a;
1716
1717 withdraw:
1718 return NULL;
1719
1720 malformed:
1721 bgp_error(conn, 3, 1, NULL, 0);
1722 return NULL;
1723
1724 err:
1725 bgp_error(conn, 3, errcode, attr_start, z+l-attr_start);
1726 return NULL;
1727 }
1728
1729 int
1730 bgp_get_attr(eattr *a, byte *buf, int buflen)
1731 {
1732 unsigned int i = EA_ID(a->id);
1733 struct attr_desc *d;
1734 int len;
1735
1736 if (ATTR_KNOWN(i))
1737 {
1738 d = &bgp_attr_table[i];
1739 len = bsprintf(buf, "%s", d->name);
1740 buf += len;
1741 if (d->format)
1742 {
1743 *buf++ = ':';
1744 *buf++ = ' ';
1745 d->format(a, buf, buflen - len - 2);
1746 return GA_FULL;
1747 }
1748 return GA_NAME;
1749 }
1750 bsprintf(buf, "%02x%s", i, (a->flags & BAF_TRANSITIVE) ? " [t]" : "");
1751 return GA_NAME;
1752 }
1753
1754 void
1755 bgp_attr_init(struct bgp_proto *p)
1756 {
1757 p->hash_size = 256;
1758 p->hash_limit = p->hash_size * 4;
1759 p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
1760 init_list(&p->bucket_queue);
1761 p->withdraw_bucket = NULL;
1762 fib_init(&p->prefix_fib, p->p.pool, sizeof(struct bgp_prefix), 0, bgp_init_prefix);
1763 }
1764
1765 void
1766 bgp_get_route_info(rte *e, byte *buf, ea_list *attrs)
1767 {
1768 eattr *p = ea_find(attrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1769 eattr *o = ea_find(attrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1770 u32 origas;
1771
1772 buf += bsprintf(buf, " (%d", e->pref);
1773
1774 if (e->u.bgp.suppressed)
1775 buf += bsprintf(buf, "-");
1776
1777 if (e->attrs->hostentry)
1778 {
1779 if (!rte_resolvable(e))
1780 buf += bsprintf(buf, "/-");
1781 else if (e->attrs->igp_metric >= IGP_METRIC_UNKNOWN)
1782 buf += bsprintf(buf, "/?");
1783 else
1784 buf += bsprintf(buf, "/%d", e->attrs->igp_metric);
1785 }
1786 buf += bsprintf(buf, ") [");
1787
1788 if (p && as_path_get_last(p->u.ptr, &origas))
1789 buf += bsprintf(buf, "AS%u", origas);
1790 if (o)
1791 buf += bsprintf(buf, "%c", "ie?"[o->u.data]);
1792 strcpy(buf, "]");
1793 }