]> git.ipfire.org Git - thirdparty/bird.git/blob - proto/bgp/attrs.c
Merge branch 'birdcl'
[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%u", 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->cf->next_hop_keep &&
939 (!p->neigh || (rta->iface != p->neigh->iface))))
940 set_next_hop(z, p->source_addr);
941 else
942 set_next_hop(z, rta->gw);
943
944 bgp_set_attr(ea->attrs+3, BA_LOCAL_PREF, p->cf->default_local_pref);
945
946 return 0; /* Leave decision to the filters */
947 }
948
949
950 static inline int
951 bgp_as_path_loopy(struct bgp_proto *p, rta *a)
952 {
953 eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
954 return (e && as_path_is_member(e->u.ptr, p->local_as));
955 }
956
957 static inline int
958 bgp_originator_id_loopy(struct bgp_proto *p, rta *a)
959 {
960 eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
961 return (e && (e->u.data == p->local_id));
962 }
963
964 static inline int
965 bgp_cluster_list_loopy(struct bgp_proto *p, rta *a)
966 {
967 eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
968 return (e && p->rr_client && int_set_contains(e->u.ptr, p->rr_cluster_id));
969 }
970
971
972 static inline void
973 bgp_path_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 as)
974 {
975 eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
976 bgp_attach_attr(attrs, pool, BA_AS_PATH, (uintptr_t) as_path_prepend(pool, a->u.ptr, as));
977 }
978
979 static inline void
980 bgp_cluster_list_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 cid)
981 {
982 eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
983 bgp_attach_attr(attrs, pool, BA_CLUSTER_LIST, (uintptr_t) int_set_add(pool, a ? a->u.ptr : NULL, cid));
984 }
985
986 static int
987 bgp_update_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool, int rr)
988 {
989 eattr *a;
990
991 if (!p->is_internal && !p->rs_client)
992 {
993 bgp_path_prepend(e, attrs, pool, p->local_as);
994
995 /* The MULTI_EXIT_DISC attribute received from a neighboring AS MUST NOT be
996 * propagated to other neighboring ASes.
997 * Perhaps it would be better to undefine it.
998 */
999 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
1000 if (a)
1001 bgp_attach_attr(attrs, pool, BA_MULTI_EXIT_DISC, 0);
1002 }
1003
1004 /* iBGP -> keep next_hop, eBGP multi-hop -> use source_addr,
1005 * eBGP single-hop -> keep next_hop if on the same iface.
1006 * If the next_hop is zero (i.e. link-local), keep only if on the same iface.
1007 *
1008 * Note that same-iface-check uses iface from route, which is based on gw.
1009 */
1010 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
1011 if (a && !p->cf->next_hop_self &&
1012 (p->cf->next_hop_keep ||
1013 (p->is_internal && ipa_nonzero(*((ip_addr *) a->u.ptr->data))) ||
1014 (p->neigh && (e->attrs->iface == p->neigh->iface))))
1015 {
1016 /* Leave the original next hop attribute, will check later where does it point */
1017 }
1018 else
1019 {
1020 /* Need to create new one */
1021 byte *b = bgp_attach_attr_wa(attrs, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
1022 set_next_hop(b, p->source_addr);
1023 }
1024
1025 if (rr)
1026 {
1027 /* Handling route reflection, RFC 4456 */
1028 struct bgp_proto *src = (struct bgp_proto *) e->attrs->proto;
1029
1030 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1031 if (!a)
1032 bgp_attach_attr(attrs, pool, BA_ORIGINATOR_ID, src->remote_id);
1033
1034 /* We attach proper cluster ID according to whether the route is entering or leaving the cluster */
1035 bgp_cluster_list_prepend(e, attrs, pool, src->rr_client ? src->rr_cluster_id : p->rr_cluster_id);
1036
1037 /* Two RR clients with different cluster ID, hmmm */
1038 if (src->rr_client && p->rr_client && (src->rr_cluster_id != p->rr_cluster_id))
1039 bgp_cluster_list_prepend(e, attrs, pool, p->rr_cluster_id);
1040 }
1041
1042 return 0; /* Leave decision to the filters */
1043 }
1044
1045 static int
1046 bgp_community_filter(struct bgp_proto *p, rte *e)
1047 {
1048 eattr *a;
1049 struct adata *d;
1050
1051 /* Check if we aren't forbidden to export the route by communities */
1052 a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_COMMUNITY));
1053 if (a)
1054 {
1055 d = a->u.ptr;
1056 if (int_set_contains(d, BGP_COMM_NO_ADVERTISE))
1057 {
1058 DBG("\tNO_ADVERTISE\n");
1059 return 1;
1060 }
1061 if (!p->is_internal &&
1062 (int_set_contains(d, BGP_COMM_NO_EXPORT) ||
1063 int_set_contains(d, BGP_COMM_NO_EXPORT_SUBCONFED)))
1064 {
1065 DBG("\tNO_EXPORT\n");
1066 return 1;
1067 }
1068 }
1069
1070 return 0;
1071 }
1072
1073 int
1074 bgp_import_control(struct proto *P, rte **new, ea_list **attrs, struct linpool *pool)
1075 {
1076 rte *e = *new;
1077 struct bgp_proto *p = (struct bgp_proto *) P;
1078 struct bgp_proto *new_bgp = (e->attrs->proto->proto == &proto_bgp) ? (struct bgp_proto *) e->attrs->proto : NULL;
1079
1080 if (p == new_bgp) /* Poison reverse updates */
1081 return -1;
1082 if (new_bgp)
1083 {
1084 /* We should check here for cluster list loop, because the receiving BGP instance
1085 might have different cluster ID */
1086 if (bgp_cluster_list_loopy(p, e->attrs))
1087 return -1;
1088
1089 if (p->cf->interpret_communities && bgp_community_filter(p, e))
1090 return -1;
1091
1092 if (p->local_as == new_bgp->local_as && p->is_internal && new_bgp->is_internal)
1093 {
1094 /* Redistribution of internal routes with IBGP */
1095 if (p->rr_client || new_bgp->rr_client)
1096 /* Route reflection, RFC 4456 */
1097 return bgp_update_attrs(p, e, attrs, pool, 1);
1098 else
1099 return -1;
1100 }
1101 else
1102 return bgp_update_attrs(p, e, attrs, pool, 0);
1103 }
1104 else
1105 return bgp_create_attrs(p, e, attrs, pool);
1106 }
1107
1108 static inline u32
1109 bgp_get_neighbor(rte *r)
1110 {
1111 eattr *e = ea_find(r->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1112 u32 as;
1113
1114 if (e && as_path_get_first(e->u.ptr, &as))
1115 return as;
1116 else
1117 return ((struct bgp_proto *) r->attrs->proto)->remote_as;
1118 }
1119
1120 static inline int
1121 rte_resolvable(rte *rt)
1122 {
1123 int rd = rt->attrs->dest;
1124 return (rd == RTD_ROUTER) || (rd == RTD_DEVICE) || (rd == RTD_MULTIPATH);
1125 }
1126
1127 int
1128 bgp_rte_better(rte *new, rte *old)
1129 {
1130 struct bgp_proto *new_bgp = (struct bgp_proto *) new->attrs->proto;
1131 struct bgp_proto *old_bgp = (struct bgp_proto *) old->attrs->proto;
1132 eattr *x, *y;
1133 u32 n, o;
1134
1135 /* Skip suppressed routes (see bgp_rte_recalculate()) */
1136 n = new->u.bgp.suppressed;
1137 o = old->u.bgp.suppressed;
1138 if (n > o)
1139 return 0;
1140 if (n < o)
1141 return 1;
1142
1143 /* RFC 4271 9.1.2.1. Route resolvability test */
1144 n = rte_resolvable(new);
1145 o = rte_resolvable(old);
1146 if (n > o)
1147 return 1;
1148 if (n < o)
1149 return 0;
1150
1151 /* Start with local preferences */
1152 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
1153 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
1154 n = x ? x->u.data : new_bgp->cf->default_local_pref;
1155 o = y ? y->u.data : old_bgp->cf->default_local_pref;
1156 if (n > o)
1157 return 1;
1158 if (n < o)
1159 return 0;
1160
1161 /* RFC 4271 9.1.2.2. a) Use AS path lengths */
1162 if (new_bgp->cf->compare_path_lengths || old_bgp->cf->compare_path_lengths)
1163 {
1164 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1165 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1166 n = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
1167 o = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
1168 if (n < o)
1169 return 1;
1170 if (n > o)
1171 return 0;
1172 }
1173
1174 /* RFC 4271 9.1.2.2. b) Use origins */
1175 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1176 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1177 n = x ? x->u.data : ORIGIN_INCOMPLETE;
1178 o = y ? y->u.data : ORIGIN_INCOMPLETE;
1179 if (n < o)
1180 return 1;
1181 if (n > o)
1182 return 0;
1183
1184 /* RFC 4271 9.1.2.2. c) Compare MED's */
1185 /* Proper RFC 4271 path selection cannot be interpreted as finding
1186 * the best path in some ordering. It is implemented partially in
1187 * bgp_rte_recalculate() when deterministic_med option is
1188 * active. Without that option, the behavior is just an
1189 * approximation, which in specific situations may lead to
1190 * persistent routing loops, because it is nondeterministic - it
1191 * depends on the order in which routes appeared. But it is also the
1192 * same behavior as used by default in Cisco routers, so it is
1193 * probably not a big issue.
1194 */
1195 if (new_bgp->cf->med_metric || old_bgp->cf->med_metric ||
1196 (bgp_get_neighbor(new) == bgp_get_neighbor(old)))
1197 {
1198 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
1199 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
1200 n = x ? x->u.data : new_bgp->cf->default_med;
1201 o = y ? y->u.data : old_bgp->cf->default_med;
1202 if (n < o)
1203 return 1;
1204 if (n > o)
1205 return 0;
1206 }
1207
1208 /* RFC 4271 9.1.2.2. d) Prefer external peers */
1209 if (new_bgp->is_internal > old_bgp->is_internal)
1210 return 0;
1211 if (new_bgp->is_internal < old_bgp->is_internal)
1212 return 1;
1213
1214 /* RFC 4271 9.1.2.2. e) Compare IGP metrics */
1215 n = new_bgp->cf->igp_metric ? new->attrs->igp_metric : 0;
1216 o = old_bgp->cf->igp_metric ? old->attrs->igp_metric : 0;
1217 if (n < o)
1218 return 1;
1219 if (n > o)
1220 return 0;
1221
1222 /* RFC 4271 9.1.2.2. f) Compare BGP identifiers */
1223 /* RFC 4456 9. a) Use ORIGINATOR_ID instead of local neighor ID */
1224 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1225 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1226 n = x ? x->u.data : new_bgp->remote_id;
1227 o = y ? y->u.data : old_bgp->remote_id;
1228
1229 /* RFC 5004 - prefer older routes */
1230 /* (if both are external and from different peer) */
1231 if ((new_bgp->cf->prefer_older || old_bgp->cf->prefer_older) &&
1232 !new_bgp->is_internal && n != o)
1233 return 0;
1234
1235 /* rest of RFC 4271 9.1.2.2. f) */
1236 if (n < o)
1237 return 1;
1238 if (n > o)
1239 return 0;
1240
1241 /* RFC 4456 9. b) Compare cluster list lengths */
1242 x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
1243 y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
1244 n = x ? int_set_get_size(x->u.ptr) : 0;
1245 o = y ? int_set_get_size(y->u.ptr) : 0;
1246 if (n < o)
1247 return 1;
1248 if (n > o)
1249 return 0;
1250
1251 /* RFC 4271 9.1.2.2. g) Compare peer IP adresses */
1252 return (ipa_compare(new_bgp->cf->remote_ip, old_bgp->cf->remote_ip) < 0);
1253 }
1254
1255
1256 static inline int
1257 same_group(rte *r, u32 lpref, u32 lasn)
1258 {
1259 return (r->pref == lpref) && (bgp_get_neighbor(r) == lasn);
1260 }
1261
1262 static inline int
1263 use_deterministic_med(rte *r)
1264 {
1265 struct proto *P = r->attrs->proto;
1266 return (P->proto == &proto_bgp) && ((struct bgp_proto *) P)->cf->deterministic_med;
1267 }
1268
1269 int
1270 bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best)
1271 {
1272 rte *r, *s;
1273 rte *key = new ? new : old;
1274 u32 lpref = key->pref;
1275 u32 lasn = bgp_get_neighbor(key);
1276 int old_is_group_best = 0;
1277
1278 /*
1279 * Proper RFC 4271 path selection is a bit complicated, it cannot be
1280 * implemented just by rte_better(), because it is not a linear
1281 * ordering. But it can be splitted to two levels, where the lower
1282 * level chooses the best routes in each group of routes from the
1283 * same neighboring AS and higher level chooses the best route (with
1284 * a slightly different ordering) between the best-in-group routes.
1285 *
1286 * When deterministic_med is disabled, we just ignore this issue and
1287 * choose the best route by bgp_rte_better() alone. If enabled, the
1288 * lower level of the route selection is done here (for the group
1289 * to which the changed route belongs), all routes in group are
1290 * marked as suppressed, just chosen best-in-group is not.
1291 *
1292 * Global best route selection then implements higher level by
1293 * choosing between non-suppressed routes (as they are always
1294 * preferred over suppressed routes). Routes from BGP protocols
1295 * that do not set deterministic_med are just never suppressed. As
1296 * they do not participate in the lower level selection, it is OK
1297 * that this fn is not called for them.
1298 *
1299 * The idea is simple, the implementation is more problematic,
1300 * mostly because of optimizations in rte_recalculate() that
1301 * avoids full recalculation in most cases.
1302 *
1303 * We can assume that at least one of new, old is non-NULL and both
1304 * are from the same protocol with enabled deterministic_med. We
1305 * group routes by both neighbor AS (lasn) and preference (lpref),
1306 * because bgp_rte_better() does not handle preference itself.
1307 */
1308
1309 /* If new and old are from different groups, we just process that
1310 as two independent events */
1311 if (new && old && !same_group(old, lpref, lasn))
1312 {
1313 int i1, i2;
1314 i1 = bgp_rte_recalculate(table, net, NULL, old, old_best);
1315 i2 = bgp_rte_recalculate(table, net, new, NULL, old_best);
1316 return i1 || i2;
1317 }
1318
1319 /*
1320 * We could find the best-in-group and then make some shortcuts like
1321 * in rte_recalculate, but as we would have to walk through all
1322 * net->routes just to find it, it is probably not worth. So we
1323 * just have two simpler fast cases that use just the old route.
1324 * We also set suppressed flag to avoid using it in bgp_rte_better().
1325 */
1326
1327 if (new)
1328 new->u.bgp.suppressed = 1;
1329
1330 if (old)
1331 {
1332 old_is_group_best = !old->u.bgp.suppressed;
1333 old->u.bgp.suppressed = 1;
1334 int new_is_better = new && bgp_rte_better(new, old);
1335
1336 /* The first case - replace not best with worse (or remove not best) */
1337 if (!old_is_group_best && !new_is_better)
1338 return 0;
1339
1340 /* The second case - replace the best with better */
1341 if (old_is_group_best && new_is_better)
1342 {
1343 /* new is best-in-group, the see discussion below - this is
1344 a special variant of NBG && OBG. From OBG we can deduce
1345 that same_group(old_best) iff (old == old_best) */
1346 new->u.bgp.suppressed = 0;
1347 return (old == old_best);
1348 }
1349 }
1350
1351 /* The default case - find a new best-in-group route */
1352 r = new; /* new may not be in the list */
1353 for (s=net->routes; rte_is_valid(s); s=s->next)
1354 if (use_deterministic_med(s) && same_group(s, lpref, lasn))
1355 {
1356 s->u.bgp.suppressed = 1;
1357 if (!r || bgp_rte_better(s, r))
1358 r = s;
1359 }
1360
1361 /* Simple case - the last route in group disappears */
1362 if (!r)
1363 return 0;
1364
1365 /* Found best-in-group */
1366 r->u.bgp.suppressed = 0;
1367
1368 /*
1369 * There are generally two reasons why we have to force
1370 * recalculation (return 1): First, the new route may be wrongfully
1371 * chosen to be the best in the first case check in
1372 * rte_recalculate(), this may happen only if old_best is from the
1373 * same group. Second, another (different than new route)
1374 * best-in-group is chosen and that may be the proper best (although
1375 * rte_recalculate() without ignore that possibility).
1376 *
1377 * There are three possible cases according to whether the old route
1378 * was the best in group (OBG, stored in old_is_group_best) and
1379 * whether the new route is the best in group (NBG, tested by r == new).
1380 * These cases work even if old or new is NULL.
1381 *
1382 * NBG -> new is a possible candidate for the best route, so we just
1383 * check for the first reason using same_group().
1384 *
1385 * !NBG && OBG -> Second reason applies, return 1
1386 *
1387 * !NBG && !OBG -> Best in group does not change, old != old_best,
1388 * rte_better(new, old_best) is false and therefore
1389 * the first reason does not apply, return 0
1390 */
1391
1392 if (r == new)
1393 return old_best && same_group(old_best, lpref, lasn);
1394 else
1395 return old_is_group_best;
1396 }
1397
1398 static struct adata *
1399 bgp_aggregator_convert_to_new(struct adata *old, struct linpool *pool)
1400 {
1401 struct adata *newa = lp_alloc(pool, sizeof(struct adata) + 8);
1402 newa->length = 8;
1403 aggregator_convert_to_new(old, newa->data);
1404 return newa;
1405 }
1406
1407
1408 /* Take last req_as ASNs from path old2 (in 2B format), convert to 4B format
1409 * and append path old4 (in 4B format).
1410 */
1411 static struct adata *
1412 bgp_merge_as_paths(struct adata *old2, struct adata *old4, int req_as, struct linpool *pool)
1413 {
1414 byte buf[old2->length * 2];
1415
1416 int ol = as_path_convert_to_new(old2, buf, req_as);
1417 int nl = ol + (old4 ? old4->length : 0);
1418
1419 struct adata *newa = lp_alloc(pool, sizeof(struct adata) + nl);
1420 newa->length = nl;
1421 memcpy(newa->data, buf, ol);
1422 if (old4) memcpy(newa->data + ol, old4->data, old4->length);
1423
1424 return newa;
1425 }
1426
1427 static int
1428 as4_aggregator_valid(struct adata *aggr)
1429 {
1430 return aggr->length == 8;
1431 }
1432
1433
1434 /* Reconstruct 4B AS_PATH and AGGREGATOR according to RFC 4893 4.2.3 */
1435 static void
1436 bgp_reconstruct_4b_atts(struct bgp_proto *p, rta *a, struct linpool *pool)
1437 {
1438 eattr *p2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1439 eattr *p4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_PATH));
1440 eattr *a2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AGGREGATOR));
1441 eattr *a4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR));
1442 int a4_removed = 0;
1443
1444 if (a4 && !as4_aggregator_valid(a4->u.ptr))
1445 {
1446 log(L_WARN "%s: AS4_AGGREGATOR attribute is invalid, skipping attribute", p->p.name);
1447 a4 = NULL;
1448 a4_removed = 1;
1449 }
1450
1451 if (a2)
1452 {
1453 u32 a2_as = get_u16(a2->u.ptr->data);
1454
1455 if (a4)
1456 {
1457 if (a2_as != AS_TRANS)
1458 {
1459 /* Routes were aggregated by old router and therefore AS4_PATH
1460 * and AS4_AGGREGATOR is invalid
1461 *
1462 * Convert AS_PATH and AGGREGATOR to 4B format and finish.
1463 */
1464
1465 a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
1466 p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
1467
1468 return;
1469 }
1470 else
1471 {
1472 /* Common case, use AS4_AGGREGATOR attribute */
1473 a2->u.ptr = a4->u.ptr;
1474 }
1475 }
1476 else
1477 {
1478 /* Common case, use old AGGREGATOR attribute */
1479 a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
1480
1481 if ((a2_as == AS_TRANS) && !a4_removed)
1482 log(L_WARN "%s: AGGREGATOR attribute contain AS_TRANS, but AS4_AGGREGATOR is missing", p->p.name);
1483 }
1484 }
1485 else
1486 if (a4)
1487 log(L_WARN "%s: AS4_AGGREGATOR attribute received, but AGGREGATOR attribute is missing", p->p.name);
1488
1489 int p2_len = as_path_getlen_int(p2->u.ptr, 2);
1490 int p4_len = p4 ? validate_as4_path(p, p4->u.ptr) : -1;
1491
1492 if (p4 && (p4_len < 0))
1493 log(L_WARN "%s: AS4_PATH attribute is malformed, skipping attribute", p->p.name);
1494
1495 if ((p4_len <= 0) || (p2_len < p4_len))
1496 p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
1497 else
1498 p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, p4->u.ptr, p2_len - p4_len, pool);
1499 }
1500
1501 static void
1502 bgp_remove_as4_attrs(struct bgp_proto *p, rta *a)
1503 {
1504 unsigned id1 = EA_CODE(EAP_BGP, BA_AS4_PATH);
1505 unsigned id2 = EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR);
1506 ea_list **el = &(a->eattrs);
1507
1508 /* We know that ea_lists constructed in bgp_decode attrs have one attribute per ea_list struct */
1509 while (*el != NULL)
1510 {
1511 unsigned fid = (*el)->attrs[0].id;
1512
1513 if ((fid == id1) || (fid == id2))
1514 {
1515 *el = (*el)->next;
1516 if (p->as4_session)
1517 log(L_WARN "%s: Unexpected AS4_* attributes received", p->p.name);
1518 }
1519 else
1520 el = &((*el)->next);
1521 }
1522 }
1523
1524 /**
1525 * bgp_decode_attrs - check and decode BGP attributes
1526 * @conn: connection
1527 * @attr: start of attribute block
1528 * @len: length of attribute block
1529 * @pool: linear pool to make all the allocations in
1530 * @mandatory: 1 iff presence of mandatory attributes has to be checked
1531 *
1532 * This function takes a BGP attribute block (a part of an Update message), checks
1533 * its consistency and converts it to a list of BIRD route attributes represented
1534 * by a &rta.
1535 */
1536 struct rta *
1537 bgp_decode_attrs(struct bgp_conn *conn, byte *attr, unsigned int len, struct linpool *pool, int mandatory)
1538 {
1539 struct bgp_proto *bgp = conn->bgp;
1540 rta *a = lp_alloc(pool, sizeof(struct rta));
1541 unsigned int flags, code, l, i, type;
1542 int errcode;
1543 byte *z, *attr_start;
1544 byte seen[256/8];
1545 ea_list *ea;
1546 struct adata *ad;
1547 int withdraw = 0;
1548
1549 bzero(a, sizeof(rta));
1550 a->proto = &bgp->p;
1551 a->source = RTS_BGP;
1552 a->scope = SCOPE_UNIVERSE;
1553 a->cast = RTC_UNICAST;
1554 /* a->dest = RTD_ROUTER; -- set in bgp_set_next_hop() */
1555 a->from = bgp->cf->remote_ip;
1556
1557 /* Parse the attributes */
1558 bzero(seen, sizeof(seen));
1559 DBG("BGP: Parsing attributes\n");
1560 while (len)
1561 {
1562 if (len < 2)
1563 goto malformed;
1564 attr_start = attr;
1565 flags = *attr++;
1566 code = *attr++;
1567 len -= 2;
1568 if (flags & BAF_EXT_LEN)
1569 {
1570 if (len < 2)
1571 goto malformed;
1572 l = get_u16(attr);
1573 attr += 2;
1574 len -= 2;
1575 }
1576 else
1577 {
1578 if (len < 1)
1579 goto malformed;
1580 l = *attr++;
1581 len--;
1582 }
1583 if (l > len)
1584 goto malformed;
1585 len -= l;
1586 z = attr;
1587 attr += l;
1588 DBG("Attr %02x %02x %d\n", code, flags, l);
1589 if (seen[code/8] & (1 << (code%8)))
1590 goto malformed;
1591 if (ATTR_KNOWN(code))
1592 {
1593 struct attr_desc *desc = &bgp_attr_table[code];
1594 if (desc->expected_length >= 0 && desc->expected_length != (int) l)
1595 { errcode = 5; goto err; }
1596 if ((desc->expected_flags ^ flags) & (BAF_OPTIONAL | BAF_TRANSITIVE))
1597 { errcode = 4; goto err; }
1598 if (!desc->allow_in_ebgp && !bgp->is_internal)
1599 continue;
1600 if (desc->validate)
1601 {
1602 errcode = desc->validate(bgp, z, l);
1603 if (errcode > 0)
1604 goto err;
1605 if (errcode == IGNORE)
1606 continue;
1607 if (errcode <= WITHDRAW)
1608 {
1609 log(L_WARN "%s: Attribute %s is malformed, withdrawing update",
1610 bgp->p.name, desc->name);
1611 withdraw = 1;
1612 }
1613 }
1614 else if (code == BA_AS_PATH)
1615 {
1616 /* Special case as it might also trim the attribute */
1617 if (validate_as_path(bgp, z, &l) < 0)
1618 { errcode = 11; goto err; }
1619 }
1620 type = desc->type;
1621 }
1622 else /* Unknown attribute */
1623 {
1624 if (!(flags & BAF_OPTIONAL))
1625 { errcode = 2; goto err; }
1626 type = EAF_TYPE_OPAQUE;
1627 }
1628
1629 // Only OPTIONAL and TRANSITIVE attributes may have non-zero PARTIAL flag
1630 // if (!((flags & BAF_OPTIONAL) && (flags & BAF_TRANSITIVE)) && (flags & BAF_PARTIAL))
1631 // { errcode = 4; goto err; }
1632
1633 seen[code/8] |= (1 << (code%8));
1634 ea = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
1635 ea->next = a->eattrs;
1636 a->eattrs = ea;
1637 ea->flags = 0;
1638 ea->count = 1;
1639 ea->attrs[0].id = EA_CODE(EAP_BGP, code);
1640 ea->attrs[0].flags = flags;
1641 ea->attrs[0].type = type;
1642 if (type & EAF_EMBEDDED)
1643 ad = NULL;
1644 else
1645 {
1646 ad = lp_alloc(pool, sizeof(struct adata) + l);
1647 ea->attrs[0].u.ptr = ad;
1648 ad->length = l;
1649 memcpy(ad->data, z, l);
1650 }
1651 switch (type)
1652 {
1653 case EAF_TYPE_ROUTER_ID:
1654 case EAF_TYPE_INT:
1655 if (l == 1)
1656 ea->attrs[0].u.data = *z;
1657 else
1658 ea->attrs[0].u.data = get_u32(z);
1659 break;
1660 case EAF_TYPE_IP_ADDRESS:
1661 ipa_ntoh(*(ip_addr *)ad->data);
1662 break;
1663 case EAF_TYPE_INT_SET:
1664 case EAF_TYPE_EC_SET:
1665 {
1666 u32 *z = (u32 *) ad->data;
1667 for(i=0; i<ad->length/4; i++)
1668 z[i] = ntohl(z[i]);
1669 break;
1670 }
1671 }
1672 }
1673
1674 if (withdraw)
1675 goto withdraw;
1676
1677 #ifdef IPV6
1678 /* If we received MP_REACH_NLRI we should check mandatory attributes */
1679 if (bgp->mp_reach_len != 0)
1680 mandatory = 1;
1681 #endif
1682
1683 /* If there is no (reachability) NLRI, we should exit now */
1684 if (! mandatory)
1685 return a;
1686
1687 /* Check if all mandatory attributes are present */
1688 for(i=0; i < ARRAY_SIZE(bgp_mandatory_attrs); i++)
1689 {
1690 code = bgp_mandatory_attrs[i];
1691 if (!(seen[code/8] & (1 << (code%8))))
1692 {
1693 bgp_error(conn, 3, 3, &bgp_mandatory_attrs[i], 1);
1694 return NULL;
1695 }
1696 }
1697
1698 /* When receiving attributes from non-AS4-aware BGP speaker,
1699 * we have to reconstruct 4B AS_PATH and AGGREGATOR attributes
1700 */
1701 if (! bgp->as4_session)
1702 bgp_reconstruct_4b_atts(bgp, a, pool);
1703
1704 bgp_remove_as4_attrs(bgp, a);
1705
1706 /* If the AS path attribute contains our AS, reject the routes */
1707 if (bgp_as_path_loopy(bgp, a))
1708 goto withdraw;
1709
1710 /* Two checks for IBGP loops caused by route reflection, RFC 4456 */
1711 if (bgp_originator_id_loopy(bgp, a) ||
1712 bgp_cluster_list_loopy(bgp, a))
1713 goto withdraw;
1714
1715 /* If there's no local preference, define one */
1716 if (!(seen[0] & (1 << BA_LOCAL_PREF)))
1717 bgp_attach_attr(&a->eattrs, pool, BA_LOCAL_PREF, bgp->cf->default_local_pref);
1718
1719 return a;
1720
1721 withdraw:
1722 return NULL;
1723
1724 malformed:
1725 bgp_error(conn, 3, 1, NULL, 0);
1726 return NULL;
1727
1728 err:
1729 bgp_error(conn, 3, errcode, attr_start, z+l-attr_start);
1730 return NULL;
1731 }
1732
1733 int
1734 bgp_get_attr(eattr *a, byte *buf, int buflen)
1735 {
1736 unsigned int i = EA_ID(a->id);
1737 struct attr_desc *d;
1738 int len;
1739
1740 if (ATTR_KNOWN(i))
1741 {
1742 d = &bgp_attr_table[i];
1743 len = bsprintf(buf, "%s", d->name);
1744 buf += len;
1745 if (d->format)
1746 {
1747 *buf++ = ':';
1748 *buf++ = ' ';
1749 d->format(a, buf, buflen - len - 2);
1750 return GA_FULL;
1751 }
1752 return GA_NAME;
1753 }
1754 bsprintf(buf, "%02x%s", i, (a->flags & BAF_TRANSITIVE) ? " [t]" : "");
1755 return GA_NAME;
1756 }
1757
1758 void
1759 bgp_attr_init(struct bgp_proto *p)
1760 {
1761 p->hash_size = 256;
1762 p->hash_limit = p->hash_size * 4;
1763 p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
1764 init_list(&p->bucket_queue);
1765 p->withdraw_bucket = NULL;
1766 fib_init(&p->prefix_fib, p->p.pool, sizeof(struct bgp_prefix), 0, bgp_init_prefix);
1767 }
1768
1769 void
1770 bgp_get_route_info(rte *e, byte *buf, ea_list *attrs)
1771 {
1772 eattr *p = ea_find(attrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1773 eattr *o = ea_find(attrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1774 u32 origas;
1775
1776 buf += bsprintf(buf, " (%d", e->pref);
1777
1778 if (e->u.bgp.suppressed)
1779 buf += bsprintf(buf, "-");
1780
1781 if (e->attrs->hostentry)
1782 {
1783 if (!rte_resolvable(e))
1784 buf += bsprintf(buf, "/-");
1785 else if (e->attrs->igp_metric >= IGP_METRIC_UNKNOWN)
1786 buf += bsprintf(buf, "/?");
1787 else
1788 buf += bsprintf(buf, "/%d", e->attrs->igp_metric);
1789 }
1790 buf += bsprintf(buf, ") [");
1791
1792 if (p && as_path_get_last(p->u.ptr, &origas))
1793 buf += bsprintf(buf, "AS%u", origas);
1794 if (o)
1795 buf += bsprintf(buf, "%c", "ie?"[o->u.data]);
1796 strcpy(buf, "]");
1797 }