]> git.ipfire.org Git - thirdparty/bird.git/blob - proto/bgp/packets.c
Merge branch 'master' into int-new
[thirdparty/bird.git] / proto / bgp / packets.c
1 /*
2 * BIRD -- BGP Packet Processing
3 *
4 * (c) 2000 Martin Mares <mj@ucw.cz>
5 * (c) 2008--2016 Ondrej Zajicek <santiago@crfreenet.org>
6 * (c) 2008--2016 CZ.NIC z.s.p.o.
7 *
8 * Can be freely distributed and used under the terms of the GNU GPL.
9 */
10
11 #undef LOCAL_DEBUG
12
13 #include <stdlib.h>
14
15 #include "nest/bird.h"
16 #include "nest/iface.h"
17 #include "nest/protocol.h"
18 #include "nest/route.h"
19 #include "nest/attrs.h"
20 #include "nest/mrtdump.h"
21 #include "conf/conf.h"
22 #include "lib/unaligned.h"
23 #include "lib/flowspec.h"
24 #include "lib/socket.h"
25
26 #include "nest/cli.h"
27
28 #include "bgp.h"
29
30
31 #define BGP_RR_REQUEST 0
32 #define BGP_RR_BEGIN 1
33 #define BGP_RR_END 2
34
35 #define BGP_NLRI_MAX (4 + 1 + 32)
36
37 #define BGP_MPLS_BOS 1 /* Bottom-of-stack bit */
38 #define BGP_MPLS_MAX 10 /* Max number of labels that 24*n <= 255 */
39 #define BGP_MPLS_NULL 3 /* Implicit NULL label */
40 #define BGP_MPLS_MAGIC 0x800000 /* Magic withdraw label value, RFC 3107 3 */
41
42
43 static struct tbf rl_rcv_update = TBF_DEFAULT_LOG_LIMITS;
44 static struct tbf rl_snd_update = TBF_DEFAULT_LOG_LIMITS;
45
46 /* Table for state -> RFC 6608 FSM error subcodes */
47 static byte fsm_err_subcode[BS_MAX] = {
48 [BS_OPENSENT] = 1,
49 [BS_OPENCONFIRM] = 2,
50 [BS_ESTABLISHED] = 3
51 };
52
53
54 static struct bgp_channel *
55 bgp_get_channel(struct bgp_proto *p, u32 afi)
56 {
57 uint i;
58
59 for (i = 0; i < p->channel_count; i++)
60 if (p->afi_map[i] == afi)
61 return p->channel_map[i];
62
63 return NULL;
64 }
65
66 static inline void
67 put_af3(byte *buf, u32 id)
68 {
69 put_u16(buf, id >> 16);
70 buf[2] = id & 0xff;
71 }
72
73 static inline void
74 put_af4(byte *buf, u32 id)
75 {
76 put_u16(buf, id >> 16);
77 buf[2] = 0;
78 buf[3] = id & 0xff;
79 }
80
81 static inline u32
82 get_af3(byte *buf)
83 {
84 return (get_u16(buf) << 16) | buf[2];
85 }
86
87 static inline u32
88 get_af4(byte *buf)
89 {
90 return (get_u16(buf) << 16) | buf[3];
91 }
92
93 /*
94 * MRT Dump format is not semantically specified.
95 * We will use these values in appropriate fields:
96 *
97 * Local AS, Remote AS - configured AS numbers for given BGP instance.
98 * Local IP, Remote IP - IP addresses of the TCP connection (0 if no connection)
99 *
100 * We dump two kinds of MRT messages: STATE_CHANGE (for BGP state
101 * changes) and MESSAGE (for received BGP messages).
102 *
103 * STATE_CHANGE uses always AS4 variant, but MESSAGE uses AS4 variant
104 * only when AS4 session is established and even in that case MESSAGE
105 * does not use AS4 variant for initial OPEN message. This strange
106 * behavior is here for compatibility with Quagga and Bgpdump,
107 */
108
109 static byte *
110 mrt_put_bgp4_hdr(byte *buf, struct bgp_conn *conn, int as4)
111 {
112 struct bgp_proto *p = conn->bgp;
113 uint v4 = ipa_is_ip4(p->cf->remote_ip);
114
115 if (as4)
116 {
117 put_u32(buf+0, p->remote_as);
118 put_u32(buf+4, p->public_as);
119 buf+=8;
120 }
121 else
122 {
123 put_u16(buf+0, (p->remote_as <= 0xFFFF) ? p->remote_as : AS_TRANS);
124 put_u16(buf+2, (p->public_as <= 0xFFFF) ? p->public_as : AS_TRANS);
125 buf+=4;
126 }
127
128 put_u16(buf+0, (p->neigh && p->neigh->iface) ? p->neigh->iface->index : 0);
129 put_u16(buf+2, v4 ? BGP_AFI_IPV4 : BGP_AFI_IPV6);
130 buf+=4;
131
132 if (v4)
133 {
134 buf = put_ip4(buf, conn->sk ? ipa_to_ip4(conn->sk->daddr) : IP4_NONE);
135 buf = put_ip4(buf, conn->sk ? ipa_to_ip4(conn->sk->saddr) : IP4_NONE);
136 }
137 else
138 {
139 buf = put_ip6(buf, conn->sk ? ipa_to_ip6(conn->sk->daddr) : IP6_NONE);
140 buf = put_ip6(buf, conn->sk ? ipa_to_ip6(conn->sk->saddr) : IP6_NONE);
141 }
142
143 return buf;
144 }
145
146 static void
147 mrt_dump_bgp_packet(struct bgp_conn *conn, byte *pkt, uint len)
148 {
149 byte *buf = alloca(128+len); /* 128 is enough for MRT headers */
150 byte *bp = buf + MRTDUMP_HDR_LENGTH;
151 int as4 = conn->bgp->as4_session;
152
153 bp = mrt_put_bgp4_hdr(bp, conn, as4);
154 memcpy(bp, pkt, len);
155 bp += len;
156 mrt_dump_message(&conn->bgp->p, BGP4MP, as4 ? BGP4MP_MESSAGE_AS4 : BGP4MP_MESSAGE,
157 buf, bp-buf);
158 }
159
160 static inline u16
161 convert_state(uint state)
162 {
163 /* Convert state from our BS_* values to values used in MRTDump */
164 return (state == BS_CLOSE) ? 1 : state + 1;
165 }
166
167 void
168 mrt_dump_bgp_state_change(struct bgp_conn *conn, uint old, uint new)
169 {
170 byte buf[128];
171 byte *bp = buf + MRTDUMP_HDR_LENGTH;
172
173 bp = mrt_put_bgp4_hdr(bp, conn, 1);
174 put_u16(bp+0, convert_state(old));
175 put_u16(bp+2, convert_state(new));
176 bp += 4;
177 mrt_dump_message(&conn->bgp->p, BGP4MP, BGP4MP_STATE_CHANGE_AS4, buf, bp-buf);
178 }
179
180 static byte *
181 bgp_create_notification(struct bgp_conn *conn, byte *buf)
182 {
183 struct bgp_proto *p = conn->bgp;
184
185 BGP_TRACE(D_PACKETS, "Sending NOTIFICATION(code=%d.%d)", conn->notify_code, conn->notify_subcode);
186 buf[0] = conn->notify_code;
187 buf[1] = conn->notify_subcode;
188 memcpy(buf+2, conn->notify_data, conn->notify_size);
189 return buf + 2 + conn->notify_size;
190 }
191
192
193 /* Capability negotiation as per RFC 5492 */
194
195 const struct bgp_af_caps *
196 bgp_find_af_caps(struct bgp_caps *caps, u32 afi)
197 {
198 struct bgp_af_caps *ac;
199
200 WALK_AF_CAPS(caps, ac)
201 if (ac->afi == afi)
202 return ac;
203
204 return NULL;
205 }
206
207 static struct bgp_af_caps *
208 bgp_get_af_caps(struct bgp_caps *caps, u32 afi)
209 {
210 struct bgp_af_caps *ac;
211
212 WALK_AF_CAPS(caps, ac)
213 if (ac->afi == afi)
214 return ac;
215
216 ac = &caps->af_data[caps->af_count++];
217 memset(ac, 0, sizeof(struct bgp_af_caps));
218 ac->afi = afi;
219
220 return ac;
221 }
222
223 static int
224 bgp_af_caps_cmp(const void *X, const void *Y)
225 {
226 const struct bgp_af_caps *x = X, *y = Y;
227 return (x->afi < y->afi) ? -1 : (x->afi > y->afi) ? 1 : 0;
228 }
229
230
231 static byte *
232 bgp_write_capabilities(struct bgp_conn *conn, byte *buf)
233 {
234 struct bgp_proto *p = conn->bgp;
235 struct bgp_channel *c;
236 struct bgp_caps *caps;
237 struct bgp_af_caps *ac;
238 uint any_ext_next_hop = 0;
239 uint any_add_path = 0;
240 byte *data;
241
242 /* Prepare bgp_caps structure */
243
244 int n = list_length(&p->p.channels);
245 caps = mb_allocz(p->p.pool, sizeof(struct bgp_caps) + n * sizeof(struct bgp_af_caps));
246 conn->local_caps = caps;
247
248 caps->as4_support = p->cf->enable_as4;
249 caps->ext_messages = p->cf->enable_extended_messages;
250 caps->route_refresh = p->cf->enable_refresh;
251 caps->enhanced_refresh = p->cf->enable_refresh;
252
253 if (caps->as4_support)
254 caps->as4_number = p->public_as;
255
256 if (p->cf->gr_mode)
257 {
258 caps->gr_aware = 1;
259 caps->gr_time = p->cf->gr_time;
260 caps->gr_flags = p->p.gr_recovery ? BGP_GRF_RESTART : 0;
261 }
262
263 /* Allocate and fill per-AF fields */
264 WALK_LIST(c, p->p.channels)
265 {
266 ac = &caps->af_data[caps->af_count++];
267 ac->afi = c->afi;
268 ac->ready = 1;
269
270 ac->ext_next_hop = bgp_channel_is_ipv4(c) && c->cf->ext_next_hop;
271 any_ext_next_hop |= ac->ext_next_hop;
272
273 ac->add_path = c->cf->add_path;
274 any_add_path |= ac->add_path;
275
276 if (c->cf->gr_able)
277 {
278 ac->gr_able = 1;
279
280 if (p->p.gr_recovery)
281 ac->gr_af_flags |= BGP_GRF_FORWARDING;
282 }
283 }
284
285 /* Sort capability fields by AFI/SAFI */
286 qsort(caps->af_data, caps->af_count, sizeof(struct bgp_af_caps), bgp_af_caps_cmp);
287
288
289 /* Create capability list in buffer */
290
291 /*
292 * Note that max length is ~ 20+14*af_count. With max 12 channels that is
293 * 188. Option limit is 253 and buffer size is 4096, so we cannot overflow
294 * unless we add new capabilities or more AFs.
295 */
296
297 WALK_AF_CAPS(caps, ac)
298 if (ac->ready)
299 {
300 *buf++ = 1; /* Capability 1: Multiprotocol extensions */
301 *buf++ = 4; /* Capability data length */
302 put_af4(buf, ac->afi);
303 buf += 4;
304 }
305
306 if (caps->route_refresh)
307 {
308 *buf++ = 2; /* Capability 2: Support for route refresh */
309 *buf++ = 0; /* Capability data length */
310 }
311
312 if (any_ext_next_hop)
313 {
314 *buf++ = 5; /* Capability 5: Support for extended next hop */
315 *buf++ = 0; /* Capability data length, will be fixed later */
316 data = buf;
317
318 WALK_AF_CAPS(caps, ac)
319 if (ac->ext_next_hop)
320 {
321 put_af4(buf, ac->afi);
322 put_u16(buf+4, BGP_AFI_IPV6);
323 buf += 6;
324 }
325
326 data[-1] = buf - data;
327 }
328
329 if (caps->ext_messages)
330 {
331 *buf++ = 6; /* Capability 6: Support for extended messages */
332 *buf++ = 0; /* Capability data length */
333 }
334
335 if (caps->gr_aware)
336 {
337 *buf++ = 64; /* Capability 64: Support for graceful restart */
338 *buf++ = 0; /* Capability data length, will be fixed later */
339 data = buf;
340
341 put_u16(buf, caps->gr_time);
342 buf[0] |= caps->gr_flags;
343 buf += 2;
344
345 WALK_AF_CAPS(caps, ac)
346 if (ac->gr_able)
347 {
348 put_af3(buf, ac->afi);
349 buf[3] = ac->gr_af_flags;
350 buf += 4;
351 }
352
353 data[-1] = buf - data;
354 }
355
356 if (caps->as4_support)
357 {
358 *buf++ = 65; /* Capability 65: Support for 4-octet AS number */
359 *buf++ = 4; /* Capability data length */
360 put_u32(buf, p->public_as);
361 buf += 4;
362 }
363
364 if (any_add_path)
365 {
366 *buf++ = 69; /* Capability 69: Support for ADD-PATH */
367 *buf++ = 0; /* Capability data length, will be fixed later */
368 data = buf;
369
370 WALK_AF_CAPS(caps, ac)
371 if (ac->add_path)
372 {
373 put_af3(buf, ac->afi);
374 buf[3] = ac->add_path;
375 buf += 4;
376 }
377
378 data[-1] = buf - data;
379 }
380
381 if (caps->enhanced_refresh)
382 {
383 *buf++ = 70; /* Capability 70: Support for enhanced route refresh */
384 *buf++ = 0; /* Capability data length */
385 }
386
387 return buf;
388 }
389
390 static void
391 bgp_read_capabilities(struct bgp_conn *conn, struct bgp_caps *caps, byte *pos, int len)
392 {
393 struct bgp_proto *p = conn->bgp;
394 struct bgp_af_caps *ac;
395 int i, cl;
396 u32 af;
397
398 while (len > 0)
399 {
400 if (len < 2 || len < (2 + pos[1]))
401 goto err;
402
403 /* Capability length */
404 cl = pos[1];
405
406 /* Capability type */
407 switch (pos[0])
408 {
409 case 1: /* Multiprotocol capability, RFC 4760 */
410 if (cl != 4)
411 goto err;
412
413 af = get_af4(pos+2);
414 ac = bgp_get_af_caps(caps, af);
415 ac->ready = 1;
416 break;
417
418 case 2: /* Route refresh capability, RFC 2918 */
419 if (cl != 0)
420 goto err;
421
422 caps->route_refresh = 1;
423 break;
424
425 case 5: /* Extended next hop encoding capability, RFC 5549 */
426 if (cl % 6)
427 goto err;
428
429 for (i = 0; i < cl; i += 6)
430 {
431 /* Specified only for IPv4 prefixes with IPv6 next hops */
432 if ((get_u16(pos+2+i+0) != BGP_AFI_IPV4) ||
433 (get_u16(pos+2+i+4) != BGP_AFI_IPV6))
434 continue;
435
436 af = get_af4(pos+2+i);
437 ac = bgp_get_af_caps(caps, af);
438 ac->ext_next_hop = 1;
439 }
440 break;
441
442 case 6: /* Extended message length capability, RFC draft */
443 if (cl != 0)
444 goto err;
445
446 caps->ext_messages = 1;
447 break;
448
449 case 64: /* Graceful restart capability, RFC 4724 */
450 if (cl % 4 != 2)
451 goto err;
452
453 /* Only the last instance is valid */
454 WALK_AF_CAPS(caps, ac)
455 {
456 ac->gr_able = 0;
457 ac->gr_af_flags = 0;
458 }
459
460 caps->gr_aware = 1;
461 caps->gr_flags = pos[2] & 0xf0;
462 caps->gr_time = get_u16(pos + 2) & 0x0fff;
463
464 for (i = 2; i < cl; i += 4)
465 {
466 af = get_af3(pos+2+i);
467 ac = bgp_get_af_caps(caps, af);
468 ac->gr_able = 1;
469 ac->gr_af_flags = pos[2+i+3];
470 }
471 break;
472
473 case 65: /* AS4 capability, RFC 6793 */
474 if (cl != 4)
475 goto err;
476
477 caps->as4_support = 1;
478 caps->as4_number = get_u32(pos + 2);
479 break;
480
481 case 69: /* ADD-PATH capability, RFC 7911 */
482 if (cl % 4)
483 goto err;
484
485 for (i = 0; i < cl; i += 4)
486 {
487 byte val = pos[2+i+3];
488 if (!val || (val > BGP_ADD_PATH_FULL))
489 {
490 log(L_WARN "%s: Got ADD-PATH capability with unknown value %u, ignoring",
491 p->p.name, val);
492 break;
493 }
494 }
495
496 for (i = 0; i < cl; i += 4)
497 {
498 af = get_af3(pos+2+i);
499 ac = bgp_get_af_caps(caps, af);
500 ac->add_path = pos[2+i+3];
501 }
502 break;
503
504 case 70: /* Enhanced route refresh capability, RFC 7313 */
505 if (cl != 0)
506 goto err;
507
508 caps->enhanced_refresh = 1;
509 break;
510
511 /* We can safely ignore all other capabilities */
512 }
513
514 ADVANCE(pos, len, 2 + cl);
515 }
516 return;
517
518 err:
519 bgp_error(conn, 2, 0, NULL, 0);
520 return;
521 }
522
523 static int
524 bgp_read_options(struct bgp_conn *conn, byte *pos, int len)
525 {
526 struct bgp_proto *p = conn->bgp;
527 struct bgp_caps *caps;
528 int ol;
529
530 /* Max number of announced AFIs is limited by max option length (255) */
531 caps = alloca(sizeof(struct bgp_caps) + 64 * sizeof(struct bgp_af_caps));
532 memset(caps, 0, sizeof(struct bgp_caps));
533
534 while (len > 0)
535 {
536 if ((len < 2) || (len < (2 + pos[1])))
537 { bgp_error(conn, 2, 0, NULL, 0); return -1; }
538
539 ol = pos[1];
540 if (pos[0] == 2)
541 {
542 /* BGP capabilities, RFC 5492 */
543 if (p->cf->capabilities)
544 bgp_read_capabilities(conn, caps, pos + 2, ol);
545 }
546 else
547 {
548 /* Unknown option */
549 bgp_error(conn, 2, 4, pos, ol); /* FIXME: ol or ol+2 ? */
550 return -1;
551 }
552
553 ADVANCE(pos, len, 2 + ol);
554 }
555
556 uint n = sizeof(struct bgp_caps) + caps->af_count * sizeof(struct bgp_af_caps);
557 conn->remote_caps = mb_allocz(p->p.pool, n);
558 memcpy(conn->remote_caps, caps, n);
559
560 return 0;
561 }
562
563 static byte *
564 bgp_create_open(struct bgp_conn *conn, byte *buf)
565 {
566 struct bgp_proto *p = conn->bgp;
567
568 BGP_TRACE(D_PACKETS, "Sending OPEN(ver=%d,as=%d,hold=%d,id=%08x)",
569 BGP_VERSION, p->public_as, p->cf->hold_time, p->local_id);
570
571 buf[0] = BGP_VERSION;
572 put_u16(buf+1, (p->public_as < 0xFFFF) ? p->public_as : AS_TRANS);
573 put_u16(buf+3, p->cf->hold_time);
574 put_u32(buf+5, p->local_id);
575
576 if (p->cf->capabilities)
577 {
578 /* Prepare local_caps and write capabilities to buffer */
579 byte *end = bgp_write_capabilities(conn, buf+12);
580 uint len = end - (buf+12);
581
582 buf[9] = len + 2; /* Optional parameters length */
583 buf[10] = 2; /* Option 2: Capability list */
584 buf[11] = len; /* Option data length */
585
586 return end;
587 }
588 else
589 {
590 /* Prepare empty local_caps */
591 conn->local_caps = mb_allocz(p->p.pool, sizeof(struct bgp_caps));
592
593 buf[9] = 0; /* No optional parameters */
594 return buf + 10;
595 }
596
597 return buf;
598 }
599
600 static void
601 bgp_rx_open(struct bgp_conn *conn, byte *pkt, uint len)
602 {
603 struct bgp_proto *p = conn->bgp;
604 struct bgp_conn *other;
605 u32 asn, hold, id;
606
607 /* Check state */
608 if (conn->state != BS_OPENSENT)
609 { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
610
611 /* Check message contents */
612 if (len < 29 || len != 29 + (uint) pkt[28])
613 { bgp_error(conn, 1, 2, pkt+16, 2); return; }
614
615 if (pkt[19] != BGP_VERSION)
616 { u16 val = BGP_VERSION; bgp_error(conn, 2, 1, (byte *) &val, 2); return; }
617
618 asn = get_u16(pkt+20);
619 hold = get_u16(pkt+22);
620 id = get_u32(pkt+24);
621 BGP_TRACE(D_PACKETS, "Got OPEN(as=%d,hold=%d,id=%R)", asn, hold, id);
622
623 if (bgp_read_options(conn, pkt+29, pkt[28]) < 0)
624 return;
625
626 if (hold > 0 && hold < 3)
627 { bgp_error(conn, 2, 6, pkt+22, 2); return; }
628
629 /* RFC 6286 2.2 - router ID is nonzero and AS-wide unique */
630 if (!id || (p->is_internal && id == p->local_id))
631 { bgp_error(conn, 2, 3, pkt+24, -4); return; }
632
633 struct bgp_caps *caps = conn->remote_caps;
634
635 if (caps->as4_support)
636 {
637 u32 as4 = caps->as4_number;
638
639 if ((as4 != asn) && (asn != AS_TRANS))
640 log(L_WARN "%s: Peer advertised inconsistent AS numbers", p->p.name);
641
642 if (as4 != p->remote_as)
643 { as4 = htonl(as4); bgp_error(conn, 2, 2, (byte *) &as4, 4); return; }
644 }
645 else
646 {
647 if (asn != p->remote_as)
648 { bgp_error(conn, 2, 2, pkt+20, 2); return; }
649 }
650
651 /* Check the other connection */
652 other = (conn == &p->outgoing_conn) ? &p->incoming_conn : &p->outgoing_conn;
653 switch (other->state)
654 {
655 case BS_CONNECT:
656 case BS_ACTIVE:
657 /* Stop outgoing connection attempts */
658 bgp_conn_enter_idle_state(other);
659 break;
660
661 case BS_IDLE:
662 case BS_OPENSENT:
663 case BS_CLOSE:
664 break;
665
666 case BS_OPENCONFIRM:
667 /*
668 * Description of collision detection rules in RFC 4271 is confusing and
669 * contradictory, but it is essentially:
670 *
671 * 1. Router with higher ID is dominant
672 * 2. If both have the same ID, router with higher ASN is dominant [RFC6286]
673 * 3. When both connections are in OpenConfirm state, one initiated by
674 * the dominant router is kept.
675 *
676 * The first line in the expression below evaluates whether the neighbor
677 * is dominant, the second line whether the new connection was initiated
678 * by the neighbor. If both are true (or both are false), we keep the new
679 * connection, otherwise we keep the old one.
680 */
681 if (((p->local_id < id) || ((p->local_id == id) && (p->public_as < p->remote_as)))
682 == (conn == &p->incoming_conn))
683 {
684 /* Should close the other connection */
685 BGP_TRACE(D_EVENTS, "Connection collision, giving up the other connection");
686 bgp_error(other, 6, 7, NULL, 0);
687 break;
688 }
689 /* Fall thru */
690 case BS_ESTABLISHED:
691 /* Should close this connection */
692 BGP_TRACE(D_EVENTS, "Connection collision, giving up this connection");
693 bgp_error(conn, 6, 7, NULL, 0);
694 return;
695
696 default:
697 bug("bgp_rx_open: Unknown state");
698 }
699
700 /* Update our local variables */
701 conn->hold_time = MIN(hold, p->cf->hold_time);
702 conn->keepalive_time = p->cf->keepalive_time ? : conn->hold_time / 3;
703 conn->as4_session = conn->local_caps->as4_support && caps->as4_support;
704 conn->ext_messages = conn->local_caps->ext_messages && caps->ext_messages;
705 p->remote_id = id;
706
707 DBG("BGP: Hold timer set to %d, keepalive to %d, AS to %d, ID to %x, AS4 session to %d\n",
708 conn->hold_time, conn->keepalive_time, p->remote_as, p->remote_id, conn->as4_session);
709
710 bgp_schedule_packet(conn, NULL, PKT_KEEPALIVE);
711 bgp_start_timer(conn->hold_timer, conn->hold_time);
712 bgp_conn_enter_openconfirm_state(conn);
713 }
714
715
716 /*
717 * Next hop handling
718 */
719
720 #define REPORT(msg, args...) \
721 ({ log(L_REMOTE "%s: " msg, s->proto->p.name, ## args); })
722
723 #define DISCARD(msg, args...) \
724 ({ REPORT(msg, ## args); return; })
725
726 #define WITHDRAW(msg, args...) \
727 ({ REPORT(msg, ## args); s->err_withdraw = 1; return; })
728
729 #define BAD_AFI "Unexpected AF <%u/%u> in UPDATE"
730 #define BAD_NEXT_HOP "Invalid NEXT_HOP attribute"
731 #define NO_NEXT_HOP "Missing NEXT_HOP attribute"
732 #define NO_LABEL_STACK "Missing MPLS stack"
733
734
735 static void
736 bgp_apply_next_hop(struct bgp_parse_state *s, rta *a, ip_addr gw, ip_addr ll)
737 {
738 struct bgp_proto *p = s->proto;
739 struct bgp_channel *c = s->channel;
740
741 if (c->cf->gw_mode == GW_DIRECT)
742 {
743 neighbor *nbr = NULL;
744
745 /* GW_DIRECT -> single_hop -> p->neigh != NULL */
746 if (ipa_nonzero(gw))
747 nbr = neigh_find2(&p->p, &gw, NULL, 0);
748 else if (ipa_nonzero(ll))
749 nbr = neigh_find2(&p->p, &ll, p->neigh->iface, 0);
750
751 if (!nbr || (nbr->scope == SCOPE_HOST))
752 WITHDRAW(BAD_NEXT_HOP);
753
754 a->dest = RTD_UNICAST;
755 a->nh.gw = nbr->addr;
756 a->nh.iface = nbr->iface;
757 }
758 else /* GW_RECURSIVE */
759 {
760 if (ipa_zero(gw))
761 WITHDRAW(BAD_NEXT_HOP);
762
763 rtable *tab = ipa_is_ip4(gw) ? c->igp_table_ip4 : c->igp_table_ip6;
764 s->hostentry = rt_get_hostentry(tab, gw, ll, c->c.table);
765
766 if (!s->mpls)
767 rta_apply_hostentry(a, s->hostentry, NULL);
768
769 /* With MPLS, hostentry is applied later in bgp_apply_mpls_labels() */
770 }
771 }
772
773 static void
774 bgp_apply_mpls_labels(struct bgp_parse_state *s, rta *a, u32 *labels, uint lnum)
775 {
776 if (lnum > MPLS_MAX_LABEL_STACK)
777 {
778 REPORT("Too many MPLS labels ($u)", lnum);
779
780 a->dest = RTD_UNREACHABLE;
781 a->hostentry = NULL;
782 a->nh = (struct nexthop) { };
783 return;
784 }
785
786 /* Handle implicit NULL as empty MPLS stack */
787 if ((lnum == 1) && (labels[0] == BGP_MPLS_NULL))
788 lnum = 0;
789
790 if (s->channel->cf->gw_mode == GW_DIRECT)
791 {
792 a->nh.labels = lnum;
793 memcpy(a->nh.label, labels, 4*lnum);
794 }
795 else /* GW_RECURSIVE */
796 {
797 mpls_label_stack ms;
798
799 ms.len = lnum;
800 memcpy(ms.stack, labels, 4*lnum);
801 rta_apply_hostentry(a, s->hostentry, &ms);
802 }
803 }
804
805
806 static inline int
807 bgp_use_next_hop(struct bgp_export_state *s, eattr *a)
808 {
809 struct bgp_proto *p = s->proto;
810 ip_addr *nh = (void *) a->u.ptr->data;
811
812 if (s->channel->cf->next_hop_self)
813 return 0;
814
815 if (s->channel->cf->next_hop_keep)
816 return 1;
817
818 /* Keep it when explicitly set in export filter */
819 if (a->type & EAF_FRESH)
820 return 1;
821
822 /* Keep it when exported to internal peers */
823 if (p->is_interior && ipa_nonzero(*nh))
824 return 1;
825
826 /* Keep it when forwarded between single-hop BGPs on the same iface */
827 struct iface *ifa = (s->src && s->src->neigh) ? s->src->neigh->iface : NULL;
828 return p->neigh && (p->neigh->iface == ifa);
829 }
830
831 static inline int
832 bgp_use_gateway(struct bgp_export_state *s)
833 {
834 struct bgp_proto *p = s->proto;
835 rta *ra = s->route->attrs;
836
837 if (s->channel->cf->next_hop_self)
838 return 0;
839
840 /* We need one valid global gateway */
841 if ((ra->dest != RTD_UNICAST) || ra->nh.next || ipa_zero(ra->nh.gw) || ipa_is_link_local(ra->nh.gw))
842 return 0;
843
844 /* Use it when exported to internal peers */
845 if (p->is_interior)
846 return 1;
847
848 /* Use it when forwarded to single-hop BGP peer on on the same iface */
849 return p->neigh && (p->neigh->iface == ra->nh.iface);
850 }
851
852 static void
853 bgp_update_next_hop_ip(struct bgp_export_state *s, eattr *a, ea_list **to)
854 {
855 if (!a || !bgp_use_next_hop(s, a))
856 {
857 if (bgp_use_gateway(s))
858 {
859 rta *ra = s->route->attrs;
860 ip_addr nh[1] = { ra->nh.gw };
861 bgp_set_attr_data(to, s->pool, BA_NEXT_HOP, 0, nh, 16);
862
863 if (s->mpls)
864 {
865 u32 implicit_null = BGP_MPLS_NULL;
866 u32 *labels = ra->nh.labels ? ra->nh.label : &implicit_null;
867 uint lnum = ra->nh.labels ? ra->nh.labels : 1;
868 bgp_set_attr_data(to, s->pool, BA_MPLS_LABEL_STACK, 0, labels, lnum * 4);
869 }
870 }
871 else
872 {
873 ip_addr nh[2] = { s->channel->next_hop_addr, s->channel->link_addr };
874 bgp_set_attr_data(to, s->pool, BA_NEXT_HOP, 0, nh, ipa_nonzero(nh[1]) ? 32 : 16);
875
876 /* TODO: Use local MPLS assigned label */
877 if (s->mpls)
878 bgp_unset_attr(to, s->pool, BA_MPLS_LABEL_STACK);
879 }
880 }
881
882 /* Check if next hop is valid */
883 a = bgp_find_attr(*to, BA_NEXT_HOP);
884 if (!a)
885 WITHDRAW(NO_NEXT_HOP);
886
887 ip_addr *nh = (void *) a->u.ptr->data;
888 ip_addr peer = s->proto->cf->remote_ip;
889 uint len = a->u.ptr->length;
890
891 /* Forbid zero next hop */
892 if (ipa_zero(nh[0]) && ((len != 32) || ipa_zero(nh[1])))
893 WITHDRAW(BAD_NEXT_HOP);
894
895 /* Forbid next hop equal to neighbor IP */
896 if (ipa_equal(peer, nh[0]) || ((len == 32) && ipa_equal(peer, nh[1])))
897 WITHDRAW(BAD_NEXT_HOP);
898
899 /* Forbid next hop with non-matching AF */
900 if ((ipa_is_ip4(nh[0]) != bgp_channel_is_ipv4(s->channel)) &&
901 !s->channel->ext_next_hop)
902 WITHDRAW(BAD_NEXT_HOP);
903
904 /* Just check if MPLS stack */
905 if (s->mpls && !bgp_find_attr(*to, BA_MPLS_LABEL_STACK))
906 WITHDRAW(NO_LABEL_STACK);
907 }
908
909 static uint
910 bgp_encode_next_hop_ip(struct bgp_write_state *s, eattr *a, byte *buf, uint size UNUSED)
911 {
912 /* This function is used only for MP-BGP, see bgp_encode_next_hop() for IPv4 BGP */
913 ip_addr *nh = (void *) a->u.ptr->data;
914 uint len = a->u.ptr->length;
915
916 ASSERT((len == 16) || (len == 32));
917
918 /*
919 * Both IPv4 and IPv6 next hops can be used (with ext_next_hop enabled). This
920 * is specified in RFC 5549 for IPv4 and in RFC 4798 for IPv6. The difference
921 * is that IPv4 address is directly encoded with IPv4 NLRI, but as IPv4-mapped
922 * IPv6 address with IPv6 NLRI.
923 */
924
925 if (bgp_channel_is_ipv4(s->channel) && ipa_is_ip4(nh[0]))
926 {
927 put_ip4(buf, ipa_to_ip4(nh[0]));
928 return 4;
929 }
930
931 put_ip6(buf, ipa_to_ip6(nh[0]));
932
933 if (len == 32)
934 put_ip6(buf+16, ipa_to_ip6(nh[1]));
935
936 return len;
937 }
938
939 static void
940 bgp_decode_next_hop_ip(struct bgp_parse_state *s, byte *data, uint len, rta *a)
941 {
942 struct bgp_channel *c = s->channel;
943 struct adata *ad = lp_alloc_adata(s->pool, 32);
944 ip_addr *nh = (void *) ad->data;
945
946 if (len == 4)
947 {
948 nh[0] = ipa_from_ip4(get_ip4(data));
949 nh[1] = IPA_NONE;
950 }
951 else if (len == 16)
952 {
953 nh[0] = ipa_from_ip6(get_ip6(data));
954 nh[1] = IPA_NONE;
955
956 if (ipa_is_link_local(nh[0]))
957 { nh[1] = nh[0]; nh[0] = IPA_NONE; }
958 }
959 else if (len == 32)
960 {
961 nh[0] = ipa_from_ip6(get_ip6(data));
962 nh[1] = ipa_from_ip6(get_ip6(data+16));
963
964 if (ipa_is_ip4(nh[0]) || !ip6_is_link_local(nh[1]))
965 nh[1] = IPA_NONE;
966 }
967 else
968 bgp_parse_error(s, 9);
969
970 if (ipa_zero(nh[1]))
971 ad->length = 16;
972
973 if ((bgp_channel_is_ipv4(c) != ipa_is_ip4(nh[0])) && !c->ext_next_hop)
974 WITHDRAW(BAD_NEXT_HOP);
975
976 // XXXX validate next hop
977
978 bgp_set_attr_ptr(&(a->eattrs), s->pool, BA_NEXT_HOP, 0, ad);
979 bgp_apply_next_hop(s, a, nh[0], nh[1]);
980 }
981
982 static uint
983 bgp_encode_next_hop_vpn(struct bgp_write_state *s, eattr *a, byte *buf, uint size UNUSED)
984 {
985 ip_addr *nh = (void *) a->u.ptr->data;
986 uint len = a->u.ptr->length;
987
988 ASSERT((len == 16) || (len == 32));
989
990 /*
991 * Both IPv4 and IPv6 next hops can be used (with ext_next_hop enabled). This
992 * is specified in RFC 5549 for VPNv4 and in RFC 4659 for VPNv6. The difference
993 * is that IPv4 address is directly encoded with VPNv4 NLRI, but as IPv4-mapped
994 * IPv6 address with VPNv6 NLRI.
995 */
996
997 if (bgp_channel_is_ipv4(s->channel) && ipa_is_ip4(nh[0]))
998 {
999 put_u64(buf, 0); /* VPN RD is 0 */
1000 put_ip4(buf+8, ipa_to_ip4(nh[0]));
1001 return 12;
1002 }
1003
1004 put_u64(buf, 0); /* VPN RD is 0 */
1005 put_ip6(buf+8, ipa_to_ip6(nh[0]));
1006
1007 if (len == 16)
1008 return 24;
1009
1010 put_u64(buf+24, 0); /* VPN RD is 0 */
1011 put_ip6(buf+32, ipa_to_ip6(nh[1]));
1012
1013 return 48;
1014 }
1015
1016 static void
1017 bgp_decode_next_hop_vpn(struct bgp_parse_state *s, byte *data, uint len, rta *a)
1018 {
1019 struct bgp_channel *c = s->channel;
1020 struct adata *ad = lp_alloc_adata(s->pool, 32);
1021 ip_addr *nh = (void *) ad->data;
1022
1023 if (len == 12)
1024 {
1025 nh[0] = ipa_from_ip4(get_ip4(data+8));
1026 nh[1] = IPA_NONE;
1027 }
1028 else if (len == 24)
1029 {
1030 nh[0] = ipa_from_ip6(get_ip6(data+8));
1031 nh[1] = IPA_NONE;
1032
1033 if (ipa_is_link_local(nh[0]))
1034 { nh[1] = nh[0]; nh[0] = IPA_NONE; }
1035 }
1036 else if (len == 48)
1037 {
1038 nh[0] = ipa_from_ip6(get_ip6(data+8));
1039 nh[1] = ipa_from_ip6(get_ip6(data+32));
1040
1041 if (ipa_is_ip4(nh[0]) || !ip6_is_link_local(nh[1]))
1042 nh[1] = IPA_NONE;
1043 }
1044 else
1045 bgp_parse_error(s, 9);
1046
1047 if (ipa_zero(nh[1]))
1048 ad->length = 16;
1049
1050 /* XXXX which error */
1051 if ((get_u64(data) != 0) || ((len == 48) && (get_u64(data+24) != 0)))
1052 bgp_parse_error(s, 9);
1053
1054 if ((bgp_channel_is_ipv4(c) != ipa_is_ip4(nh[0])) && !c->ext_next_hop)
1055 WITHDRAW(BAD_NEXT_HOP);
1056
1057 // XXXX validate next hop
1058
1059 bgp_set_attr_ptr(&(a->eattrs), s->pool, BA_NEXT_HOP, 0, ad);
1060 bgp_apply_next_hop(s, a, nh[0], nh[1]);
1061 }
1062
1063
1064
1065 static uint
1066 bgp_encode_next_hop_none(struct bgp_write_state *s UNUSED, eattr *a UNUSED, byte *buf UNUSED, uint size UNUSED)
1067 {
1068 return 0;
1069 }
1070
1071 static void
1072 bgp_decode_next_hop_none(struct bgp_parse_state *s UNUSED, byte *data UNUSED, uint len UNUSED, rta *a UNUSED)
1073 {
1074 /*
1075 * Although we expect no next hop and RFC 7606 7.11 states that attribute
1076 * MP_REACH_NLRI with unexpected next hop length is considered malformed,
1077 * FlowSpec RFC 5575 4 states that next hop shall be ignored on receipt.
1078 */
1079
1080 return;
1081 }
1082
1083 static void
1084 bgp_update_next_hop_none(struct bgp_export_state *s, eattr *a, ea_list **to)
1085 {
1086 /* NEXT_HOP shall not pass */
1087 if (a)
1088 bgp_unset_attr(to, s->pool, BA_NEXT_HOP);
1089 }
1090
1091
1092 /*
1093 * UPDATE
1094 */
1095
1096 static void
1097 bgp_rte_update(struct bgp_parse_state *s, net_addr *n, u32 path_id, rta *a0)
1098 {
1099 if (path_id != s->last_id)
1100 {
1101 s->last_src = rt_get_source(&s->proto->p, path_id);
1102 s->last_id = path_id;
1103
1104 rta_free(s->cached_rta);
1105 s->cached_rta = NULL;
1106 }
1107
1108 if (!a0)
1109 {
1110 /* Route withdraw */
1111 rte_update2(&s->channel->c, n, NULL, s->last_src);
1112 return;
1113 }
1114
1115 /* Prepare cached route attributes */
1116 if (s->cached_rta == NULL)
1117 {
1118 a0->src = s->last_src;
1119
1120 /* Workaround for rta_lookup() breaking eattrs */
1121 ea_list *ea = a0->eattrs;
1122 s->cached_rta = rta_lookup(a0);
1123 a0->eattrs = ea;
1124 }
1125
1126 rta *a = rta_clone(s->cached_rta);
1127 rte *e = rte_get_temp(a);
1128
1129 e->pflags = 0;
1130 e->u.bgp.suppressed = 0;
1131 rte_update2(&s->channel->c, n, e, s->last_src);
1132 }
1133
1134 static void
1135 bgp_encode_mpls_labels(struct bgp_write_state *s UNUSED, adata *mpls, byte **pos, uint *size, byte *pxlen)
1136 {
1137 u32 dummy = 0;
1138 u32 *labels = mpls ? (u32 *) mpls->data : &dummy;
1139 uint lnum = mpls ? (mpls->length / 4) : 1;
1140
1141 for (uint i = 0; i < lnum; i++)
1142 {
1143 put_u24(*pos, labels[i] << 4);
1144 ADVANCE(*pos, *size, 3);
1145 }
1146
1147 /* Add bottom-of-stack flag */
1148 (*pos)[-1] |= BGP_MPLS_BOS;
1149
1150 *pxlen += 24 * lnum;
1151 }
1152
1153 static void
1154 bgp_decode_mpls_labels(struct bgp_parse_state *s, byte **pos, uint *len, uint *pxlen, rta *a)
1155 {
1156 u32 labels[BGP_MPLS_MAX], label;
1157 uint lnum = 0;
1158
1159 do {
1160 if (*pxlen < 24)
1161 bgp_parse_error(s, 1);
1162
1163 label = get_u24(*pos);
1164 labels[lnum++] = label >> 4;
1165 ADVANCE(*pos, *len, 3);
1166 *pxlen -= 24;
1167
1168 /* Withdraw: Magic label stack value 0x800000 according to RFC 3107, section 3, last paragraph */
1169 if (!a && !s->err_withdraw && (lnum == 1) && (label == BGP_MPLS_MAGIC))
1170 break;
1171 }
1172 while (!(label & BGP_MPLS_BOS));
1173
1174 if (!a)
1175 return;
1176
1177 /* Attach MPLS attribute unless we already have one */
1178 if (!s->mpls_labels)
1179 {
1180 s->mpls_labels = lp_alloc_adata(s->pool, 4*BGP_MPLS_MAX);
1181 bgp_set_attr_ptr(&(a->eattrs), s->pool, BA_MPLS_LABEL_STACK, 0, s->mpls_labels);
1182 }
1183
1184 /* Overwrite data in the attribute */
1185 s->mpls_labels->length = 4*lnum;
1186 memcpy(s->mpls_labels->data, labels, 4*lnum);
1187
1188 /* Update next hop entry in rta */
1189 bgp_apply_mpls_labels(s, a, labels, lnum);
1190
1191 /* Attributes were changed, invalidate cached entry */
1192 rta_free(s->cached_rta);
1193 s->cached_rta = NULL;
1194
1195 return;
1196 }
1197
1198 static uint
1199 bgp_encode_nlri_ip4(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
1200 {
1201 byte *pos = buf;
1202
1203 while (!EMPTY_LIST(buck->prefixes) && (size >= BGP_NLRI_MAX))
1204 {
1205 struct bgp_prefix *px = HEAD(buck->prefixes);
1206 struct net_addr_ip4 *net = (void *) px->net;
1207
1208 /* Encode path ID */
1209 if (s->add_path)
1210 {
1211 put_u32(pos, px->path_id);
1212 ADVANCE(pos, size, 4);
1213 }
1214
1215 /* Encode prefix length */
1216 *pos = net->pxlen;
1217 ADVANCE(pos, size, 1);
1218
1219 /* Encode MPLS labels */
1220 if (s->mpls)
1221 bgp_encode_mpls_labels(s, s->mpls_labels, &pos, &size, pos - 1);
1222
1223 /* Encode prefix body */
1224 ip4_addr a = ip4_hton(net->prefix);
1225 uint b = (net->pxlen + 7) / 8;
1226 memcpy(pos, &a, b);
1227 ADVANCE(pos, size, b);
1228
1229 bgp_free_prefix(s->channel, px);
1230 }
1231
1232 return pos - buf;
1233 }
1234
1235 static void
1236 bgp_decode_nlri_ip4(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
1237 {
1238 while (len)
1239 {
1240 net_addr_ip4 net;
1241 u32 path_id = 0;
1242
1243 /* Decode path ID */
1244 if (s->add_path)
1245 {
1246 if (len < 5)
1247 bgp_parse_error(s, 1);
1248
1249 path_id = get_u32(pos);
1250 ADVANCE(pos, len, 4);
1251 }
1252
1253 /* Decode prefix length */
1254 uint l = *pos;
1255 ADVANCE(pos, len, 1);
1256
1257 if (len < ((l + 7) / 8))
1258 bgp_parse_error(s, 1);
1259
1260 /* Decode MPLS labels */
1261 if (s->mpls)
1262 bgp_decode_mpls_labels(s, &pos, &len, &l, a);
1263
1264 if (l > IP4_MAX_PREFIX_LENGTH)
1265 bgp_parse_error(s, 10);
1266
1267 /* Decode prefix body */
1268 ip4_addr addr = IP4_NONE;
1269 uint b = (l + 7) / 8;
1270 memcpy(&addr, pos, b);
1271 ADVANCE(pos, len, b);
1272
1273 net = NET_ADDR_IP4(ip4_ntoh(addr), l);
1274 net_normalize_ip4(&net);
1275
1276 // XXXX validate prefix
1277
1278 bgp_rte_update(s, (net_addr *) &net, path_id, a);
1279 }
1280 }
1281
1282
1283 static uint
1284 bgp_encode_nlri_ip6(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
1285 {
1286 byte *pos = buf;
1287
1288 while (!EMPTY_LIST(buck->prefixes) && (size >= BGP_NLRI_MAX))
1289 {
1290 struct bgp_prefix *px = HEAD(buck->prefixes);
1291 struct net_addr_ip6 *net = (void *) px->net;
1292
1293 /* Encode path ID */
1294 if (s->add_path)
1295 {
1296 put_u32(pos, px->path_id);
1297 ADVANCE(pos, size, 4);
1298 }
1299
1300 /* Encode prefix length */
1301 *pos = net->pxlen;
1302 ADVANCE(pos, size, 1);
1303
1304 /* Encode MPLS labels */
1305 if (s->mpls)
1306 bgp_encode_mpls_labels(s, s->mpls_labels, &pos, &size, pos - 1);
1307
1308 /* Encode prefix body */
1309 ip6_addr a = ip6_hton(net->prefix);
1310 uint b = (net->pxlen + 7) / 8;
1311 memcpy(pos, &a, b);
1312 ADVANCE(pos, size, b);
1313
1314 bgp_free_prefix(s->channel, px);
1315 }
1316
1317 return pos - buf;
1318 }
1319
1320 static void
1321 bgp_decode_nlri_ip6(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
1322 {
1323 while (len)
1324 {
1325 net_addr_ip6 net;
1326 u32 path_id = 0;
1327
1328 /* Decode path ID */
1329 if (s->add_path)
1330 {
1331 if (len < 5)
1332 bgp_parse_error(s, 1);
1333
1334 path_id = get_u32(pos);
1335 ADVANCE(pos, len, 4);
1336 }
1337
1338 /* Decode prefix length */
1339 uint l = *pos;
1340 ADVANCE(pos, len, 1);
1341
1342 if (len < ((l + 7) / 8))
1343 bgp_parse_error(s, 1);
1344
1345 /* Decode MPLS labels */
1346 if (s->mpls)
1347 bgp_decode_mpls_labels(s, &pos, &len, &l, a);
1348
1349 if (l > IP6_MAX_PREFIX_LENGTH)
1350 bgp_parse_error(s, 10);
1351
1352 /* Decode prefix body */
1353 ip6_addr addr = IP6_NONE;
1354 uint b = (l + 7) / 8;
1355 memcpy(&addr, pos, b);
1356 ADVANCE(pos, len, b);
1357
1358 net = NET_ADDR_IP6(ip6_ntoh(addr), l);
1359 net_normalize_ip6(&net);
1360
1361 // XXXX validate prefix
1362
1363 bgp_rte_update(s, (net_addr *) &net, path_id, a);
1364 }
1365 }
1366
1367 static uint
1368 bgp_encode_nlri_vpn4(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
1369 {
1370 byte *pos = buf;
1371
1372 while (!EMPTY_LIST(buck->prefixes) && (size >= BGP_NLRI_MAX))
1373 {
1374 struct bgp_prefix *px = HEAD(buck->prefixes);
1375 struct net_addr_vpn4 *net = (void *) px->net;
1376
1377 /* Encode path ID */
1378 if (s->add_path)
1379 {
1380 put_u32(pos, px->path_id);
1381 ADVANCE(pos, size, 4);
1382 }
1383
1384 /* Encode prefix length */
1385 *pos = 64 + net->pxlen;
1386 ADVANCE(pos, size, 1);
1387
1388 /* Encode MPLS labels */
1389 if (s->mpls)
1390 bgp_encode_mpls_labels(s, s->mpls_labels, &pos, &size, pos - 1);
1391
1392 /* Encode route distinguisher */
1393 put_u64(pos, net->rd);
1394 ADVANCE(pos, size, 8);
1395
1396 /* Encode prefix body */
1397 ip4_addr a = ip4_hton(net->prefix);
1398 uint b = (net->pxlen + 7) / 8;
1399 memcpy(pos, &a, b);
1400 ADVANCE(pos, size, b);
1401
1402 bgp_free_prefix(s->channel, px);
1403 }
1404
1405 return pos - buf;
1406 }
1407
1408 static void
1409 bgp_decode_nlri_vpn4(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
1410 {
1411 while (len)
1412 {
1413 net_addr_vpn4 net;
1414 u32 path_id = 0;
1415
1416 /* Decode path ID */
1417 if (s->add_path)
1418 {
1419 if (len < 5)
1420 bgp_parse_error(s, 1);
1421
1422 path_id = get_u32(pos);
1423 ADVANCE(pos, len, 4);
1424 }
1425
1426 /* Decode prefix length */
1427 uint l = *pos;
1428 ADVANCE(pos, len, 1);
1429
1430 if (len < ((l + 7) / 8))
1431 bgp_parse_error(s, 1);
1432
1433 /* Decode MPLS labels */
1434 if (s->mpls)
1435 bgp_decode_mpls_labels(s, &pos, &len, &l, a);
1436
1437 /* Decode route distinguisher */
1438 if (l < 64)
1439 bgp_parse_error(s, 1);
1440
1441 u64 rd = get_u64(pos);
1442 ADVANCE(pos, len, 8);
1443 l -= 64;
1444
1445 if (l > IP4_MAX_PREFIX_LENGTH)
1446 bgp_parse_error(s, 10);
1447
1448 /* Decode prefix body */
1449 ip4_addr addr = IP4_NONE;
1450 uint b = (l + 7) / 8;
1451 memcpy(&addr, pos, b);
1452 ADVANCE(pos, len, b);
1453
1454 net = NET_ADDR_VPN4(ip4_ntoh(addr), l, rd);
1455 net_normalize_vpn4(&net);
1456
1457 // XXXX validate prefix
1458
1459 bgp_rte_update(s, (net_addr *) &net, path_id, a);
1460 }
1461 }
1462
1463
1464 static uint
1465 bgp_encode_nlri_vpn6(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
1466 {
1467 byte *pos = buf;
1468
1469 while (!EMPTY_LIST(buck->prefixes) && (size >= BGP_NLRI_MAX))
1470 {
1471 struct bgp_prefix *px = HEAD(buck->prefixes);
1472 struct net_addr_vpn6 *net = (void *) px->net;
1473
1474 /* Encode path ID */
1475 if (s->add_path)
1476 {
1477 put_u32(pos, px->path_id);
1478 ADVANCE(pos, size, 4);
1479 }
1480
1481 /* Encode prefix length */
1482 *pos = 64 + net->pxlen;
1483 ADVANCE(pos, size, 1);
1484
1485 /* Encode MPLS labels */
1486 bgp_encode_mpls_labels(s, s->mpls_labels, &pos, &size, pos - 1);
1487
1488 /* Encode route distinguisher */
1489 put_u64(pos, net->rd);
1490 ADVANCE(pos, size, 8);
1491
1492 /* Encode prefix body */
1493 ip6_addr a = ip6_hton(net->prefix);
1494 uint b = (net->pxlen + 7) / 8;
1495 memcpy(pos, &a, b);
1496 ADVANCE(pos, size, b);
1497
1498 bgp_free_prefix(s->channel, px);
1499 }
1500
1501 return pos - buf;
1502 }
1503
1504 static void
1505 bgp_decode_nlri_vpn6(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
1506 {
1507 while (len)
1508 {
1509 net_addr_vpn6 net;
1510 u32 path_id = 0;
1511
1512 /* Decode path ID */
1513 if (s->add_path)
1514 {
1515 if (len < 5)
1516 bgp_parse_error(s, 1);
1517
1518 path_id = get_u32(pos);
1519 ADVANCE(pos, len, 4);
1520 }
1521
1522 /* Decode prefix length */
1523 uint l = *pos;
1524 ADVANCE(pos, len, 1);
1525
1526 if (len < ((l + 7) / 8))
1527 bgp_parse_error(s, 1);
1528
1529 /* Decode MPLS labels */
1530 if (s->mpls)
1531 bgp_decode_mpls_labels(s, &pos, &len, &l, a);
1532
1533 /* Decode route distinguisher */
1534 if (l < 64)
1535 bgp_parse_error(s, 1);
1536
1537 u64 rd = get_u64(pos);
1538 ADVANCE(pos, len, 8);
1539 l -= 64;
1540
1541 if (l > IP6_MAX_PREFIX_LENGTH)
1542 bgp_parse_error(s, 10);
1543
1544 /* Decode prefix body */
1545 ip6_addr addr = IP6_NONE;
1546 uint b = (l + 7) / 8;
1547 memcpy(&addr, pos, b);
1548 ADVANCE(pos, len, b);
1549
1550 net = NET_ADDR_VPN6(ip6_ntoh(addr), l, rd);
1551 net_normalize_vpn6(&net);
1552
1553 // XXXX validate prefix
1554
1555 bgp_rte_update(s, (net_addr *) &net, path_id, a);
1556 }
1557 }
1558
1559
1560 static uint
1561 bgp_encode_nlri_flow4(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
1562 {
1563 byte *pos = buf;
1564
1565 while (!EMPTY_LIST(buck->prefixes) && (size >= 4))
1566 {
1567 struct bgp_prefix *px = HEAD(buck->prefixes);
1568 struct net_addr_flow4 *net = (void *) px->net;
1569 uint flen = net->length - sizeof(net_addr_flow4);
1570
1571 /* Encode path ID */
1572 if (s->add_path)
1573 {
1574 put_u32(pos, px->path_id);
1575 ADVANCE(pos, size, 4);
1576 }
1577
1578 if (flen > size)
1579 break;
1580
1581 /* Copy whole flow data including length */
1582 memcpy(pos, net->data, flen);
1583 ADVANCE(pos, size, flen);
1584
1585 bgp_free_prefix(s->channel, px);
1586 }
1587
1588 return pos - buf;
1589 }
1590
1591 static void
1592 bgp_decode_nlri_flow4(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
1593 {
1594 while (len)
1595 {
1596 u32 path_id = 0;
1597
1598 /* Decode path ID */
1599 if (s->add_path)
1600 {
1601 if (len < 4)
1602 bgp_parse_error(s, 1);
1603
1604 path_id = get_u32(pos);
1605 ADVANCE(pos, len, 4);
1606 }
1607
1608 if (len < 2)
1609 bgp_parse_error(s, 1);
1610
1611 /* Decode flow length */
1612 uint hlen = flow_hdr_length(pos);
1613 uint dlen = flow_read_length(pos);
1614 uint flen = hlen + dlen;
1615 byte *data = pos + hlen;
1616
1617 if (len < flen)
1618 bgp_parse_error(s, 1);
1619
1620 /* Validate flow data */
1621 enum flow_validated_state r = flow4_validate(data, dlen);
1622 if (r != FLOW_ST_VALID)
1623 {
1624 log(L_REMOTE "%s: Invalid flow route: %s", s->proto->p.name, flow_validated_state_str(r));
1625 bgp_parse_error(s, 1);
1626 }
1627
1628 if (data[0] != FLOW_TYPE_DST_PREFIX)
1629 {
1630 log(L_REMOTE "%s: No dst prefix at first pos", s->proto->p.name);
1631 bgp_parse_error(s, 1);
1632 }
1633
1634 /* Decode dst prefix */
1635 ip4_addr px = IP4_NONE;
1636 uint pxlen = data[1];
1637
1638 // FIXME: Use some generic function
1639 memcpy(&px, data, BYTES(pxlen));
1640 px = ip4_and(px, ip4_mkmask(pxlen));
1641
1642 /* Prepare the flow */
1643 net_addr *n = alloca(sizeof(struct net_addr_flow4) + flen);
1644 net_fill_flow4(n, px, pxlen, pos, flen);
1645 ADVANCE(pos, len, flen);
1646
1647 bgp_rte_update(s, n, path_id, a);
1648 }
1649 }
1650
1651
1652 static uint
1653 bgp_encode_nlri_flow6(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
1654 {
1655 byte *pos = buf;
1656
1657 while (!EMPTY_LIST(buck->prefixes) && (size >= 4))
1658 {
1659 struct bgp_prefix *px = HEAD(buck->prefixes);
1660 struct net_addr_flow6 *net = (void *) px->net;
1661 uint flen = net->length - sizeof(net_addr_flow6);
1662
1663 /* Encode path ID */
1664 if (s->add_path)
1665 {
1666 put_u32(pos, px->path_id);
1667 ADVANCE(pos, size, 4);
1668 }
1669
1670 if (flen > size)
1671 break;
1672
1673 /* Copy whole flow data including length */
1674 memcpy(pos, net->data, flen);
1675 ADVANCE(pos, size, flen);
1676
1677 bgp_free_prefix(s->channel, px);
1678 }
1679
1680 return pos - buf;
1681 }
1682
1683 static void
1684 bgp_decode_nlri_flow6(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
1685 {
1686 while (len)
1687 {
1688 u32 path_id = 0;
1689
1690 /* Decode path ID */
1691 if (s->add_path)
1692 {
1693 if (len < 4)
1694 bgp_parse_error(s, 1);
1695
1696 path_id = get_u32(pos);
1697 ADVANCE(pos, len, 4);
1698 }
1699
1700 if (len < 2)
1701 bgp_parse_error(s, 1);
1702
1703 /* Decode flow length */
1704 uint hlen = flow_hdr_length(pos);
1705 uint dlen = flow_read_length(pos);
1706 uint flen = hlen + dlen;
1707 byte *data = pos + hlen;
1708
1709 if (len < flen)
1710 bgp_parse_error(s, 1);
1711
1712 /* Validate flow data */
1713 enum flow_validated_state r = flow6_validate(data, dlen);
1714 if (r != FLOW_ST_VALID)
1715 {
1716 log(L_REMOTE "%s: Invalid flow route: %s", s->proto->p.name, flow_validated_state_str(r));
1717 bgp_parse_error(s, 1);
1718 }
1719
1720 if (data[0] != FLOW_TYPE_DST_PREFIX)
1721 {
1722 log(L_REMOTE "%s: No dst prefix at first pos", s->proto->p.name);
1723 bgp_parse_error(s, 1);
1724 }
1725
1726 /* Decode dst prefix */
1727 ip6_addr px = IP6_NONE;
1728 uint pxlen = data[1];
1729
1730 // FIXME: Use some generic function
1731 memcpy(&px, data, BYTES(pxlen));
1732 px = ip6_and(px, ip6_mkmask(pxlen));
1733
1734 /* Prepare the flow */
1735 net_addr *n = alloca(sizeof(struct net_addr_flow6) + flen);
1736 net_fill_flow6(n, px, pxlen, pos, flen);
1737 ADVANCE(pos, len, flen);
1738
1739 bgp_rte_update(s, n, path_id, a);
1740 }
1741 }
1742
1743
1744 static const struct bgp_af_desc bgp_af_table[] = {
1745 {
1746 .afi = BGP_AF_IPV4,
1747 .net = NET_IP4,
1748 .name = "ipv4",
1749 .encode_nlri = bgp_encode_nlri_ip4,
1750 .decode_nlri = bgp_decode_nlri_ip4,
1751 .encode_next_hop = bgp_encode_next_hop_ip,
1752 .decode_next_hop = bgp_decode_next_hop_ip,
1753 .update_next_hop = bgp_update_next_hop_ip,
1754 },
1755 {
1756 .afi = BGP_AF_IPV4_MC,
1757 .net = NET_IP4,
1758 .name = "ipv4-mc",
1759 .encode_nlri = bgp_encode_nlri_ip4,
1760 .decode_nlri = bgp_decode_nlri_ip4,
1761 .encode_next_hop = bgp_encode_next_hop_ip,
1762 .decode_next_hop = bgp_decode_next_hop_ip,
1763 .update_next_hop = bgp_update_next_hop_ip,
1764 },
1765 {
1766 .afi = BGP_AF_IPV4_MPLS,
1767 .net = NET_IP4,
1768 .mpls = 1,
1769 .name = "ipv4-mpls",
1770 .encode_nlri = bgp_encode_nlri_ip4,
1771 .decode_nlri = bgp_decode_nlri_ip4,
1772 .encode_next_hop = bgp_encode_next_hop_ip,
1773 .decode_next_hop = bgp_decode_next_hop_ip,
1774 .update_next_hop = bgp_update_next_hop_ip,
1775 },
1776 {
1777 .afi = BGP_AF_IPV6,
1778 .net = NET_IP6,
1779 .name = "ipv6",
1780 .encode_nlri = bgp_encode_nlri_ip6,
1781 .decode_nlri = bgp_decode_nlri_ip6,
1782 .encode_next_hop = bgp_encode_next_hop_ip,
1783 .decode_next_hop = bgp_decode_next_hop_ip,
1784 .update_next_hop = bgp_update_next_hop_ip,
1785 },
1786 {
1787 .afi = BGP_AF_IPV6_MC,
1788 .net = NET_IP6,
1789 .name = "ipv6-mc",
1790 .encode_nlri = bgp_encode_nlri_ip6,
1791 .decode_nlri = bgp_decode_nlri_ip6,
1792 .encode_next_hop = bgp_encode_next_hop_ip,
1793 .decode_next_hop = bgp_decode_next_hop_ip,
1794 .update_next_hop = bgp_update_next_hop_ip,
1795 },
1796 {
1797 .afi = BGP_AF_IPV6_MPLS,
1798 .net = NET_IP6,
1799 .mpls = 1,
1800 .name = "ipv6-mpls",
1801 .encode_nlri = bgp_encode_nlri_ip6,
1802 .decode_nlri = bgp_decode_nlri_ip6,
1803 .encode_next_hop = bgp_encode_next_hop_ip,
1804 .decode_next_hop = bgp_decode_next_hop_ip,
1805 .update_next_hop = bgp_update_next_hop_ip,
1806 },
1807 {
1808 .afi = BGP_AF_VPN4_MPLS,
1809 .net = NET_VPN4,
1810 .mpls = 1,
1811 .name = "vpn4-mpls",
1812 .encode_nlri = bgp_encode_nlri_vpn4,
1813 .decode_nlri = bgp_decode_nlri_vpn4,
1814 .encode_next_hop = bgp_encode_next_hop_vpn,
1815 .decode_next_hop = bgp_decode_next_hop_vpn,
1816 .update_next_hop = bgp_update_next_hop_ip,
1817 },
1818 {
1819 .afi = BGP_AF_VPN6_MPLS,
1820 .net = NET_VPN6,
1821 .mpls = 1,
1822 .name = "vpn6-mpls",
1823 .encode_nlri = bgp_encode_nlri_vpn6,
1824 .decode_nlri = bgp_decode_nlri_vpn6,
1825 .encode_next_hop = bgp_encode_next_hop_vpn,
1826 .decode_next_hop = bgp_decode_next_hop_vpn,
1827 .update_next_hop = bgp_update_next_hop_ip,
1828 },
1829 {
1830 .afi = BGP_AF_VPN4_MC,
1831 .net = NET_VPN4,
1832 .name = "vpn4-mc",
1833 .encode_nlri = bgp_encode_nlri_vpn4,
1834 .decode_nlri = bgp_decode_nlri_vpn4,
1835 .encode_next_hop = bgp_encode_next_hop_vpn,
1836 .decode_next_hop = bgp_decode_next_hop_vpn,
1837 .update_next_hop = bgp_update_next_hop_ip,
1838 },
1839 {
1840 .afi = BGP_AF_VPN6_MC,
1841 .net = NET_VPN6,
1842 .name = "vpn6-mc",
1843 .encode_nlri = bgp_encode_nlri_vpn6,
1844 .decode_nlri = bgp_decode_nlri_vpn6,
1845 .encode_next_hop = bgp_encode_next_hop_vpn,
1846 .decode_next_hop = bgp_decode_next_hop_vpn,
1847 .update_next_hop = bgp_update_next_hop_ip,
1848 },
1849 {
1850 .afi = BGP_AF_FLOW4,
1851 .net = NET_FLOW4,
1852 .no_igp = 1,
1853 .name = "flow4",
1854 .encode_nlri = bgp_encode_nlri_flow4,
1855 .decode_nlri = bgp_decode_nlri_flow4,
1856 .encode_next_hop = bgp_encode_next_hop_none,
1857 .decode_next_hop = bgp_decode_next_hop_none,
1858 .update_next_hop = bgp_update_next_hop_none,
1859 },
1860 {
1861 .afi = BGP_AF_FLOW6,
1862 .net = NET_FLOW6,
1863 .no_igp = 1,
1864 .name = "flow6",
1865 .encode_nlri = bgp_encode_nlri_flow6,
1866 .decode_nlri = bgp_decode_nlri_flow6,
1867 .encode_next_hop = bgp_encode_next_hop_none,
1868 .decode_next_hop = bgp_decode_next_hop_none,
1869 .update_next_hop = bgp_update_next_hop_none,
1870 },
1871 };
1872
1873 const struct bgp_af_desc *
1874 bgp_get_af_desc(u32 afi)
1875 {
1876 uint i;
1877 for (i = 0; i < ARRAY_SIZE(bgp_af_table); i++)
1878 if (bgp_af_table[i].afi == afi)
1879 return &bgp_af_table[i];
1880
1881 return NULL;
1882 }
1883
1884 static inline uint
1885 bgp_encode_nlri(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
1886 {
1887 return s->channel->desc->encode_nlri(s, buck, buf, end - buf);
1888 }
1889
1890 static inline uint
1891 bgp_encode_next_hop(struct bgp_write_state *s, eattr *nh, byte *buf)
1892 {
1893 return s->channel->desc->encode_next_hop(s, nh, buf, 255);
1894 }
1895
1896 void
1897 bgp_update_next_hop(struct bgp_export_state *s, eattr *a, ea_list **to)
1898 {
1899 s->channel->desc->update_next_hop(s, a, to);
1900 }
1901
1902 #define MAX_ATTRS_LENGTH (end-buf+BGP_HEADER_LENGTH - 1024)
1903
1904 static byte *
1905 bgp_create_ip_reach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
1906 {
1907 /*
1908 * 2 B Withdrawn Routes Length (zero)
1909 * --- IPv4 Withdrawn Routes NLRI (unused)
1910 * 2 B Total Path Attribute Length
1911 * var Path Attributes
1912 * var IPv4 Network Layer Reachability Information
1913 */
1914
1915 int lr, la;
1916
1917 la = bgp_encode_attrs(s, buck->eattrs, buf+4, buf + MAX_ATTRS_LENGTH);
1918 if (la < 0)
1919 {
1920 /* Attribute list too long */
1921 bgp_withdraw_bucket(s->channel, buck);
1922 return NULL;
1923 }
1924
1925 put_u16(buf+0, 0);
1926 put_u16(buf+2, la);
1927
1928 lr = bgp_encode_nlri(s, buck, buf+4+la, end);
1929
1930 return buf+4+la+lr;
1931 }
1932
1933 static byte *
1934 bgp_create_mp_reach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
1935 {
1936 /*
1937 * 2 B IPv4 Withdrawn Routes Length (zero)
1938 * --- IPv4 Withdrawn Routes NLRI (unused)
1939 * 2 B Total Path Attribute Length
1940 * 1 B MP_REACH_NLRI hdr - Attribute Flags
1941 * 1 B MP_REACH_NLRI hdr - Attribute Type Code
1942 * 2 B MP_REACH_NLRI hdr - Length of Attribute Data
1943 * 2 B MP_REACH_NLRI data - Address Family Identifier
1944 * 1 B MP_REACH_NLRI data - Subsequent Address Family Identifier
1945 * 1 B MP_REACH_NLRI data - Length of Next Hop Network Address
1946 * var MP_REACH_NLRI data - Network Address of Next Hop
1947 * 1 B MP_REACH_NLRI data - Reserved (zero)
1948 * var MP_REACH_NLRI data - Network Layer Reachability Information
1949 * var Rest of Path Attributes
1950 * --- IPv4 Network Layer Reachability Information (unused)
1951 */
1952
1953 int lh, lr, la; /* Lengths of next hop, NLRI and attributes */
1954
1955 /* Begin of MP_REACH_NLRI atribute */
1956 buf[4] = BAF_OPTIONAL | BAF_EXT_LEN;
1957 buf[5] = BA_MP_REACH_NLRI;
1958 put_u16(buf+6, 0); /* Will be fixed later */
1959 put_af3(buf+8, s->channel->afi);
1960 byte *pos = buf+11;
1961
1962 /* Encode attributes to temporary buffer */
1963 byte *abuf = alloca(MAX_ATTRS_LENGTH);
1964 la = bgp_encode_attrs(s, buck->eattrs, abuf, abuf + MAX_ATTRS_LENGTH);
1965 if (la < 0)
1966 {
1967 /* Attribute list too long */
1968 bgp_withdraw_bucket(s->channel, buck);
1969 return NULL;
1970 }
1971
1972 /* Encode the next hop */
1973 lh = bgp_encode_next_hop(s, s->mp_next_hop, pos+1);
1974 *pos = lh;
1975 pos += 1+lh;
1976
1977 /* Reserved field */
1978 *pos++ = 0;
1979
1980 /* Encode the NLRI */
1981 lr = bgp_encode_nlri(s, buck, pos, end - la);
1982 pos += lr;
1983
1984 /* End of MP_REACH_NLRI atribute, update data length */
1985 put_u16(buf+6, pos-buf-8);
1986
1987 /* Copy remaining attributes */
1988 memcpy(pos, abuf, la);
1989 pos += la;
1990
1991 /* Initial UPDATE fields */
1992 put_u16(buf+0, 0);
1993 put_u16(buf+2, pos-buf-4);
1994
1995 return pos;
1996 }
1997
1998 #undef MAX_ATTRS_LENGTH
1999
2000 static byte *
2001 bgp_create_ip_unreach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
2002 {
2003 /*
2004 * 2 B Withdrawn Routes Length
2005 * var IPv4 Withdrawn Routes NLRI
2006 * 2 B Total Path Attribute Length (zero)
2007 * --- Path Attributes (unused)
2008 * --- IPv4 Network Layer Reachability Information (unused)
2009 */
2010
2011 uint len = bgp_encode_nlri(s, buck, buf+2, end);
2012
2013 put_u16(buf+0, len);
2014 put_u16(buf+2+len, 0);
2015
2016 return buf+4+len;
2017 }
2018
2019 static byte *
2020 bgp_create_mp_unreach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
2021 {
2022 /*
2023 * 2 B Withdrawn Routes Length (zero)
2024 * --- IPv4 Withdrawn Routes NLRI (unused)
2025 * 2 B Total Path Attribute Length
2026 * 1 B MP_UNREACH_NLRI hdr - Attribute Flags
2027 * 1 B MP_UNREACH_NLRI hdr - Attribute Type Code
2028 * 2 B MP_UNREACH_NLRI hdr - Length of Attribute Data
2029 * 2 B MP_UNREACH_NLRI data - Address Family Identifier
2030 * 1 B MP_UNREACH_NLRI data - Subsequent Address Family Identifier
2031 * var MP_UNREACH_NLRI data - Network Layer Reachability Information
2032 * --- IPv4 Network Layer Reachability Information (unused)
2033 */
2034
2035 uint len = bgp_encode_nlri(s, buck, buf+11, end);
2036
2037 put_u16(buf+0, 0);
2038 put_u16(buf+2, 7+len);
2039
2040 /* Begin of MP_UNREACH_NLRI atribute */
2041 buf[4] = BAF_OPTIONAL | BAF_EXT_LEN;
2042 buf[5] = BA_MP_UNREACH_NLRI;
2043 put_u16(buf+6, 3+len);
2044 put_af3(buf+8, s->channel->afi);
2045
2046 return buf+11+len;
2047 }
2048
2049 static byte *
2050 bgp_create_update(struct bgp_channel *c, byte *buf)
2051 {
2052 struct bgp_proto *p = (void *) c->c.proto;
2053 struct bgp_bucket *buck;
2054 byte *end = buf + (bgp_max_packet_length(p->conn) - BGP_HEADER_LENGTH);
2055 byte *res = NULL;
2056
2057 again: ;
2058
2059 /* Initialize write state */
2060 struct bgp_write_state s = {
2061 .proto = p,
2062 .channel = c,
2063 .pool = bgp_linpool,
2064 .as4_session = p->as4_session,
2065 .add_path = c->add_path_tx,
2066 .mpls = c->desc->mpls,
2067 };
2068
2069 /* Try unreachable bucket */
2070 if ((buck = c->withdraw_bucket) && !EMPTY_LIST(buck->prefixes))
2071 {
2072 res = (c->afi == BGP_AF_IPV4) && !c->ext_next_hop ?
2073 bgp_create_ip_unreach(&s, buck, buf, end):
2074 bgp_create_mp_unreach(&s, buck, buf, end);
2075
2076 goto done;
2077 }
2078
2079 /* Try reachable buckets */
2080 if (!EMPTY_LIST(c->bucket_queue))
2081 {
2082 buck = HEAD(c->bucket_queue);
2083
2084 /* Cleanup empty buckets */
2085 if (EMPTY_LIST(buck->prefixes))
2086 {
2087 bgp_free_bucket(c, buck);
2088 goto again;
2089 }
2090
2091 res = (c->afi == BGP_AF_IPV4) && !c->ext_next_hop ?
2092 bgp_create_ip_reach(&s, buck, buf, end):
2093 bgp_create_mp_reach(&s, buck, buf, end);
2094
2095 if (EMPTY_LIST(buck->prefixes))
2096 bgp_free_bucket(c, buck);
2097 else
2098 bgp_defer_bucket(c, buck);
2099
2100 if (!res)
2101 goto again;
2102
2103 goto done;
2104 }
2105
2106 /* No more prefixes to send */
2107 return NULL;
2108
2109 done:
2110 BGP_TRACE_RL(&rl_snd_update, D_PACKETS, "Sending UPDATE");
2111 lp_flush(s.pool);
2112
2113 return res;
2114 }
2115
2116 static byte *
2117 bgp_create_ip_end_mark(struct bgp_channel *c UNUSED, byte *buf)
2118 {
2119 /* Empty update packet */
2120 put_u32(buf, 0);
2121
2122 return buf+4;
2123 }
2124
2125 static byte *
2126 bgp_create_mp_end_mark(struct bgp_channel *c, byte *buf)
2127 {
2128 put_u16(buf+0, 0);
2129 put_u16(buf+2, 6); /* length 4--9 */
2130
2131 /* Empty MP_UNREACH_NLRI atribute */
2132 buf[4] = BAF_OPTIONAL;
2133 buf[5] = BA_MP_UNREACH_NLRI;
2134 buf[6] = 3; /* Length 7--9 */
2135 put_af3(buf+7, c->afi);
2136
2137 return buf+10;
2138 }
2139
2140 static byte *
2141 bgp_create_end_mark(struct bgp_channel *c, byte *buf)
2142 {
2143 struct bgp_proto *p = (void *) c->c.proto;
2144
2145 BGP_TRACE(D_PACKETS, "Sending END-OF-RIB");
2146
2147 return (c->afi == BGP_AF_IPV4) ?
2148 bgp_create_ip_end_mark(c, buf):
2149 bgp_create_mp_end_mark(c, buf);
2150 }
2151
2152 static inline void
2153 bgp_rx_end_mark(struct bgp_parse_state *s, u32 afi)
2154 {
2155 struct bgp_proto *p = s->proto;
2156 struct bgp_channel *c = bgp_get_channel(p, afi);
2157
2158 BGP_TRACE(D_PACKETS, "Got END-OF-RIB");
2159
2160 if (!c)
2161 DISCARD(BAD_AFI, BGP_AFI(afi), BGP_SAFI(afi));
2162
2163 if (c->load_state == BFS_LOADING)
2164 c->load_state = BFS_NONE;
2165
2166 if (p->p.gr_recovery)
2167 channel_graceful_restart_unlock(&c->c);
2168
2169 if (c->gr_active)
2170 bgp_graceful_restart_done(c);
2171 }
2172
2173 static inline void
2174 bgp_decode_nlri(struct bgp_parse_state *s, u32 afi, byte *nlri, uint len, ea_list *ea, byte *nh, uint nh_len)
2175 {
2176 struct bgp_channel *c = bgp_get_channel(s->proto, afi);
2177 rta *a = NULL;
2178
2179 if (!c)
2180 DISCARD(BAD_AFI, BGP_AFI(afi), BGP_SAFI(afi));
2181
2182 s->channel = c;
2183 s->add_path = c->add_path_rx;
2184 s->mpls = c->desc->mpls;
2185
2186 s->last_id = 0;
2187 s->last_src = s->proto->p.main_source;
2188
2189 /*
2190 * IPv4 BGP and MP-BGP may be used together in one update, therefore we do not
2191 * add BA_NEXT_HOP in bgp_decode_attrs(), but we add it here independently for
2192 * IPv4 BGP and MP-BGP. We undo the attribute (and possibly others attached by
2193 * decode_next_hop hooks) by restoring a->eattrs afterwards.
2194 */
2195
2196 if (ea)
2197 {
2198 a = allocz(RTA_MAX_SIZE);
2199
2200 a->source = RTS_BGP;
2201 a->scope = SCOPE_UNIVERSE;
2202 a->from = s->proto->cf->remote_ip;
2203 a->eattrs = ea;
2204
2205 c->desc->decode_next_hop(s, nh, nh_len, a);
2206
2207 /* Handle withdraw during next hop decoding */
2208 if (s->err_withdraw)
2209 a = NULL;
2210 }
2211
2212 c->desc->decode_nlri(s, nlri, len, a);
2213
2214 rta_free(s->cached_rta);
2215 s->cached_rta = NULL;
2216 }
2217
2218 static void
2219 bgp_rx_update(struct bgp_conn *conn, byte *pkt, uint len)
2220 {
2221 struct bgp_proto *p = conn->bgp;
2222 ea_list *ea = NULL;
2223
2224 BGP_TRACE_RL(&rl_rcv_update, D_PACKETS, "Got UPDATE");
2225
2226 /* Workaround for some BGP implementations that skip initial KEEPALIVE */
2227 if (conn->state == BS_OPENCONFIRM)
2228 bgp_conn_enter_established_state(conn);
2229
2230 if (conn->state != BS_ESTABLISHED)
2231 { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
2232
2233 bgp_start_timer(conn->hold_timer, conn->hold_time);
2234
2235 /* Initialize parse state */
2236 struct bgp_parse_state s = {
2237 .proto = p,
2238 .pool = bgp_linpool,
2239 .as4_session = p->as4_session,
2240 };
2241
2242 /* Parse error handler */
2243 if (setjmp(s.err_jmpbuf))
2244 {
2245 bgp_error(conn, 3, s.err_subcode, NULL, 0);
2246 goto done;
2247 }
2248
2249 /* Check minimal length */
2250 if (len < 23)
2251 { bgp_error(conn, 1, 2, pkt+16, 2); return; }
2252
2253 /* Skip fixed header */
2254 uint pos = 19;
2255
2256 /*
2257 * UPDATE message format
2258 *
2259 * 2 B IPv4 Withdrawn Routes Length
2260 * var IPv4 Withdrawn Routes NLRI
2261 * 2 B Total Path Attribute Length
2262 * var Path Attributes
2263 * var IPv4 Reachable Routes NLRI
2264 */
2265
2266 s.ip_unreach_len = get_u16(pkt + pos);
2267 s.ip_unreach_nlri = pkt + pos + 2;
2268 pos += 2 + s.ip_unreach_len;
2269
2270 if (pos + 2 > len)
2271 bgp_parse_error(&s, 1);
2272
2273 s.attr_len = get_u16(pkt + pos);
2274 s.attrs = pkt + pos + 2;
2275 pos += 2 + s.attr_len;
2276
2277 if (pos > len)
2278 bgp_parse_error(&s, 1);
2279
2280 s.ip_reach_len = len - pos;
2281 s.ip_reach_nlri = pkt + pos;
2282
2283
2284 if (s.attr_len)
2285 ea = bgp_decode_attrs(&s, s.attrs, s.attr_len);
2286
2287 /* Check for End-of-RIB marker */
2288 if (!s.attr_len && !s.ip_unreach_len && !s.ip_reach_len)
2289 { bgp_rx_end_mark(&s, BGP_AF_IPV4); goto done; }
2290
2291 /* Check for MP End-of-RIB marker */
2292 if ((s.attr_len < 8) && !s.ip_unreach_len && !s.ip_reach_len &&
2293 !s.mp_reach_len && !s.mp_unreach_len && s.mp_unreach_af)
2294 { bgp_rx_end_mark(&s, s.mp_unreach_af); goto done; }
2295
2296 if (s.ip_unreach_len)
2297 bgp_decode_nlri(&s, BGP_AF_IPV4, s.ip_unreach_nlri, s.ip_unreach_len, NULL, NULL, 0);
2298
2299 if (s.mp_unreach_len)
2300 bgp_decode_nlri(&s, s.mp_unreach_af, s.mp_unreach_nlri, s.mp_unreach_len, NULL, NULL, 0);
2301
2302 if (s.ip_reach_len)
2303 bgp_decode_nlri(&s, BGP_AF_IPV4, s.ip_reach_nlri, s.ip_reach_len,
2304 ea, s.ip_next_hop_data, s.ip_next_hop_len);
2305
2306 if (s.mp_reach_len)
2307 bgp_decode_nlri(&s, s.mp_reach_af, s.mp_reach_nlri, s.mp_reach_len,
2308 ea, s.mp_next_hop_data, s.mp_next_hop_len);
2309
2310 done:
2311 rta_free(s.cached_rta);
2312 lp_flush(s.pool);
2313 return;
2314 }
2315
2316
2317 /*
2318 * ROUTE-REFRESH
2319 */
2320
2321 static inline byte *
2322 bgp_create_route_refresh(struct bgp_channel *c, byte *buf)
2323 {
2324 struct bgp_proto *p = (void *) c->c.proto;
2325
2326 BGP_TRACE(D_PACKETS, "Sending ROUTE-REFRESH");
2327
2328 /* Original route refresh request, RFC 2918 */
2329 put_af4(buf, c->afi);
2330 buf[2] = BGP_RR_REQUEST;
2331
2332 return buf+4;
2333 }
2334
2335 static inline byte *
2336 bgp_create_begin_refresh(struct bgp_channel *c, byte *buf)
2337 {
2338 struct bgp_proto *p = (void *) c->c.proto;
2339
2340 BGP_TRACE(D_PACKETS, "Sending BEGIN-OF-RR");
2341
2342 /* Demarcation of beginning of route refresh (BoRR), RFC 7313 */
2343 put_af4(buf, c->afi);
2344 buf[2] = BGP_RR_BEGIN;
2345
2346 return buf+4;
2347 }
2348
2349 static inline byte *
2350 bgp_create_end_refresh(struct bgp_channel *c, byte *buf)
2351 {
2352 struct bgp_proto *p = (void *) c->c.proto;
2353
2354 BGP_TRACE(D_PACKETS, "Sending END-OF-RR");
2355
2356 /* Demarcation of ending of route refresh (EoRR), RFC 7313 */
2357 put_af4(buf, c->afi);
2358 buf[2] = BGP_RR_END;
2359
2360 return buf+4;
2361 }
2362
2363 static void
2364 bgp_rx_route_refresh(struct bgp_conn *conn, byte *pkt, uint len)
2365 {
2366 struct bgp_proto *p = conn->bgp;
2367
2368 if (conn->state != BS_ESTABLISHED)
2369 { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
2370
2371 if (!conn->local_caps->route_refresh)
2372 { bgp_error(conn, 1, 3, pkt+18, 1); return; }
2373
2374 if (len < (BGP_HEADER_LENGTH + 4))
2375 { bgp_error(conn, 1, 2, pkt+16, 2); return; }
2376
2377 if (len > (BGP_HEADER_LENGTH + 4))
2378 { bgp_error(conn, 7, 1, pkt, MIN(len, 2048)); return; }
2379
2380 struct bgp_channel *c = bgp_get_channel(p, get_af4(pkt+19));
2381 if (!c)
2382 {
2383 log(L_WARN "%s: Got ROUTE-REFRESH subtype %u for AF %u.%u, ignoring",
2384 p->p.name, pkt[21], get_u16(pkt+19), pkt[22]);
2385 return;
2386 }
2387
2388 /* RFC 7313 redefined reserved field as RR message subtype */
2389 uint subtype = p->enhanced_refresh ? pkt[21] : BGP_RR_REQUEST;
2390
2391 switch (subtype)
2392 {
2393 case BGP_RR_REQUEST:
2394 BGP_TRACE(D_PACKETS, "Got ROUTE-REFRESH");
2395 channel_request_feeding(&c->c);
2396 break;
2397
2398 case BGP_RR_BEGIN:
2399 BGP_TRACE(D_PACKETS, "Got BEGIN-OF-RR");
2400 bgp_refresh_begin(c);
2401 break;
2402
2403 case BGP_RR_END:
2404 BGP_TRACE(D_PACKETS, "Got END-OF-RR");
2405 bgp_refresh_end(c);
2406 break;
2407
2408 default:
2409 log(L_WARN "%s: Got ROUTE-REFRESH message with unknown subtype %u, ignoring",
2410 p->p.name, subtype);
2411 break;
2412 }
2413 }
2414
2415 static inline struct bgp_channel *
2416 bgp_get_channel_to_send(struct bgp_proto *p, struct bgp_conn *conn)
2417 {
2418 uint i = conn->last_channel;
2419
2420 /* Try the last channel, but at most several times */
2421 if ((conn->channels_to_send & (1 << i)) &&
2422 (conn->last_channel_count < 16))
2423 goto found;
2424
2425 /* Find channel with non-zero channels_to_send */
2426 do
2427 {
2428 i++;
2429 if (i >= p->channel_count)
2430 i = 0;
2431 }
2432 while (! (conn->channels_to_send & (1 << i)));
2433
2434 /* Use that channel */
2435 conn->last_channel = i;
2436 conn->last_channel_count = 0;
2437
2438 found:
2439 conn->last_channel_count++;
2440 return p->channel_map[i];
2441 }
2442
2443 static inline int
2444 bgp_send(struct bgp_conn *conn, uint type, uint len)
2445 {
2446 sock *sk = conn->sk;
2447 byte *buf = sk->tbuf;
2448
2449 memset(buf, 0xff, 16); /* Marker */
2450 put_u16(buf+16, len);
2451 buf[18] = type;
2452
2453 return sk_send(sk, len);
2454 }
2455
2456 /**
2457 * bgp_fire_tx - transmit packets
2458 * @conn: connection
2459 *
2460 * Whenever the transmit buffers of the underlying TCP connection
2461 * are free and we have any packets queued for sending, the socket functions
2462 * call bgp_fire_tx() which takes care of selecting the highest priority packet
2463 * queued (Notification > Keepalive > Open > Update), assembling its header
2464 * and body and sending it to the connection.
2465 */
2466 static int
2467 bgp_fire_tx(struct bgp_conn *conn)
2468 {
2469 struct bgp_proto *p = conn->bgp;
2470 struct bgp_channel *c;
2471 byte *buf, *pkt, *end;
2472 uint s;
2473
2474 if (!conn->sk)
2475 return 0;
2476
2477 buf = conn->sk->tbuf;
2478 pkt = buf + BGP_HEADER_LENGTH;
2479 s = conn->packets_to_send;
2480
2481 if (s & (1 << PKT_SCHEDULE_CLOSE))
2482 {
2483 /* We can finally close connection and enter idle state */
2484 bgp_conn_enter_idle_state(conn);
2485 return 0;
2486 }
2487 if (s & (1 << PKT_NOTIFICATION))
2488 {
2489 conn->packets_to_send = 1 << PKT_SCHEDULE_CLOSE;
2490 end = bgp_create_notification(conn, pkt);
2491 return bgp_send(conn, PKT_NOTIFICATION, end - buf);
2492 }
2493 else if (s & (1 << PKT_KEEPALIVE))
2494 {
2495 conn->packets_to_send &= ~(1 << PKT_KEEPALIVE);
2496 BGP_TRACE(D_PACKETS, "Sending KEEPALIVE");
2497 bgp_start_timer(conn->keepalive_timer, conn->keepalive_time);
2498 return bgp_send(conn, PKT_KEEPALIVE, BGP_HEADER_LENGTH);
2499 }
2500 else if (s & (1 << PKT_OPEN))
2501 {
2502 conn->packets_to_send &= ~(1 << PKT_OPEN);
2503 end = bgp_create_open(conn, pkt);
2504 return bgp_send(conn, PKT_OPEN, end - buf);
2505 }
2506 else while (conn->channels_to_send)
2507 {
2508 c = bgp_get_channel_to_send(p, conn);
2509 s = c->packets_to_send;
2510
2511 if (s & (1 << PKT_ROUTE_REFRESH))
2512 {
2513 c->packets_to_send &= ~(1 << PKT_ROUTE_REFRESH);
2514 end = bgp_create_route_refresh(c, pkt);
2515 return bgp_send(conn, PKT_ROUTE_REFRESH, end - buf);
2516 }
2517 else if (s & (1 << PKT_BEGIN_REFRESH))
2518 {
2519 /* BoRR is a subtype of RR, but uses separate bit in packets_to_send */
2520 c->packets_to_send &= ~(1 << PKT_BEGIN_REFRESH);
2521 end = bgp_create_begin_refresh(c, pkt);
2522 return bgp_send(conn, PKT_ROUTE_REFRESH, end - buf);
2523 }
2524 else if (s & (1 << PKT_UPDATE))
2525 {
2526 end = bgp_create_update(c, pkt);
2527 if (end)
2528 return bgp_send(conn, PKT_UPDATE, end - buf);
2529
2530 /* No update to send, perhaps we need to send End-of-RIB or EoRR */
2531 c->packets_to_send = 0;
2532 conn->channels_to_send &= ~(1 << c->index);
2533
2534 if (c->feed_state == BFS_LOADED)
2535 {
2536 c->feed_state = BFS_NONE;
2537 end = bgp_create_end_mark(c, pkt);
2538 return bgp_send(conn, PKT_UPDATE, end - buf);
2539 }
2540
2541 else if (c->feed_state == BFS_REFRESHED)
2542 {
2543 c->feed_state = BFS_NONE;
2544 end = bgp_create_end_refresh(c, pkt);
2545 return bgp_send(conn, PKT_ROUTE_REFRESH, end - buf);
2546 }
2547 }
2548 else if (s)
2549 bug("Channel packets_to_send: %x", s);
2550
2551 c->packets_to_send = 0;
2552 conn->channels_to_send &= ~(1 << c->index);
2553 }
2554
2555 return 0;
2556 }
2557
2558 /**
2559 * bgp_schedule_packet - schedule a packet for transmission
2560 * @conn: connection
2561 * @c: channel
2562 * @type: packet type
2563 *
2564 * Schedule a packet of type @type to be sent as soon as possible.
2565 */
2566 void
2567 bgp_schedule_packet(struct bgp_conn *conn, struct bgp_channel *c, int type)
2568 {
2569 ASSERT(conn->sk);
2570
2571 DBG("BGP: Scheduling packet type %d\n", type);
2572
2573 if (c)
2574 {
2575 if (! conn->channels_to_send)
2576 {
2577 conn->last_channel = c->index;
2578 conn->last_channel_count = 0;
2579 }
2580
2581 c->packets_to_send |= 1 << type;
2582 conn->channels_to_send |= 1 << c->index;
2583 }
2584 else
2585 conn->packets_to_send |= 1 << type;
2586
2587 if ((conn->sk->tpos == conn->sk->tbuf) && !ev_active(conn->tx_ev))
2588 ev_schedule(conn->tx_ev);
2589 }
2590
2591 void
2592 bgp_kick_tx(void *vconn)
2593 {
2594 struct bgp_conn *conn = vconn;
2595
2596 DBG("BGP: kicking TX\n");
2597 while (bgp_fire_tx(conn) > 0)
2598 ;
2599 }
2600
2601 void
2602 bgp_tx(sock *sk)
2603 {
2604 struct bgp_conn *conn = sk->data;
2605
2606 DBG("BGP: TX hook\n");
2607 while (bgp_fire_tx(conn) > 0)
2608 ;
2609 }
2610
2611
2612 static struct {
2613 byte major, minor;
2614 byte *msg;
2615 } bgp_msg_table[] = {
2616 { 1, 0, "Invalid message header" },
2617 { 1, 1, "Connection not synchronized" },
2618 { 1, 2, "Bad message length" },
2619 { 1, 3, "Bad message type" },
2620 { 2, 0, "Invalid OPEN message" },
2621 { 2, 1, "Unsupported version number" },
2622 { 2, 2, "Bad peer AS" },
2623 { 2, 3, "Bad BGP identifier" },
2624 { 2, 4, "Unsupported optional parameter" },
2625 { 2, 5, "Authentication failure" },
2626 { 2, 6, "Unacceptable hold time" },
2627 { 2, 7, "Required capability missing" }, /* [RFC5492] */
2628 { 2, 8, "No supported AFI/SAFI" }, /* This error msg is nonstandard */
2629 { 3, 0, "Invalid UPDATE message" },
2630 { 3, 1, "Malformed attribute list" },
2631 { 3, 2, "Unrecognized well-known attribute" },
2632 { 3, 3, "Missing mandatory attribute" },
2633 { 3, 4, "Invalid attribute flags" },
2634 { 3, 5, "Invalid attribute length" },
2635 { 3, 6, "Invalid ORIGIN attribute" },
2636 { 3, 7, "AS routing loop" }, /* Deprecated */
2637 { 3, 8, "Invalid NEXT_HOP attribute" },
2638 { 3, 9, "Optional attribute error" },
2639 { 3, 10, "Invalid network field" },
2640 { 3, 11, "Malformed AS_PATH" },
2641 { 4, 0, "Hold timer expired" },
2642 { 5, 0, "Finite state machine error" }, /* Subcodes are according to [RFC6608] */
2643 { 5, 1, "Unexpected message in OpenSent state" },
2644 { 5, 2, "Unexpected message in OpenConfirm state" },
2645 { 5, 3, "Unexpected message in Established state" },
2646 { 6, 0, "Cease" }, /* Subcodes are according to [RFC4486] */
2647 { 6, 1, "Maximum number of prefixes reached" },
2648 { 6, 2, "Administrative shutdown" },
2649 { 6, 3, "Peer de-configured" },
2650 { 6, 4, "Administrative reset" },
2651 { 6, 5, "Connection rejected" },
2652 { 6, 6, "Other configuration change" },
2653 { 6, 7, "Connection collision resolution" },
2654 { 6, 8, "Out of Resources" },
2655 { 7, 0, "Invalid ROUTE-REFRESH message" }, /* [RFC7313] */
2656 { 7, 1, "Invalid ROUTE-REFRESH message length" } /* [RFC7313] */
2657 };
2658
2659 /**
2660 * bgp_error_dsc - return BGP error description
2661 * @code: BGP error code
2662 * @subcode: BGP error subcode
2663 *
2664 * bgp_error_dsc() returns error description for BGP errors
2665 * which might be static string or given temporary buffer.
2666 */
2667 const char *
2668 bgp_error_dsc(uint code, uint subcode)
2669 {
2670 static char buff[32];
2671 uint i;
2672
2673 for (i=0; i < ARRAY_SIZE(bgp_msg_table); i++)
2674 if (bgp_msg_table[i].major == code && bgp_msg_table[i].minor == subcode)
2675 return bgp_msg_table[i].msg;
2676
2677 bsprintf(buff, "Unknown error %u.%u", code, subcode);
2678 return buff;
2679 }
2680
2681 void
2682 bgp_log_error(struct bgp_proto *p, u8 class, char *msg, uint code, uint subcode, byte *data, uint len)
2683 {
2684 const byte *name;
2685 byte *t, argbuf[36];
2686 uint i;
2687
2688 /* Don't report Cease messages generated by myself */
2689 if (code == 6 && class == BE_BGP_TX)
2690 return;
2691
2692 name = bgp_error_dsc(code, subcode);
2693 t = argbuf;
2694 if (len)
2695 {
2696 *t++ = ':';
2697 *t++ = ' ';
2698
2699 if ((code == 2) && (subcode == 2) && ((len == 2) || (len == 4)))
2700 {
2701 /* Bad peer AS - we would like to print the AS */
2702 t += bsprintf(t, "%u", (len == 2) ? get_u16(data) : get_u32(data));
2703 goto done;
2704 }
2705 if (len > 16)
2706 len = 16;
2707 for (i=0; i<len; i++)
2708 t += bsprintf(t, "%02x", data[i]);
2709 }
2710 done:
2711 *t = 0;
2712 log(L_REMOTE "%s: %s: %s%s", p->p.name, msg, name, argbuf);
2713 }
2714
2715 static void
2716 bgp_rx_notification(struct bgp_conn *conn, byte *pkt, uint len)
2717 {
2718 struct bgp_proto *p = conn->bgp;
2719
2720 if (len < 21)
2721 { bgp_error(conn, 1, 2, pkt+16, 2); return; }
2722
2723 uint code = pkt[19];
2724 uint subcode = pkt[20];
2725 int err = (code != 6);
2726
2727 bgp_log_error(p, BE_BGP_RX, "Received", code, subcode, pkt+21, len-21);
2728 bgp_store_error(p, conn, BE_BGP_RX, (code << 16) | subcode);
2729
2730 bgp_conn_enter_close_state(conn);
2731 bgp_schedule_packet(conn, NULL, PKT_SCHEDULE_CLOSE);
2732
2733 if (err)
2734 {
2735 bgp_update_startup_delay(p);
2736 bgp_stop(p, 0);
2737 }
2738 }
2739
2740 static void
2741 bgp_rx_keepalive(struct bgp_conn *conn)
2742 {
2743 struct bgp_proto *p = conn->bgp;
2744
2745 BGP_TRACE(D_PACKETS, "Got KEEPALIVE");
2746 bgp_start_timer(conn->hold_timer, conn->hold_time);
2747
2748 if (conn->state == BS_OPENCONFIRM)
2749 { bgp_conn_enter_established_state(conn); return; }
2750
2751 if (conn->state != BS_ESTABLISHED)
2752 bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0);
2753 }
2754
2755
2756 /**
2757 * bgp_rx_packet - handle a received packet
2758 * @conn: BGP connection
2759 * @pkt: start of the packet
2760 * @len: packet size
2761 *
2762 * bgp_rx_packet() takes a newly received packet and calls the corresponding
2763 * packet handler according to the packet type.
2764 */
2765 static void
2766 bgp_rx_packet(struct bgp_conn *conn, byte *pkt, uint len)
2767 {
2768 byte type = pkt[18];
2769
2770 DBG("BGP: Got packet %02x (%d bytes)\n", type, len);
2771
2772 if (conn->bgp->p.mrtdump & MD_MESSAGES)
2773 mrt_dump_bgp_packet(conn, pkt, len);
2774
2775 switch (type)
2776 {
2777 case PKT_OPEN: return bgp_rx_open(conn, pkt, len);
2778 case PKT_UPDATE: return bgp_rx_update(conn, pkt, len);
2779 case PKT_NOTIFICATION: return bgp_rx_notification(conn, pkt, len);
2780 case PKT_KEEPALIVE: return bgp_rx_keepalive(conn);
2781 case PKT_ROUTE_REFRESH: return bgp_rx_route_refresh(conn, pkt, len);
2782 default: bgp_error(conn, 1, 3, pkt+18, 1);
2783 }
2784 }
2785
2786 /**
2787 * bgp_rx - handle received data
2788 * @sk: socket
2789 * @size: amount of data received
2790 *
2791 * bgp_rx() is called by the socket layer whenever new data arrive from
2792 * the underlying TCP connection. It assembles the data fragments to packets,
2793 * checks their headers and framing and passes complete packets to
2794 * bgp_rx_packet().
2795 */
2796 int
2797 bgp_rx(sock *sk, uint size)
2798 {
2799 struct bgp_conn *conn = sk->data;
2800 byte *pkt_start = sk->rbuf;
2801 byte *end = pkt_start + size;
2802 uint i, len;
2803
2804 DBG("BGP: RX hook: Got %d bytes\n", size);
2805 while (end >= pkt_start + BGP_HEADER_LENGTH)
2806 {
2807 if ((conn->state == BS_CLOSE) || (conn->sk != sk))
2808 return 0;
2809 for(i=0; i<16; i++)
2810 if (pkt_start[i] != 0xff)
2811 {
2812 bgp_error(conn, 1, 1, NULL, 0);
2813 break;
2814 }
2815 len = get_u16(pkt_start+16);
2816 if ((len < BGP_HEADER_LENGTH) || (len > bgp_max_packet_length(conn)))
2817 {
2818 bgp_error(conn, 1, 2, pkt_start+16, 2);
2819 break;
2820 }
2821 if (end < pkt_start + len)
2822 break;
2823 bgp_rx_packet(conn, pkt_start, len);
2824 pkt_start += len;
2825 }
2826 if (pkt_start != sk->rbuf)
2827 {
2828 memmove(sk->rbuf, pkt_start, end - pkt_start);
2829 sk->rpos = sk->rbuf + (end - pkt_start);
2830 }
2831 return 0;
2832 }