Statistics
| Branch: | Revision:

iof-bird-daemon / proto / bgp / attrs.c @ e81b440f

History | View | Annotate | Download (37.5 KB)

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
static byte bgp_mandatory_attrs[] = { BA_ORIGIN, BA_AS_PATH
26
#ifndef IPV6
27
,BA_NEXT_HOP
28
#endif
29
};
30

    
31
struct attr_desc {
32
  char *name;
33
  int expected_length;
34
  int expected_flags;
35
  int type;
36
  int allow_in_ebgp;
37
  int (*validate)(struct bgp_proto *p, byte *attr, int len);
38
  void (*format)(eattr *ea, byte *buf, int buflen);
39
};
40

    
41
static int
42
bgp_check_origin(struct bgp_proto *p UNUSED, byte *a, int len UNUSED)
43
{
44
  if (*a > 2)
45
    return 6;
46
  return 0;
47
}
48

    
49
static void
50
bgp_format_origin(eattr *a, byte *buf, int buflen UNUSED)
51
{
52
  static char *bgp_origin_names[] = { "IGP", "EGP", "Incomplete" };
53

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

    
57
static int
58
path_segment_contains(byte *p, int bs, u32 asn)
59
{
60
  int i;
61
  int len = p[1];
62
  p += 2;
63

    
64
  for(i=0; i<len; i++)
65
    {
66
      u32 asn2 = (bs == 4) ? get_u32(p) : get_u16(p);
67
      if (asn2 == asn)
68
        return 1;
69
      p += bs;
70
    }
71

    
72
  return 0;
73
}
74

    
75
/* Validates path attribute, removes AS_CONFED_* segments, and also returns path length */
76
static int
77
validate_path(struct bgp_proto *p, int as_path, int bs, byte *idata, unsigned int *ilength)
78
{
79
  int res = 0;
80
  u8 *a, *dst;
81
  int len, plen, copy;
82

    
83
  dst = a = idata;
84
  len = *ilength;
85

    
86
  while (len)
87
    {
88
      if (len < 2)
89
        return -1;
90

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

    
95
      switch (a[0])
96
        {
97
        case AS_PATH_SET:
98
          copy = 1;
99
          res++;
100
          break;
101

    
102
        case AS_PATH_SEQUENCE:
103
          copy = 1;
104
          res += a[1];
105
          break;
106

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

    
115
          log(L_WARN "%s: %s_PATH attribute contains AS_CONFED_* segment, skipping segment",
116
              p->p.name, as_path ? "AS" : "AS4");
117
          copy = 0;
118
          break;
119

    
120
        default:
121
          return -1;
122
        }
123

    
124
      if (copy)
125
        {
126
          if (dst != a)
127
            memmove(dst, a, plen);
128
          dst += plen;
129
        }
130

    
131
      len -= plen;
132
      a += plen;
133
    }
134

    
135
  *ilength = dst - idata;
136
  return res;
137
}
138

    
139
static inline int
140
validate_as_path(struct bgp_proto *p, byte *a, int *len)
141
{
142
  return validate_path(p, 1, p->as4_session ? 4 : 2, a, len);
143
}
144

    
145
static inline int
146
validate_as4_path(struct bgp_proto *p, struct adata *path)
147
{
148
  return validate_path(p, 0, 4, path->data, &path->length);
149
}
150

    
151
static int
152
bgp_check_next_hop(struct bgp_proto *p UNUSED, byte *a, int len)
153
{
154
#ifdef IPV6
155
  return -1;
156
#else
157
  ip_addr addr;
158

    
159
  memcpy(&addr, a, len);
160
  ipa_ntoh(addr);
161
  if (ipa_classify(addr) & IADDR_HOST)
162
    return 0;
163
  else
164
    return 8;
165
#endif
166
}
167

    
168
static void
169
bgp_format_next_hop(eattr *a, byte *buf, int buflen UNUSED)
170
{
171
  ip_addr *ipp = (ip_addr *) a->u.ptr->data;
172
#ifdef IPV6
173
  /* in IPv6, we might have two addresses in NEXT HOP */
174
  if ((a->u.ptr->length == NEXT_HOP_LENGTH) && ipa_nonzero(ipp[1]))
175
    {
176
      bsprintf(buf, "%I %I", ipp[0], ipp[1]);
177
      return;
178
    }
179
#endif
180

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

    
184
static int
185
bgp_check_aggregator(struct bgp_proto *p, byte *a UNUSED, int len)
186
{
187
  int exp_len = p->as4_session ? 8 : 6;
188
  
189
  return (len == exp_len) ? 0 : 5;
190
}
191

    
192
static void
193
bgp_format_aggregator(eattr *a, byte *buf, int buflen UNUSED)
194
{
195
  struct adata *ad =  a->u.ptr;
196
  byte *data = ad->data;
197
  u32 as;
198

    
199
  as = get_u32(data);
200
  data += 4;
201

    
202
  bsprintf(buf, "%d.%d.%d.%d AS%d", data[0], data[1], data[2], data[3], as);
203
}
204

    
205
static int
206
bgp_check_cluster_list(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
207
{
208
  return ((len % 4) == 0) ? 0 : 5;
209
}
210

    
211
static void
212
bgp_format_cluster_list(eattr *a, byte *buf, int buflen UNUSED)
213
{
214
  int_set_format(a->u.ptr, 0, buf, buflen);
215
}
216

    
217
static int
218
bgp_check_reach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
219
{
220
#ifdef IPV6
221
  p->mp_reach_start = a;
222
  p->mp_reach_len = len;
223
#endif
224
  return -1;
225
}
226

    
227
static int
228
bgp_check_unreach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
229
{
230
#ifdef IPV6
231
  p->mp_unreach_start = a;
232
  p->mp_unreach_len = len;
233
#endif
234
  return -1;
235
}
236

    
237
static struct attr_desc bgp_attr_table[] = {
238
  { NULL, -1, 0, 0, 0,                                                                /* Undefined */
239
    NULL, NULL },
240
  { "origin", 1, BAF_TRANSITIVE, EAF_TYPE_INT, 1,                                /* BA_ORIGIN */
241
    bgp_check_origin, bgp_format_origin },
242
  { "as_path", -1, BAF_TRANSITIVE, EAF_TYPE_AS_PATH, 1,                                /* BA_AS_PATH */
243
    NULL, NULL }, /* is checked by validate_as_path() as a special case */
244
  { "next_hop", 4, BAF_TRANSITIVE, EAF_TYPE_IP_ADDRESS, 1,                        /* BA_NEXT_HOP */
245
    bgp_check_next_hop, bgp_format_next_hop },
246
  { "med", 4, BAF_OPTIONAL, EAF_TYPE_INT, 1,                                        /* BA_MULTI_EXIT_DISC */
247
    NULL, NULL },
248
  { "local_pref", 4, BAF_TRANSITIVE, EAF_TYPE_INT, 0,                                /* BA_LOCAL_PREF */
249
    NULL, NULL },
250
  { "atomic_aggr", 0, BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,                        /* BA_ATOMIC_AGGR */
251
    NULL, NULL },
252
  { "aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,        /* BA_AGGREGATOR */
253
    bgp_check_aggregator, bgp_format_aggregator },
254
  { "community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_INT_SET, 1,        /* BA_COMMUNITY */
255
    NULL, NULL },
256
  { "originator_id", 4, BAF_OPTIONAL, EAF_TYPE_ROUTER_ID, 0,                        /* BA_ORIGINATOR_ID */
257
    NULL, NULL },
258
  { "cluster_list", -1, BAF_OPTIONAL, EAF_TYPE_INT_SET, 0,                        /* BA_CLUSTER_LIST */
259
    bgp_check_cluster_list, bgp_format_cluster_list }, 
260
  { .name = NULL },                                                                /* BA_DPA */
261
  { .name = NULL },                                                                        /* BA_ADVERTISER */
262
  { .name = NULL },                                                                        /* BA_RCID_PATH */
263
  { "mp_reach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1,                        /* BA_MP_REACH_NLRI */
264
    bgp_check_reach_nlri, NULL },
265
  { "mp_unreach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1,                        /* BA_MP_UNREACH_NLRI */
266
    bgp_check_unreach_nlri, NULL },
267
  {  .name = NULL },                                                                        /* BA_EXTENDED_COMM */
268
  { "as4_path", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,                /* BA_AS4_PATH */
269
    NULL, NULL },
270
  { "as4_aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1,        /* BA_AS4_PATH */
271
    NULL, NULL }
272
};
273

    
274
/* BA_AS4_PATH is type EAF_TYPE_OPAQUE and not type EAF_TYPE_AS_PATH.
275
 * It does not matter as this attribute does not appear on routes in the routing table.
276
 */
277

    
278
#define ATTR_KNOWN(code) ((code) < ARRAY_SIZE(bgp_attr_table) && bgp_attr_table[code].name)
279

    
280
static inline struct adata *
281
bgp_alloc_adata(struct linpool *pool, unsigned len)
282
{
283
  struct adata *ad = lp_alloc(pool, sizeof(struct adata) + len);
284
  ad->length = len;
285
  return ad;
286
}
287

    
288
static void
289
bgp_set_attr(eattr *e, unsigned attr, uintptr_t val)
290
{
291
  ASSERT(ATTR_KNOWN(attr));
292
  e->id = EA_CODE(EAP_BGP, attr);
293
  e->type = bgp_attr_table[attr].type;
294
  e->flags = bgp_attr_table[attr].expected_flags;
295
  if (e->type & EAF_EMBEDDED)
296
    e->u.data = val;
297
  else
298
    e->u.ptr = (struct adata *) val;
299
}
300

    
301
static byte *
302
bgp_set_attr_wa(eattr *e, struct linpool *pool, unsigned attr, unsigned len)
303
{
304
  struct adata *ad = bgp_alloc_adata(pool, len);
305
  bgp_set_attr(e, attr, (uintptr_t) ad);
306
  return ad->data;
307
}
308

    
309
void
310
bgp_attach_attr(ea_list **to, struct linpool *pool, unsigned attr, uintptr_t val)
311
{
312
  ea_list *a = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
313
  a->next = *to;
314
  *to = a;
315
  a->flags = EALF_SORTED;
316
  a->count = 1;
317
  bgp_set_attr(a->attrs, attr, val);
318
}
319

    
320
byte *
321
bgp_attach_attr_wa(ea_list **to, struct linpool *pool, unsigned attr, unsigned len)
322
{
323
  struct adata *ad = bgp_alloc_adata(pool, len);
324
  bgp_attach_attr(to, pool, attr, (uintptr_t) ad);
325
  return ad->data;
326
}
327

    
328
static int
329
bgp_encode_attr_hdr(byte *dst, unsigned int flags, unsigned code, int len)
330
{
331
  int wlen;
332

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

    
335
  if (len < 256)
336
    {
337
      *dst++ = flags;
338
      *dst++ = code;
339
      *dst++ = len;
340
      wlen = 3;
341
    }
342
  else
343
    {
344
      *dst++ = flags | BAF_EXT_LEN;
345
      *dst++ = code;
346
      put_u16(dst, len);
347
      wlen = 4;
348
    }
349

    
350
  return wlen;
351
}
352

    
353
static void
354
aggregator_convert_to_old(struct adata *aggr, byte *dst, int *new_used)
355
{
356
  byte *src = aggr->data;
357
  *new_used = 0;
358

    
359
  u32 as = get_u32(src);
360
  if (as > 0xFFFF) 
361
    {
362
      as = AS_TRANS;
363
      *new_used = 1;
364
    }
365
  put_u16(dst, as);
366

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

    
371
static void
372
aggregator_convert_to_new(struct adata *aggr, byte *dst)
373
{
374
  byte *src = aggr->data;
375

    
376
  u32 as   = get_u16(src);
377
  put_u32(dst, as);
378

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

    
383
static int
384
bgp_get_attr_len(eattr *a)
385
{
386
  int len;
387
  if (ATTR_KNOWN(EA_ID(a->id)))
388
    {
389
      int code = EA_ID(a->id);
390
      struct attr_desc *desc = &bgp_attr_table[code];
391
      len = desc->expected_length;
392
      if (len < 0)
393
        {
394
          ASSERT(!(a->type & EAF_EMBEDDED));
395
          len = a->u.ptr->length;
396
        }
397
    }
398
  else
399
    {
400
      ASSERT((a->type & EAF_TYPE_MASK) == EAF_TYPE_OPAQUE);
401
      len = a->u.ptr->length;
402
    }
403
  
404
  return len;
405
}
406

    
407
#define ADVANCE(w, r, l) do { r -= l; w += l; } while (0)
408

    
409
/**
410
 * bgp_encode_attrs - encode BGP attributes
411
 * @p: BGP instance
412
 * @w: buffer
413
 * @attrs: a list of extended attributes
414
 * @remains: remaining space in the buffer
415
 *
416
 * The bgp_encode_attrs() function takes a list of extended attributes
417
 * and converts it to its BGP representation (a part of an Update message).
418
 *
419
 * Result: Length of the attribute block generated or -1 if not enough space.
420
 */
421
unsigned int
422
bgp_encode_attrs(struct bgp_proto *p, byte *w, ea_list *attrs, int remains)
423
{
424
  unsigned int i, code, flags;
425
  byte *start = w;
426
  int len, rv;
427

    
428
  for(i=0; i<attrs->count; i++)
429
    {
430
      eattr *a = &attrs->attrs[i];
431
      ASSERT(EA_PROTO(a->id) == EAP_BGP);
432
      code = EA_ID(a->id);
433
#ifdef IPV6
434
      /* When talking multiprotocol BGP, the NEXT_HOP attributes are used only temporarily. */
435
      if (code == BA_NEXT_HOP)
436
        continue;
437
#endif
438

    
439
      /* When AS4-aware BGP speaker is talking to non-AS4-aware BGP speaker,
440
       * we have to convert our 4B AS_PATH to 2B AS_PATH and send our AS_PATH 
441
       * as optional AS4_PATH attribute.
442
       */
443
      if ((code == BA_AS_PATH) && (! p->as4_session))
444
        {
445
          len = a->u.ptr->length;
446

    
447
          if (remains < (len + 4))
448
            goto err_no_buffer;
449

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

    
458
          DBG("BGP: Encoding old AS_PATH\n");
459
          rv = bgp_encode_attr_hdr(w, BAF_TRANSITIVE, BA_AS_PATH, nl);
460
          ADVANCE(w, remains, rv);
461
          memcpy(w, buf, nl);
462
          ADVANCE(w, remains, nl);
463

    
464
          if (! new_used)
465
            continue;
466

    
467
          if (remains < (len + 4))
468
            goto err_no_buffer;
469

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

    
475
          DBG("BGP: Encoding AS4_PATH\n");
476
          rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AS4_PATH, len);
477
          ADVANCE(w, remains, rv);
478
          memcpy(w, a->u.ptr->data, len);
479
          ADVANCE(w, remains, len);
480

    
481
          continue;
482
        }
483

    
484
      /* The same issue with AGGREGATOR attribute */
485
      if ((code == BA_AGGREGATOR) && (! p->as4_session))
486
        {
487
          int new_used;
488

    
489
          len = 6;
490
          if (remains < (len + 3))
491
            goto err_no_buffer;
492

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

    
498
          if (! new_used)
499
            continue;
500

    
501
          len = 8;
502
          if (remains < (len + 3))
503
            goto err_no_buffer;
504

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

    
510
          continue;
511
        }
512

    
513
      /* Standard path continues here ... */
514

    
515
      flags = a->flags & (BAF_OPTIONAL | BAF_TRANSITIVE | BAF_PARTIAL);
516
      len = bgp_get_attr_len(a);
517

    
518
      if (remains < len + 4)
519
        goto err_no_buffer;
520

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

    
524
      switch (a->type & EAF_TYPE_MASK)
525
        {
526
        case EAF_TYPE_INT:
527
        case EAF_TYPE_ROUTER_ID:
528
          if (len == 4)
529
            put_u32(w, a->u.data);
530
          else
531
            *w = a->u.data;
532
          break;
533
        case EAF_TYPE_IP_ADDRESS:
534
          {
535
            ip_addr ip = *(ip_addr *)a->u.ptr->data;
536
            ipa_hton(ip);
537
            memcpy(w, &ip, len);
538
            break;
539
          }
540
        case EAF_TYPE_INT_SET:
541
          {
542
            u32 *z = (u32 *)a->u.ptr->data;
543
            int i;
544
            for(i=0; i<len; i+=4)
545
              put_u32(w+i, *z++);
546
            break;
547
          }
548
        case EAF_TYPE_OPAQUE:
549
        case EAF_TYPE_AS_PATH:
550
          memcpy(w, a->u.ptr->data, len);
551
          break;
552
        default:
553
          bug("bgp_encode_attrs: unknown attribute type %02x", a->type);
554
        }
555
      ADVANCE(w, remains, len);
556
    }
557
  return w - start;
558

    
559
 err_no_buffer:
560
  return -1;
561
}
562

    
563
static void
564
bgp_init_prefix(struct fib_node *N)
565
{
566
  struct bgp_prefix *p = (struct bgp_prefix *) N;
567
  p->bucket_node.next = NULL;
568
}
569

    
570
static int
571
bgp_compare_u32(const u32 *x, const u32 *y)
572
{
573
  return (*x < *y) ? -1 : (*x > *y) ? 1 : 0;
574
}
575

    
576
static void
577
bgp_normalize_set(u32 *dest, u32 *src, unsigned cnt)
578
{
579
  memcpy(dest, src, sizeof(u32) * cnt);
580
  qsort(dest, cnt, sizeof(u32), (int(*)(const void *, const void *)) bgp_compare_u32);
581
}
582

    
583
static void
584
bgp_rehash_buckets(struct bgp_proto *p)
585
{
586
  struct bgp_bucket **old = p->bucket_hash;
587
  struct bgp_bucket **new;
588
  unsigned oldn = p->hash_size;
589
  unsigned i, e, mask;
590
  struct bgp_bucket *b;
591

    
592
  p->hash_size = p->hash_limit;
593
  DBG("BGP: Rehashing bucket table from %d to %d\n", oldn, p->hash_size);
594
  p->hash_limit *= 4;
595
  if (p->hash_limit >= 65536)
596
    p->hash_limit = ~0;
597
  new = p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
598
  mask = p->hash_size - 1;
599
  for (i=0; i<oldn; i++)
600
    while (b = old[i])
601
      {
602
        old[i] = b->hash_next;
603
        e = b->hash & mask;
604
        b->hash_next = new[e];
605
        if (b->hash_next)
606
          b->hash_next->hash_prev = b;
607
        b->hash_prev = NULL;
608
        new[e] = b;
609
      }
610
  mb_free(old);
611
}
612

    
613
static struct bgp_bucket *
614
bgp_new_bucket(struct bgp_proto *p, ea_list *new, unsigned hash)
615
{
616
  struct bgp_bucket *b;
617
  unsigned ea_size = sizeof(ea_list) + new->count * sizeof(eattr);
618
  unsigned ea_size_aligned = BIRD_ALIGN(ea_size, CPU_STRUCT_ALIGN);
619
  unsigned size = sizeof(struct bgp_bucket) + ea_size;
620
  unsigned i;
621
  byte *dest;
622
  unsigned index = hash & (p->hash_size - 1);
623

    
624
  /* Gather total size of non-inline attributes */
625
  for (i=0; i<new->count; i++)
626
    {
627
      eattr *a = &new->attrs[i];
628
      if (!(a->type & EAF_EMBEDDED))
629
        size += BIRD_ALIGN(sizeof(struct adata) + a->u.ptr->length, CPU_STRUCT_ALIGN);
630
    }
631

    
632
  /* Create the bucket and hash it */
633
  b = mb_alloc(p->p.pool, size);
634
  b->hash_next = p->bucket_hash[index];
635
  if (b->hash_next)
636
    b->hash_next->hash_prev = b;
637
  p->bucket_hash[index] = b;
638
  b->hash_prev = NULL;
639
  b->hash = hash;
640
  add_tail(&p->bucket_queue, &b->send_node);
641
  init_list(&b->prefixes);
642
  memcpy(b->eattrs, new, ea_size);
643
  dest = ((byte *)b->eattrs) + ea_size_aligned;
644

    
645
  /* Copy values of non-inline attributes */
646
  for (i=0; i<new->count; i++)
647
    {
648
      eattr *a = &b->eattrs->attrs[i];
649
      if (!(a->type & EAF_EMBEDDED))
650
        {
651
          struct adata *oa = a->u.ptr;
652
          struct adata *na = (struct adata *) dest;
653
          memcpy(na, oa, sizeof(struct adata) + oa->length);
654
          a->u.ptr = na;
655
          dest += BIRD_ALIGN(sizeof(struct adata) + na->length, CPU_STRUCT_ALIGN);
656
        }
657
    }
658

    
659
  /* If needed, rehash */
660
  p->hash_count++;
661
  if (p->hash_count > p->hash_limit)
662
    bgp_rehash_buckets(p);
663

    
664
  return b;
665
}
666

    
667
static struct bgp_bucket *
668
bgp_get_bucket(struct bgp_proto *p, net *n, ea_list *attrs, int originate)
669
{
670
  ea_list *new;
671
  unsigned i, cnt, hash, code;
672
  eattr *a, *d;
673
  u32 seen = 0;
674
  struct bgp_bucket *b;
675

    
676
  /* Merge the attribute list */
677
  new = alloca(ea_scan(attrs));
678
  ea_merge(attrs, new);
679
  ea_sort(new);
680

    
681
  /* Normalize attributes */
682
  d = new->attrs;
683
  cnt = new->count;
684
  new->count = 0;
685
  for(i=0; i<cnt; i++)
686
    {
687
      a = &new->attrs[i];
688
#ifdef LOCAL_DEBUG
689
      {
690
        byte buf[EA_FORMAT_BUF_SIZE];
691
        ea_format(a, buf);
692
        DBG("\t%s\n", buf);
693
      }
694
#endif
695
      if (EA_PROTO(a->id) != EAP_BGP)
696
        continue;
697
      code = EA_ID(a->id);
698
      if (ATTR_KNOWN(code))
699
        {
700
          if (!bgp_attr_table[code].allow_in_ebgp && !p->is_internal)
701
            continue;
702
          /* The flags might have been zero if the attr was added by filters */
703
          a->flags = (a->flags & BAF_PARTIAL) | bgp_attr_table[code].expected_flags;
704
          if (code < 32)
705
            seen |= 1 << code;
706
        }
707
      else
708
        {
709
          /* Don't re-export unknown non-transitive attributes */
710
          if (!(a->flags & BAF_TRANSITIVE))
711
            continue;
712
        }
713
      *d = *a;
714
      if ((d->type & EAF_ORIGINATED) && !originate && (d->flags & BAF_TRANSITIVE) && (d->flags & BAF_OPTIONAL))
715
        d->flags |= BAF_PARTIAL;
716
      switch (d->type & EAF_TYPE_MASK)
717
        {
718
        case EAF_TYPE_INT_SET:
719
          {
720
            struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
721
            z->length = d->u.ptr->length;
722
            bgp_normalize_set((u32 *) z->data, (u32 *) d->u.ptr->data, z->length / 4);
723
            d->u.ptr = z;
724
            break;
725
          }
726
        default: ;
727
        }
728
      d++;
729
      new->count++;
730
    }
731

    
732
  /* Hash */
733
  hash = ea_hash(new);
734
  for(b=p->bucket_hash[hash & (p->hash_size - 1)]; b; b=b->hash_next)
735
    if (b->hash == hash && ea_same(b->eattrs, new))
736
      {
737
        DBG("Found bucket.\n");
738
        return b;
739
      }
740

    
741
  /* Ensure that there are all mandatory attributes */
742
  for(i=0; i<ARRAY_SIZE(bgp_mandatory_attrs); i++)
743
    if (!(seen & (1 << bgp_mandatory_attrs[i])))
744
      {
745
        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);
746
        return NULL;
747
      }
748

    
749
  /* Check if next hop is valid */
750
  a = ea_find(new, EA_CODE(EAP_BGP, BA_NEXT_HOP));
751
  if (!a || ipa_equal(p->next_hop, *(ip_addr *)a->u.ptr->data))
752
    {
753
      log(L_ERR "%s: Invalid NEXT_HOP attribute in route %I/%d", p->p.name, n->n.prefix, n->n.pxlen);
754
      return NULL;
755
    }
756

    
757
  /* Create new bucket */
758
  DBG("Creating bucket.\n");
759
  return bgp_new_bucket(p, new, hash);
760
}
761

    
762
void
763
bgp_free_bucket(struct bgp_proto *p, struct bgp_bucket *buck)
764
{
765
  if (buck->hash_next)
766
    buck->hash_next->hash_prev = buck->hash_prev;
767
  if (buck->hash_prev)
768
    buck->hash_prev->hash_next = buck->hash_next;
769
  else
770
    p->bucket_hash[buck->hash & (p->hash_size-1)] = buck->hash_next;
771
  mb_free(buck);
772
}
773

    
774
void
775
bgp_rt_notify(struct proto *P, rtable *tbl UNUSED, net *n, rte *new, rte *old UNUSED, ea_list *attrs)
776
{
777
  struct bgp_proto *p = (struct bgp_proto *) P;
778
  struct bgp_bucket *buck;
779
  struct bgp_prefix *px;
780

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

    
783
  if (new)
784
    {
785
      buck = bgp_get_bucket(p, n, attrs, new->attrs->source != RTS_BGP);
786
      if (!buck)                        /* Inconsistent attribute list */
787
        return;
788
    }
789
  else
790
    {
791
      if (!(buck = p->withdraw_bucket))
792
        {
793
          buck = p->withdraw_bucket = mb_alloc(P->pool, sizeof(struct bgp_bucket));
794
          init_list(&buck->prefixes);
795
        }
796
    }
797
  px = fib_get(&p->prefix_fib, &n->n.prefix, n->n.pxlen);
798
  if (px->bucket_node.next)
799
    {
800
      DBG("\tRemoving old entry.\n");
801
      rem_node(&px->bucket_node);
802
    }
803
  add_tail(&buck->prefixes, &px->bucket_node);
804
  bgp_schedule_packet(p->conn, PKT_UPDATE);
805
}
806

    
807

    
808
static int
809
bgp_create_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool)
810
{
811
  ea_list *ea = lp_alloc(pool, sizeof(ea_list) + 4*sizeof(eattr));
812
  rta *rta = e->attrs;
813
  byte *z;
814

    
815
  ea->next = *attrs;
816
  *attrs = ea;
817
  ea->flags = EALF_SORTED;
818
  ea->count = 4;
819

    
820
  bgp_set_attr(ea->attrs, BA_ORIGIN,
821
       ((rta->source == RTS_OSPF_EXT1) || (rta->source == RTS_OSPF_EXT2)) ? ORIGIN_INCOMPLETE : ORIGIN_IGP);
822

    
823
  if (p->is_internal)
824
    bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 0);
825
  else
826
    {
827
      z = bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 6);
828
      z[0] = AS_PATH_SEQUENCE;
829
      z[1] = 1;                                /* 1 AS */
830
      put_u32(z+2, p->local_as);
831
    }
832

    
833
  z = bgp_set_attr_wa(ea->attrs+2, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
834
  if (p->cf->next_hop_self ||
835
      rta->dest != RTD_ROUTER ||
836
      ipa_equal(e->attrs->gw, IPA_NONE) ||
837
      ipa_has_link_scope(rta->gw) ||
838
      (!p->is_internal && (rta->iface != p->neigh->iface)))
839
    set_next_hop(z, p->source_addr);
840
  else
841
    set_next_hop(z, rta->gw);
842

    
843
  bgp_set_attr(ea->attrs+3, BA_LOCAL_PREF, p->cf->default_local_pref);
844

    
845
  return 0;                                /* Leave decision to the filters */
846
}
847

    
848

    
849
static inline int
850
bgp_as_path_loopy(struct bgp_proto *p, rta *a)
851
{
852
  eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
853
  return (e && as_path_is_member(e->u.ptr, p->local_as));
854
}
855

    
856
static inline int
857
bgp_originator_id_loopy(struct bgp_proto *p, rta *a)
858
{
859
  eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
860
  return (e && (e->u.data == p->local_id));
861
}
862

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

    
870

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

    
878
static inline void
879
bgp_cluster_list_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 cid)
880
{
881
  eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
882
  bgp_attach_attr(attrs, pool, BA_CLUSTER_LIST, (uintptr_t) int_set_add(pool, a ? a->u.ptr : NULL, cid));
883
}
884

    
885
static int
886
bgp_update_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool, int rr)
887
{
888
  eattr *a;
889

    
890
  if (!p->is_internal && !p->rs_client)
891
    {
892
      bgp_path_prepend(e, attrs, pool, p->local_as);
893

    
894
      /* The MULTI_EXIT_DISC attribute received from a neighboring AS MUST NOT be
895
       * propagated to other neighboring ASes.
896
       * Perhaps it would be better to undefine it.
897
       */
898
      a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
899
      if (a)
900
        bgp_attach_attr(attrs, pool, BA_MULTI_EXIT_DISC, 0);
901
    }
902

    
903
  a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
904
  if (a && !p->cf->next_hop_self && (p->is_internal || (!p->is_internal && e->attrs->iface == p->neigh->iface)))
905
    {
906
      /* Leave the original next hop attribute, will check later where does it point */
907
    }
908
  else
909
    {
910
      /* Need to create new one */
911
      byte *b = bgp_attach_attr_wa(attrs, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
912
      set_next_hop(b, p->source_addr);
913
    }
914

    
915
  if (rr)
916
    {
917
      /* Handling route reflection, RFC 4456 */
918
      struct bgp_proto *src = (struct bgp_proto *) e->attrs->proto;
919

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

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

    
927
      /* Two RR clients with different cluster ID, hmmm */
928
      if (src->rr_client && p->rr_client && (src->rr_cluster_id != p->rr_cluster_id))
929
        bgp_cluster_list_prepend(e, attrs, pool, p->rr_cluster_id);
930
    }
931

    
932
  return 0;                                /* Leave decision to the filters */
933
}
934

    
935
static int
936
bgp_community_filter(struct bgp_proto *p, rte *e)
937
{
938
  eattr *a;
939
  struct adata *d;
940

    
941
  /* Check if we aren't forbidden to export the route by communities */
942
  a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_COMMUNITY));
943
  if (a)
944
    {
945
      d = a->u.ptr;
946
      if (int_set_contains(d, BGP_COMM_NO_ADVERTISE))
947
        {
948
          DBG("\tNO_ADVERTISE\n");
949
          return 1;
950
        }
951
      if (!p->is_internal &&
952
          (int_set_contains(d, BGP_COMM_NO_EXPORT) ||
953
           int_set_contains(d, BGP_COMM_NO_EXPORT_SUBCONFED)))
954
        {
955
          DBG("\tNO_EXPORT\n");
956
          return 1;
957
        }
958
    }
959

    
960
  return 0;
961
}
962

    
963
int
964
bgp_import_control(struct proto *P, rte **new, ea_list **attrs, struct linpool *pool)
965
{
966
  rte *e = *new;
967
  struct bgp_proto *p = (struct bgp_proto *) P;
968
  struct bgp_proto *new_bgp = (e->attrs->proto->proto == &proto_bgp) ? (struct bgp_proto *) e->attrs->proto : NULL;
969

    
970
  if (p == new_bgp)                        /* Poison reverse updates */
971
    return -1;
972
  if (new_bgp)
973
    {
974
      /* We should check here for cluster list loop, because the receiving BGP instance
975
         might have different cluster ID  */
976
      if (bgp_cluster_list_loopy(p, e->attrs))
977
        return -1;
978

    
979
      if (p->cf->interpret_communities && bgp_community_filter(p, e))
980
        return -1;
981

    
982
      if (p->local_as == new_bgp->local_as && p->is_internal && new_bgp->is_internal)
983
        {
984
          /* Redistribution of internal routes with IBGP */
985
          if (p->rr_client || new_bgp->rr_client)
986
            /* Route reflection, RFC 4456 */
987
            return bgp_update_attrs(p, e, attrs, pool, 1);
988
          else
989
            return -1;
990
        }
991
      else
992
        return bgp_update_attrs(p, e, attrs, pool, 0);
993
    }
994
  else
995
    return bgp_create_attrs(p, e, attrs, pool);
996
}
997

    
998
static inline u32
999
bgp_get_neighbor(rte *r)
1000
{
1001
  eattr *e = ea_find(r->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1002
  u32 as;
1003

    
1004
  if (e && as_path_get_first(e->u.ptr, &as))
1005
    return as;
1006
  else
1007
    return ((struct bgp_proto *) r->attrs->proto)->remote_as;
1008
}
1009

    
1010
int
1011
bgp_rte_better(rte *new, rte *old)
1012
{
1013
  struct bgp_proto *new_bgp = (struct bgp_proto *) new->attrs->proto;
1014
  struct bgp_proto *old_bgp = (struct bgp_proto *) old->attrs->proto;
1015
  eattr *x, *y;
1016
  u32 n, o;
1017

    
1018
  /* Start with local preferences */
1019
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
1020
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_LOCAL_PREF));
1021
  n = x ? x->u.data : new_bgp->cf->default_local_pref;
1022
  o = y ? y->u.data : old_bgp->cf->default_local_pref;
1023
  if (n > o)
1024
    return 1;
1025
  if (n < o)
1026
    return 0;
1027

    
1028
  /* RFC 4271 9.1.2.2. a)  Use AS path lengths */
1029
  if (new_bgp->cf->compare_path_lengths || old_bgp->cf->compare_path_lengths)
1030
    {
1031
      x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1032
      y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1033
      n = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
1034
      o = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
1035
      if (n < o)
1036
        return 1;
1037
      if (n > o)
1038
        return 0;
1039
    }
1040

    
1041
  /* RFC 4271 9.1.2.2. b) Use origins */
1042
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1043
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1044
  n = x ? x->u.data : ORIGIN_INCOMPLETE;
1045
  o = y ? y->u.data : ORIGIN_INCOMPLETE;
1046
  if (n < o)
1047
    return 1;
1048
  if (n > o)
1049
    return 0;
1050

    
1051
  /* RFC 4271 9.1.2.2. c) Compare MED's */
1052
  if (bgp_get_neighbor(new) == bgp_get_neighbor(old))
1053
    {
1054
      x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
1055
      y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
1056
      n = x ? x->u.data : new_bgp->cf->default_med;
1057
      o = y ? y->u.data : old_bgp->cf->default_med;
1058
      if (n < o)
1059
        return 1;
1060
      if (n > o)
1061
        return 0;
1062
    }
1063

    
1064
  /* RFC 4271 9.1.2.2. d) Prefer external peers */
1065
  if (new_bgp->is_internal > old_bgp->is_internal)
1066
    return 0;
1067
  if (new_bgp->is_internal < old_bgp->is_internal)
1068
    return 1;
1069

    
1070
  /* Skipping RFC 4271 9.1.2.2. e) */
1071
  /* We don't have interior distances */
1072

    
1073
  /* RFC 4456 9. b) Compare cluster list lengths */
1074
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
1075
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
1076
  n = x ? int_set_get_size(x->u.ptr) : 0;
1077
  o = y ? int_set_get_size(y->u.ptr) : 0;
1078
  if (n < o)
1079
    return 1;
1080
  if (n > o)
1081
    return 0;
1082

    
1083
  /* RFC 4271 9.1.2.2. f) Compare BGP identifiers */
1084
  /* RFC 4456 9. a) Use ORIGINATOR_ID instead of local neighor ID */
1085
  x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1086
  y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
1087
  n = x ? x->u.data : new_bgp->remote_id;
1088
  o = y ? y->u.data : old_bgp->remote_id;
1089

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

    
1096
  /* rest of RFC 4271 9.1.2.2. f) */
1097
  if (n < o)
1098
    return 1;
1099
  if (n > o)
1100
    return 0;
1101

    
1102
  /* RFC 4271 9.1.2.2. g) Compare peer IP adresses */
1103
  return (ipa_compare(new_bgp->cf->remote_ip, old_bgp->cf->remote_ip) < 0);
1104
}
1105

    
1106
static struct adata *
1107
bgp_aggregator_convert_to_new(struct adata *old, struct linpool *pool)
1108
{
1109
  struct adata *newa = lp_alloc(pool, sizeof(struct adata) + 8);
1110
  newa->length = 8;
1111
  aggregator_convert_to_new(old, newa->data);
1112
  return newa;
1113
}
1114

    
1115

    
1116
/* Take last req_as ASNs from path old2 (in 2B format), convert to 4B format
1117
 * and append path old4 (in 4B format).
1118
 */
1119
static struct adata *
1120
bgp_merge_as_paths(struct adata *old2, struct adata *old4, int req_as, struct linpool *pool)
1121
{
1122
  byte buf[old2->length * 2];
1123

    
1124
  int ol = as_path_convert_to_new(old2, buf, req_as);
1125
  int nl = ol + (old4 ? old4->length : 0);
1126

    
1127
  struct adata *newa = lp_alloc(pool, sizeof(struct adata) + nl);
1128
  newa->length = nl;
1129
  memcpy(newa->data, buf, ol);
1130
  if (old4) memcpy(newa->data + ol, old4->data, old4->length);
1131

    
1132
  return newa;
1133
}
1134

    
1135
static int
1136
as4_aggregator_valid(struct adata *aggr)
1137
{
1138
  if (aggr->length != 8)
1139
    return 0;
1140

    
1141
  u32 *a = (u32 *) aggr->data;
1142

    
1143
  if ((a[0] == 0) || (a[1] == 0))
1144
    return 0;
1145

    
1146
  return 1;
1147
}
1148

    
1149

    
1150
/* Reconstruct 4B AS_PATH and AGGREGATOR according to RFC 4893 4.2.3 */
1151
static void
1152
bgp_reconstruct_4b_atts(struct bgp_proto *p, rta *a, struct linpool *pool)
1153
{
1154
  eattr *p2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1155
  eattr *p4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_PATH));
1156
  eattr *a2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AGGREGATOR));
1157
  eattr *a4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR));
1158
  int a4_removed = 0;
1159

    
1160
  if (a4 && !as4_aggregator_valid(a4->u.ptr))
1161
    {
1162
      log(L_WARN "%s: AS4_AGGREGATOR attribute is invalid, skipping attribute", p->p.name);
1163
      a4 = NULL;
1164
      a4_removed = 1;
1165
    }
1166

    
1167
  if (a2)
1168
    {
1169
      u32 a2_as = get_u16(a2->u.ptr->data);
1170

    
1171
      if (a4)
1172
        {
1173
          if (a2_as != AS_TRANS)
1174
            {
1175
              /* Routes were aggregated by old router and therefore AS4_PATH
1176
               * and AS4_AGGREGATOR is invalid
1177
               *
1178
               * Convert AS_PATH and AGGREGATOR to 4B format and finish.
1179
               */
1180

    
1181
              a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
1182
              p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
1183

    
1184
              return;
1185
            }
1186
          else
1187
            {
1188
              /* Common case, use AS4_AGGREGATOR attribute */
1189
              a2->u.ptr = a4->u.ptr;
1190
            }
1191
        }
1192
      else
1193
        {
1194
          /* Common case, use old AGGREGATOR attribute */
1195
          a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
1196

    
1197
          if ((a2_as == AS_TRANS) && !a4_removed)
1198
            log(L_WARN "%s: AGGREGATOR attribute contain AS_TRANS, but AS4_AGGREGATOR is missing", p->p.name);
1199
        }
1200
    }
1201
  else
1202
    if (a4)
1203
      log(L_WARN "%s: AS4_AGGREGATOR attribute received, but AGGREGATOR attribute is missing", p->p.name);
1204

    
1205
  int p2_len = as_path_getlen_int(p2->u.ptr, 2);
1206
  int p4_len = p4 ? validate_as4_path(p, p4->u.ptr) : -1;
1207

    
1208
  if (p4 && (p4_len < 0))
1209
    log(L_WARN "%s: AS4_PATH attribute is malformed, skipping attribute", p->p.name);
1210

    
1211
  if ((p4_len <= 0) || (p2_len < p4_len))
1212
    p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
1213
  else
1214
    p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, p4->u.ptr, p2_len - p4_len, pool);
1215
}
1216

    
1217
static void
1218
bgp_remove_as4_attrs(struct bgp_proto *p, rta *a)
1219
{
1220
  unsigned id1 = EA_CODE(EAP_BGP, BA_AS4_PATH);
1221
  unsigned id2 = EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR);
1222
  ea_list **el = &(a->eattrs);
1223

    
1224
  /* We know that ea_lists constructed in bgp_decode attrs have one attribute per ea_list struct */
1225
  while (*el != NULL)
1226
    {
1227
      unsigned fid = (*el)->attrs[0].id;
1228

    
1229
      if ((fid == id1) || (fid == id2))
1230
        {
1231
          *el = (*el)->next;
1232
          if (p->as4_session)
1233
            log(L_WARN "BGP: Unexpected AS4_* attributes received");
1234
        }
1235
      else
1236
        el = &((*el)->next);
1237
    }
1238
}
1239

    
1240
/**
1241
 * bgp_decode_attrs - check and decode BGP attributes
1242
 * @conn: connection
1243
 * @attr: start of attribute block
1244
 * @len: length of attribute block
1245
 * @pool: linear pool to make all the allocations in
1246
 * @mandatory: 1 iff presence of mandatory attributes has to be checked
1247
 *
1248
 * This function takes a BGP attribute block (a part of an Update message), checks
1249
 * its consistency and converts it to a list of BIRD route attributes represented
1250
 * by a &rta.
1251
 */
1252
struct rta *
1253
bgp_decode_attrs(struct bgp_conn *conn, byte *attr, unsigned int len, struct linpool *pool, int mandatory)
1254
{
1255
  struct bgp_proto *bgp = conn->bgp;
1256
  rta *a = lp_alloc(pool, sizeof(struct rta));
1257
  unsigned int flags, code, l, i, type;
1258
  int errcode;
1259
  byte *z, *attr_start;
1260
  byte seen[256/8];
1261
  ea_list *ea;
1262
  struct adata *ad;
1263

    
1264
  a->proto = &bgp->p;
1265
  a->source = RTS_BGP;
1266
  a->scope = SCOPE_UNIVERSE;
1267
  a->cast = RTC_UNICAST;
1268
  a->dest = RTD_ROUTER;
1269
  a->flags = 0;
1270
  a->aflags = 0;
1271
  a->from = bgp->cf->remote_ip;
1272
  a->eattrs = NULL;
1273

    
1274
  /* Parse the attributes */
1275
  bzero(seen, sizeof(seen));
1276
  DBG("BGP: Parsing attributes\n");
1277
  while (len)
1278
    {
1279
      if (len < 2)
1280
        goto malformed;
1281
      attr_start = attr;
1282
      flags = *attr++;
1283
      code = *attr++;
1284
      len -= 2;
1285
      if (flags & BAF_EXT_LEN)
1286
        {
1287
          if (len < 2)
1288
            goto malformed;
1289
          l = get_u16(attr);
1290
          attr += 2;
1291
          len -= 2;
1292
        }
1293
      else
1294
        {
1295
          if (len < 1)
1296
            goto malformed;
1297
          l = *attr++;
1298
          len--;
1299
        }
1300
      if (l > len)
1301
        goto malformed;
1302
      len -= l;
1303
      z = attr;
1304
      attr += l;
1305
      DBG("Attr %02x %02x %d\n", code, flags, l);
1306
      if (seen[code/8] & (1 << (code%8)))
1307
        goto malformed;
1308
      if (ATTR_KNOWN(code))
1309
        {
1310
          struct attr_desc *desc = &bgp_attr_table[code];
1311
          if (desc->expected_length >= 0 && desc->expected_length != (int) l)
1312
            { errcode = 5; goto err; }
1313
          if ((desc->expected_flags ^ flags) & (BAF_OPTIONAL | BAF_TRANSITIVE))
1314
            { errcode = 4; goto err; }
1315
          if (!desc->allow_in_ebgp && !bgp->is_internal)
1316
            continue;
1317
          if (desc->validate)
1318
            {
1319
              errcode = desc->validate(bgp, z, l);
1320
              if (errcode > 0)
1321
                goto err;
1322
              if (errcode < 0)
1323
                continue;
1324
            }
1325
          else if (code == BA_AS_PATH)
1326
            {
1327
              /* Special case as it might also trim the attribute */
1328
              if (validate_as_path(bgp, z, &l) < 0)
1329
                { errcode = 11; goto err; }
1330
            }
1331
          type = desc->type;
1332
        }
1333
      else                                /* Unknown attribute */
1334
        {
1335
          if (!(flags & BAF_OPTIONAL))
1336
            { errcode = 2; goto err; }
1337
          type = EAF_TYPE_OPAQUE;
1338
        }
1339
      
1340
      // Only OPTIONAL and TRANSITIVE attributes may have non-zero PARTIAL flag
1341
      // if (!((flags & BAF_OPTIONAL) && (flags & BAF_TRANSITIVE)) && (flags & BAF_PARTIAL))
1342
      //   { errcode = 4; goto err; }
1343

    
1344
      seen[code/8] |= (1 << (code%8));
1345
      ea = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
1346
      ea->next = a->eattrs;
1347
      a->eattrs = ea;
1348
      ea->flags = 0;
1349
      ea->count = 1;
1350
      ea->attrs[0].id = EA_CODE(EAP_BGP, code);
1351
      ea->attrs[0].flags = flags;
1352
      ea->attrs[0].type = type;
1353
      if (type & EAF_EMBEDDED)
1354
        ad = NULL;
1355
      else
1356
        {
1357
          ad = lp_alloc(pool, sizeof(struct adata) + l);
1358
          ea->attrs[0].u.ptr = ad;
1359
          ad->length = l;
1360
          memcpy(ad->data, z, l);
1361
        }
1362
      switch (type)
1363
        {
1364
        case EAF_TYPE_ROUTER_ID:
1365
        case EAF_TYPE_INT:
1366
          if (l == 1)
1367
            ea->attrs[0].u.data = *z;
1368
          else
1369
            ea->attrs[0].u.data = get_u32(z);
1370
          break;
1371
        case EAF_TYPE_IP_ADDRESS:
1372
          ipa_ntoh(*(ip_addr *)ad->data);
1373
          break;
1374
        case EAF_TYPE_INT_SET:
1375
          {
1376
            u32 *z = (u32 *) ad->data;
1377
            for(i=0; i<ad->length/4; i++)
1378
              z[i] = ntohl(z[i]);
1379
            break;
1380
          }
1381
        }
1382
    }
1383

    
1384
#ifdef IPV6
1385
  /* If we received MP_REACH_NLRI we should check mandatory attributes */
1386
  if (bgp->mp_reach_len != 0)
1387
    mandatory = 1;
1388
#endif
1389

    
1390
  /* If there is no (reachability) NLRI, we should exit now */
1391
  if (! mandatory)
1392
    return a;
1393

    
1394
  /* Check if all mandatory attributes are present */
1395
  for(i=0; i < ARRAY_SIZE(bgp_mandatory_attrs); i++)
1396
    {
1397
      code = bgp_mandatory_attrs[i];
1398
      if (!(seen[code/8] & (1 << (code%8))))
1399
        {
1400
          bgp_error(conn, 3, 3, &bgp_mandatory_attrs[i], 1);
1401
          return NULL;
1402
        }
1403
    }
1404

    
1405
  /* When receiving attributes from non-AS4-aware BGP speaker,
1406
   * we have to reconstruct 4B AS_PATH and AGGREGATOR attributes
1407
   */
1408
  if (! bgp->as4_session)
1409
    bgp_reconstruct_4b_atts(bgp, a, pool);
1410

    
1411
  bgp_remove_as4_attrs(bgp, a);
1412

    
1413
  /* If the AS path attribute contains our AS, reject the routes */
1414
  if (bgp_as_path_loopy(bgp, a))
1415
    goto loop;
1416

    
1417
  /* Two checks for IBGP loops caused by route reflection, RFC 4456 */ 
1418
  if (bgp_originator_id_loopy(bgp, a) ||
1419
      bgp_cluster_list_loopy(bgp, a))
1420
    goto loop;
1421

    
1422
  /* If there's no local preference, define one */
1423
  if (!(seen[0] & (1 << BA_LOCAL_PREF)))
1424
    bgp_attach_attr(&a->eattrs, pool, BA_LOCAL_PREF, bgp->cf->default_local_pref);
1425

    
1426
  return a;
1427

    
1428
loop:
1429
  DBG("BGP: Path loop!\n");
1430
  return NULL;
1431

    
1432
malformed:
1433
  bgp_error(conn, 3, 1, NULL, 0);
1434
  return NULL;
1435

    
1436
err:
1437
  bgp_error(conn, 3, errcode, attr_start, z+l-attr_start);
1438
  return NULL;
1439
}
1440

    
1441
int
1442
bgp_get_attr(eattr *a, byte *buf, int buflen)
1443
{
1444
  unsigned int i = EA_ID(a->id);
1445
  struct attr_desc *d;
1446

    
1447
  if (ATTR_KNOWN(i))
1448
    {
1449
      d = &bgp_attr_table[i];
1450
      buf += bsprintf(buf, "%s", d->name);
1451
      if (d->format)
1452
        {
1453
          *buf++ = ':';
1454
          *buf++ = ' ';
1455
          d->format(a, buf, buflen);
1456
          return GA_FULL;
1457
        }
1458
      return GA_NAME;
1459
    }
1460
  bsprintf(buf, "%02x%s", i, (a->flags & BAF_TRANSITIVE) ? " [t]" : "");
1461
  return GA_NAME;
1462
}
1463

    
1464
void
1465
bgp_attr_init(struct bgp_proto *p)
1466
{
1467
  p->hash_size = 256;
1468
  p->hash_limit = p->hash_size * 4;
1469
  p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
1470
  init_list(&p->bucket_queue);
1471
  p->withdraw_bucket = NULL;
1472
  fib_init(&p->prefix_fib, p->p.pool, sizeof(struct bgp_prefix), 0, bgp_init_prefix);
1473
}
1474

    
1475
void
1476
bgp_get_route_info(rte *e, byte *buf, ea_list *attrs)
1477
{
1478
  eattr *p = ea_find(attrs, EA_CODE(EAP_BGP, BA_AS_PATH));
1479
  eattr *o = ea_find(attrs, EA_CODE(EAP_BGP, BA_ORIGIN));
1480
  u32 origas;
1481

    
1482
  buf += bsprintf(buf, " (%d) [", e->pref);
1483
  if (p && as_path_get_last(p->u.ptr, &origas))
1484
    buf += bsprintf(buf, "AS%u", origas);
1485
  if (o)
1486
    buf += bsprintf(buf, "%c", "ie?"[o->u.data]);
1487
  strcpy(buf, "]");
1488
}