]> git.ipfire.org Git - thirdparty/bird.git/blob - proto/bgp/bgp.c
Build: switch on -Wextra, get rid of most of the warnings
[thirdparty/bird.git] / proto / bgp / bgp.c
1 /*
2 * BIRD -- The Border Gateway Protocol
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 /**
10 * DOC: Border Gateway Protocol
11 *
12 * The BGP protocol is implemented in three parts: |bgp.c| which takes care of the
13 * connection and most of the interface with BIRD core, |packets.c| handling
14 * both incoming and outgoing BGP packets and |attrs.c| containing functions for
15 * manipulation with BGP attribute lists.
16 *
17 * As opposed to the other existing routing daemons, BIRD has a sophisticated core
18 * architecture which is able to keep all the information needed by BGP in the
19 * primary routing table, therefore no complex data structures like a central
20 * BGP table are needed. This increases memory footprint of a BGP router with
21 * many connections, but not too much and, which is more important, it makes
22 * BGP much easier to implement.
23 *
24 * Each instance of BGP (corresponding to a single BGP peer) is described by a &bgp_proto
25 * structure to which are attached individual connections represented by &bgp_connection
26 * (usually, there exists only one connection, but during BGP session setup, there
27 * can be more of them). The connections are handled according to the BGP state machine
28 * defined in the RFC with all the timers and all the parameters configurable.
29 *
30 * In incoming direction, we listen on the connection's socket and each time we receive
31 * some input, we pass it to bgp_rx(). It decodes packet headers and the markers and
32 * passes complete packets to bgp_rx_packet() which distributes the packet according
33 * to its type.
34 *
35 * In outgoing direction, we gather all the routing updates and sort them to buckets
36 * (&bgp_bucket) according to their attributes (we keep a hash table for fast comparison
37 * of &rta's and a &fib which helps us to find if we already have another route for
38 * the same destination queued for sending, so that we can replace it with the new one
39 * immediately instead of sending both updates). There also exists a special bucket holding
40 * all the route withdrawals which cannot be queued anywhere else as they don't have any
41 * attributes. If we have any packet to send (due to either new routes or the connection
42 * tracking code wanting to send a Open, Keepalive or Notification message), we call
43 * bgp_schedule_packet() which sets the corresponding bit in a @packet_to_send
44 * bit field in &bgp_conn and as soon as the transmit socket buffer becomes empty,
45 * we call bgp_fire_tx(). It inspects state of all the packet type bits and calls
46 * the corresponding bgp_create_xx() functions, eventually rescheduling the same packet
47 * type if we have more data of the same type to send.
48 *
49 * The processing of attributes consists of two functions: bgp_decode_attrs() for checking
50 * of the attribute blocks and translating them to the language of BIRD's extended attributes
51 * and bgp_encode_attrs() which does the converse. Both functions are built around a
52 * @bgp_attr_table array describing all important characteristics of all known attributes.
53 * Unknown transitive attributes are attached to the route as %EAF_TYPE_OPAQUE byte streams.
54 *
55 * BGP protocol implements graceful restart in both restarting (local restart)
56 * and receiving (neighbor restart) roles. The first is handled mostly by the
57 * graceful restart code in the nest, BGP protocol just handles capabilities,
58 * sets @gr_wait and locks graceful restart until end-of-RIB mark is received.
59 * The second is implemented by internal restart of the BGP state to %BS_IDLE
60 * and protocol state to %PS_START, but keeping the protocol up from the core
61 * point of view and therefore maintaining received routes. Routing table
62 * refresh cycle (rt_refresh_begin(), rt_refresh_end()) is used for removing
63 * stale routes after reestablishment of BGP session during graceful restart.
64 */
65
66 #undef LOCAL_DEBUG
67
68 #include "nest/bird.h"
69 #include "nest/iface.h"
70 #include "nest/protocol.h"
71 #include "nest/route.h"
72 #include "nest/cli.h"
73 #include "nest/locks.h"
74 #include "conf/conf.h"
75 #include "lib/socket.h"
76 #include "lib/resource.h"
77 #include "lib/string.h"
78
79 #include "bgp.h"
80
81
82 struct linpool *bgp_linpool; /* Global temporary pool */
83 static sock *bgp_listen_sk; /* Global listening socket */
84 static int bgp_counter; /* Number of protocol instances using the listening socket */
85
86 static void bgp_close(struct bgp_proto *p, int apply_md5);
87 static void bgp_connect(struct bgp_proto *p);
88 static void bgp_active(struct bgp_proto *p);
89 static sock *bgp_setup_listen_sk(ip_addr addr, unsigned port, u32 flags);
90 static void bgp_update_bfd(struct bgp_proto *p, int use_bfd);
91
92
93 /**
94 * bgp_open - open a BGP instance
95 * @p: BGP instance
96 *
97 * This function allocates and configures shared BGP resources.
98 * Should be called as the last step during initialization
99 * (when lock is acquired and neighbor is ready).
100 * When error, state changed to PS_DOWN, -1 is returned and caller
101 * should return immediately.
102 */
103 static int
104 bgp_open(struct bgp_proto *p)
105 {
106 struct config *cfg = p->cf->c.global;
107 int errcode;
108
109 if (!bgp_listen_sk)
110 bgp_listen_sk = bgp_setup_listen_sk(cfg->listen_bgp_addr, cfg->listen_bgp_port, cfg->listen_bgp_flags);
111
112 if (!bgp_listen_sk)
113 {
114 errcode = BEM_NO_SOCKET;
115 goto err;
116 }
117
118 if (!bgp_linpool)
119 bgp_linpool = lp_new(&root_pool, 4080);
120
121 bgp_counter++;
122
123 if (p->cf->password)
124 if (sk_set_md5_auth(bgp_listen_sk, p->cf->source_addr, p->cf->remote_ip,
125 p->cf->iface, p->cf->password, p->cf->setkey) < 0)
126 {
127 sk_log_error(bgp_listen_sk, p->p.name);
128 bgp_close(p, 0);
129 errcode = BEM_INVALID_MD5;
130 goto err;
131 }
132
133 return 0;
134
135 err:
136 p->p.disabled = 1;
137 bgp_store_error(p, NULL, BE_MISC, errcode);
138 proto_notify_state(&p->p, PS_DOWN);
139 return -1;
140 }
141
142 static void
143 bgp_startup(struct bgp_proto *p)
144 {
145 BGP_TRACE(D_EVENTS, "Started");
146 p->start_state = p->cf->capabilities ? BSS_CONNECT : BSS_CONNECT_NOCAP;
147
148 if (!p->cf->passive)
149 bgp_active(p);
150 }
151
152 static void
153 bgp_startup_timeout(timer *t)
154 {
155 bgp_startup(t->data);
156 }
157
158
159 static void
160 bgp_initiate(struct bgp_proto *p)
161 {
162 int rv = bgp_open(p);
163 if (rv < 0)
164 return;
165
166 if (p->cf->bfd)
167 bgp_update_bfd(p, p->cf->bfd);
168
169 if (p->startup_delay)
170 {
171 p->start_state = BSS_DELAY;
172 BGP_TRACE(D_EVENTS, "Startup delayed by %d seconds due to errors", p->startup_delay);
173 bgp_start_timer(p->startup_timer, p->startup_delay);
174 }
175 else
176 bgp_startup(p);
177 }
178
179 /**
180 * bgp_close - close a BGP instance
181 * @p: BGP instance
182 * @apply_md5: 0 to disable unsetting MD5 auth
183 *
184 * This function frees and deconfigures shared BGP resources.
185 * @apply_md5 is set to 0 when bgp_close is called as a cleanup
186 * from failed bgp_open().
187 */
188 static void
189 bgp_close(struct bgp_proto *p, int apply_md5)
190 {
191 ASSERT(bgp_counter);
192 bgp_counter--;
193
194 if (p->cf->password && apply_md5)
195 if (sk_set_md5_auth(bgp_listen_sk, p->cf->source_addr, p->cf->remote_ip,
196 p->cf->iface, NULL, p->cf->setkey) < 0)
197 sk_log_error(bgp_listen_sk, p->p.name);
198
199 if (!bgp_counter)
200 {
201 rfree(bgp_listen_sk);
202 bgp_listen_sk = NULL;
203 rfree(bgp_linpool);
204 bgp_linpool = NULL;
205 }
206 }
207
208 /**
209 * bgp_start_timer - start a BGP timer
210 * @t: timer
211 * @value: time to fire (0 to disable the timer)
212 *
213 * This functions calls tm_start() on @t with time @value and the
214 * amount of randomization suggested by the BGP standard. Please use
215 * it for all BGP timers.
216 */
217 void
218 bgp_start_timer(timer *t, int value)
219 {
220 if (value)
221 {
222 /* The randomization procedure is specified in RFC 1771: 9.2.3.3 */
223 t->randomize = value / 4;
224 tm_start(t, value - t->randomize);
225 }
226 else
227 tm_stop(t);
228 }
229
230 /**
231 * bgp_close_conn - close a BGP connection
232 * @conn: connection to close
233 *
234 * This function takes a connection described by the &bgp_conn structure,
235 * closes its socket and frees all resources associated with it.
236 */
237 void
238 bgp_close_conn(struct bgp_conn *conn)
239 {
240 // struct bgp_proto *p = conn->bgp;
241
242 DBG("BGP: Closing connection\n");
243 conn->packets_to_send = 0;
244 rfree(conn->connect_retry_timer);
245 conn->connect_retry_timer = NULL;
246 rfree(conn->keepalive_timer);
247 conn->keepalive_timer = NULL;
248 rfree(conn->hold_timer);
249 conn->hold_timer = NULL;
250 rfree(conn->sk);
251 conn->sk = NULL;
252 rfree(conn->tx_ev);
253 conn->tx_ev = NULL;
254 }
255
256
257 /**
258 * bgp_update_startup_delay - update a startup delay
259 * @p: BGP instance
260 *
261 * This function updates a startup delay that is used to postpone next BGP connect.
262 * It also handles disable_after_error and might stop BGP instance when error
263 * happened and disable_after_error is on.
264 *
265 * It should be called when BGP protocol error happened.
266 */
267 void
268 bgp_update_startup_delay(struct bgp_proto *p)
269 {
270 struct bgp_config *cf = p->cf;
271
272 DBG("BGP: Updating startup delay\n");
273
274 if (p->last_proto_error && ((now - p->last_proto_error) >= (int) cf->error_amnesia_time))
275 p->startup_delay = 0;
276
277 p->last_proto_error = now;
278
279 if (cf->disable_after_error)
280 {
281 p->startup_delay = 0;
282 p->p.disabled = 1;
283 return;
284 }
285
286 if (!p->startup_delay)
287 p->startup_delay = cf->error_delay_time_min;
288 else
289 p->startup_delay = MIN(2 * p->startup_delay, cf->error_delay_time_max);
290 }
291
292 static void
293 bgp_graceful_close_conn(struct bgp_conn *conn, unsigned subcode)
294 {
295 switch (conn->state)
296 {
297 case BS_IDLE:
298 case BS_CLOSE:
299 return;
300 case BS_CONNECT:
301 case BS_ACTIVE:
302 bgp_conn_enter_idle_state(conn);
303 return;
304 case BS_OPENSENT:
305 case BS_OPENCONFIRM:
306 case BS_ESTABLISHED:
307 bgp_error(conn, 6, subcode, NULL, 0);
308 return;
309 default:
310 bug("bgp_graceful_close_conn: Unknown state %d", conn->state);
311 }
312 }
313
314 static void
315 bgp_down(struct bgp_proto *p)
316 {
317 if (p->start_state > BSS_PREPARE)
318 bgp_close(p, 1);
319
320 BGP_TRACE(D_EVENTS, "Down");
321 proto_notify_state(&p->p, PS_DOWN);
322 }
323
324 static void
325 bgp_decision(void *vp)
326 {
327 struct bgp_proto *p = vp;
328
329 DBG("BGP: Decision start\n");
330 if ((p->p.proto_state == PS_START)
331 && (p->outgoing_conn.state == BS_IDLE)
332 && (p->incoming_conn.state != BS_OPENCONFIRM)
333 && (!p->cf->passive))
334 bgp_active(p);
335
336 if ((p->p.proto_state == PS_STOP)
337 && (p->outgoing_conn.state == BS_IDLE)
338 && (p->incoming_conn.state == BS_IDLE))
339 bgp_down(p);
340 }
341
342 void
343 bgp_stop(struct bgp_proto *p, unsigned subcode)
344 {
345 proto_notify_state(&p->p, PS_STOP);
346 bgp_graceful_close_conn(&p->outgoing_conn, subcode);
347 bgp_graceful_close_conn(&p->incoming_conn, subcode);
348 ev_schedule(p->event);
349 }
350
351 static inline void
352 bgp_conn_set_state(struct bgp_conn *conn, unsigned new_state)
353 {
354 if (conn->bgp->p.mrtdump & MD_STATES)
355 mrt_dump_bgp_state_change(conn, conn->state, new_state);
356
357 conn->state = new_state;
358 }
359
360 void
361 bgp_conn_enter_openconfirm_state(struct bgp_conn *conn)
362 {
363 /* Really, most of the work is done in bgp_rx_open(). */
364 bgp_conn_set_state(conn, BS_OPENCONFIRM);
365 }
366
367 void
368 bgp_conn_enter_established_state(struct bgp_conn *conn)
369 {
370 struct bgp_proto *p = conn->bgp;
371
372 BGP_TRACE(D_EVENTS, "BGP session established");
373 DBG("BGP: UP!!!\n");
374
375 /* For multi-hop BGP sessions */
376 if (ipa_zero(p->source_addr))
377 p->source_addr = conn->sk->saddr;
378
379 conn->sk->fast_rx = 0;
380
381 p->conn = conn;
382 p->last_error_class = 0;
383 p->last_error_code = 0;
384 p->feed_state = BFS_NONE;
385 p->load_state = BFS_NONE;
386 bgp_init_bucket_table(p);
387 bgp_init_prefix_table(p, 8);
388
389 int peer_gr_ready = conn->peer_gr_aware && !(conn->peer_gr_flags & BGP_GRF_RESTART);
390
391 if (p->p.gr_recovery && !peer_gr_ready)
392 proto_graceful_restart_unlock(&p->p);
393
394 if (p->p.gr_recovery && (p->cf->gr_mode == BGP_GR_ABLE) && peer_gr_ready)
395 p->p.gr_wait = 1;
396
397 if (p->gr_active)
398 tm_stop(p->gr_timer);
399
400 if (p->gr_active && (!conn->peer_gr_able || !(conn->peer_gr_aflags & BGP_GRF_FORWARDING)))
401 bgp_graceful_restart_done(p);
402
403 /* GR capability implies that neighbor will send End-of-RIB */
404 if (conn->peer_gr_aware)
405 p->load_state = BFS_LOADING;
406
407 /* proto_notify_state() will likely call bgp_feed_begin(), setting p->feed_state */
408
409 bgp_conn_set_state(conn, BS_ESTABLISHED);
410 proto_notify_state(&p->p, PS_UP);
411 }
412
413 static void
414 bgp_conn_leave_established_state(struct bgp_proto *p)
415 {
416 BGP_TRACE(D_EVENTS, "BGP session closed");
417 p->conn = NULL;
418
419 if (p->p.proto_state == PS_UP)
420 bgp_stop(p, 0);
421 }
422
423 void
424 bgp_conn_enter_close_state(struct bgp_conn *conn)
425 {
426 struct bgp_proto *p = conn->bgp;
427 int os = conn->state;
428
429 bgp_conn_set_state(conn, BS_CLOSE);
430 tm_stop(conn->keepalive_timer);
431 conn->sk->rx_hook = NULL;
432
433 /* Timeout for CLOSE state, if we cannot send notification soon then we just hangup */
434 bgp_start_timer(conn->hold_timer, 10);
435
436 if (os == BS_ESTABLISHED)
437 bgp_conn_leave_established_state(p);
438 }
439
440 void
441 bgp_conn_enter_idle_state(struct bgp_conn *conn)
442 {
443 struct bgp_proto *p = conn->bgp;
444 int os = conn->state;
445
446 bgp_close_conn(conn);
447 bgp_conn_set_state(conn, BS_IDLE);
448 ev_schedule(p->event);
449
450 if (os == BS_ESTABLISHED)
451 bgp_conn_leave_established_state(p);
452 }
453
454 /**
455 * bgp_handle_graceful_restart - handle detected BGP graceful restart
456 * @p: BGP instance
457 *
458 * This function is called when a BGP graceful restart of the neighbor is
459 * detected (when the TCP connection fails or when a new TCP connection
460 * appears). The function activates processing of the restart - starts routing
461 * table refresh cycle and activates BGP restart timer. The protocol state goes
462 * back to %PS_START, but changing BGP state back to %BS_IDLE is left for the
463 * caller.
464 */
465 void
466 bgp_handle_graceful_restart(struct bgp_proto *p)
467 {
468 ASSERT(p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready);
469
470 BGP_TRACE(D_EVENTS, "Neighbor graceful restart detected%s",
471 p->gr_active ? " - already pending" : "");
472 proto_notify_state(&p->p, PS_START);
473
474 if (p->gr_active)
475 rt_refresh_end(p->p.main_ahook->table, p->p.main_ahook);
476
477 p->gr_active = 1;
478 bgp_start_timer(p->gr_timer, p->conn->peer_gr_time);
479 rt_refresh_begin(p->p.main_ahook->table, p->p.main_ahook);
480 }
481
482 /**
483 * bgp_graceful_restart_done - finish active BGP graceful restart
484 * @p: BGP instance
485 *
486 * This function is called when the active BGP graceful restart of the neighbor
487 * should be finished - either successfully (the neighbor sends all paths and
488 * reports end-of-RIB on the new session) or unsuccessfully (the neighbor does
489 * not support BGP graceful restart on the new session). The function ends
490 * routing table refresh cycle and stops BGP restart timer.
491 */
492 void
493 bgp_graceful_restart_done(struct bgp_proto *p)
494 {
495 BGP_TRACE(D_EVENTS, "Neighbor graceful restart done");
496 p->gr_active = 0;
497 tm_stop(p->gr_timer);
498 rt_refresh_end(p->p.main_ahook->table, p->p.main_ahook);
499 }
500
501 /**
502 * bgp_graceful_restart_timeout - timeout of graceful restart 'restart timer'
503 * @t: timer
504 *
505 * This function is a timeout hook for @gr_timer, implementing BGP restart time
506 * limit for reestablisment of the BGP session after the graceful restart. When
507 * fired, we just proceed with the usual protocol restart.
508 */
509
510 static void
511 bgp_graceful_restart_timeout(timer *t)
512 {
513 struct bgp_proto *p = t->data;
514
515 BGP_TRACE(D_EVENTS, "Neighbor graceful restart timeout");
516 bgp_stop(p, 0);
517 }
518
519
520 /**
521 * bgp_refresh_begin - start incoming enhanced route refresh sequence
522 * @p: BGP instance
523 *
524 * This function is called when an incoming enhanced route refresh sequence is
525 * started by the neighbor, demarcated by the BoRR packet. The function updates
526 * the load state and starts the routing table refresh cycle. Note that graceful
527 * restart also uses routing table refresh cycle, but RFC 7313 and load states
528 * ensure that these two sequences do not overlap.
529 */
530 void
531 bgp_refresh_begin(struct bgp_proto *p)
532 {
533 if (p->load_state == BFS_LOADING)
534 { log(L_WARN "%s: BEGIN-OF-RR received before END-OF-RIB, ignoring", p->p.name); return; }
535
536 p->load_state = BFS_REFRESHING;
537 rt_refresh_begin(p->p.main_ahook->table, p->p.main_ahook);
538 }
539
540 /**
541 * bgp_refresh_end - finish incoming enhanced route refresh sequence
542 * @p: BGP instance
543 *
544 * This function is called when an incoming enhanced route refresh sequence is
545 * finished by the neighbor, demarcated by the EoRR packet. The function updates
546 * the load state and ends the routing table refresh cycle. Routes not received
547 * during the sequence are removed by the nest.
548 */
549 void
550 bgp_refresh_end(struct bgp_proto *p)
551 {
552 if (p->load_state != BFS_REFRESHING)
553 { log(L_WARN "%s: END-OF-RR received without prior BEGIN-OF-RR, ignoring", p->p.name); return; }
554
555 p->load_state = BFS_NONE;
556 rt_refresh_end(p->p.main_ahook->table, p->p.main_ahook);
557 }
558
559
560 static void
561 bgp_send_open(struct bgp_conn *conn)
562 {
563 conn->start_state = conn->bgp->start_state;
564
565 // Default values, possibly changed by receiving capabilities.
566 conn->advertised_as = 0;
567 conn->peer_refresh_support = 0;
568 conn->peer_as4_support = 0;
569 conn->peer_add_path = 0;
570 conn->peer_enhanced_refresh_support = 0;
571 conn->peer_gr_aware = 0;
572 conn->peer_gr_able = 0;
573 conn->peer_gr_time = 0;
574 conn->peer_gr_flags = 0;
575 conn->peer_gr_aflags = 0;
576 conn->peer_ext_messages_support = 0;
577
578 DBG("BGP: Sending open\n");
579 conn->sk->rx_hook = bgp_rx;
580 conn->sk->tx_hook = bgp_tx;
581 tm_stop(conn->connect_retry_timer);
582 bgp_schedule_packet(conn, PKT_OPEN);
583 bgp_conn_set_state(conn, BS_OPENSENT);
584 bgp_start_timer(conn->hold_timer, conn->bgp->cf->initial_hold_time);
585 }
586
587 static void
588 bgp_connected(sock *sk)
589 {
590 struct bgp_conn *conn = sk->data;
591 struct bgp_proto *p = conn->bgp;
592
593 BGP_TRACE(D_EVENTS, "Connected");
594 bgp_send_open(conn);
595 }
596
597 static void
598 bgp_connect_timeout(timer *t)
599 {
600 struct bgp_conn *conn = t->data;
601 struct bgp_proto *p = conn->bgp;
602
603 DBG("BGP: connect_timeout\n");
604 if (p->p.proto_state == PS_START)
605 {
606 bgp_close_conn(conn);
607 bgp_connect(p);
608 }
609 else
610 bgp_conn_enter_idle_state(conn);
611 }
612
613 static void
614 bgp_sock_err(sock *sk, int err)
615 {
616 struct bgp_conn *conn = sk->data;
617 struct bgp_proto *p = conn->bgp;
618
619 /*
620 * This error hook may be called either asynchronously from main
621 * loop, or synchronously from sk_send(). But sk_send() is called
622 * only from bgp_tx() and bgp_kick_tx(), which are both called
623 * asynchronously from main loop. Moreover, they end if err hook is
624 * called. Therefore, we could suppose that it is always called
625 * asynchronously.
626 */
627
628 bgp_store_error(p, conn, BE_SOCKET, err);
629
630 if (err)
631 BGP_TRACE(D_EVENTS, "Connection lost (%M)", err);
632 else
633 BGP_TRACE(D_EVENTS, "Connection closed");
634
635 if ((conn->state == BS_ESTABLISHED) && p->gr_ready)
636 bgp_handle_graceful_restart(p);
637
638 bgp_conn_enter_idle_state(conn);
639 }
640
641 static void
642 bgp_hold_timeout(timer *t)
643 {
644 struct bgp_conn *conn = t->data;
645 struct bgp_proto *p = conn->bgp;
646
647 DBG("BGP: Hold timeout\n");
648
649 /* We are already closing the connection - just do hangup */
650 if (conn->state == BS_CLOSE)
651 {
652 BGP_TRACE(D_EVENTS, "Connection stalled");
653 bgp_conn_enter_idle_state(conn);
654 return;
655 }
656
657 /* If there is something in input queue, we are probably congested
658 and perhaps just not processed BGP packets in time. */
659
660 if (sk_rx_ready(conn->sk) > 0)
661 bgp_start_timer(conn->hold_timer, 10);
662 else
663 bgp_error(conn, 4, 0, NULL, 0);
664 }
665
666 static void
667 bgp_keepalive_timeout(timer *t)
668 {
669 struct bgp_conn *conn = t->data;
670
671 DBG("BGP: Keepalive timer\n");
672 bgp_schedule_packet(conn, PKT_KEEPALIVE);
673
674 /* Kick TX a bit faster */
675 if (ev_active(conn->tx_ev))
676 ev_run(conn->tx_ev);
677 }
678
679 static void
680 bgp_setup_conn(struct bgp_proto *p, struct bgp_conn *conn)
681 {
682 timer *t;
683
684 conn->sk = NULL;
685 conn->bgp = p;
686 conn->packets_to_send = 0;
687
688 t = conn->connect_retry_timer = tm_new(p->p.pool);
689 t->hook = bgp_connect_timeout;
690 t->data = conn;
691 t = conn->hold_timer = tm_new(p->p.pool);
692 t->hook = bgp_hold_timeout;
693 t->data = conn;
694 t = conn->keepalive_timer = tm_new(p->p.pool);
695 t->hook = bgp_keepalive_timeout;
696 t->data = conn;
697 conn->tx_ev = ev_new(p->p.pool);
698 conn->tx_ev->hook = bgp_kick_tx;
699 conn->tx_ev->data = conn;
700 }
701
702 static void
703 bgp_setup_sk(struct bgp_conn *conn, sock *s)
704 {
705 s->data = conn;
706 s->err_hook = bgp_sock_err;
707 s->fast_rx = 1;
708 conn->sk = s;
709 }
710
711 static void
712 bgp_active(struct bgp_proto *p)
713 {
714 int delay = MAX(1, p->cf->connect_delay_time);
715 struct bgp_conn *conn = &p->outgoing_conn;
716
717 BGP_TRACE(D_EVENTS, "Connect delayed by %d seconds", delay);
718 bgp_setup_conn(p, conn);
719 bgp_conn_set_state(conn, BS_ACTIVE);
720 bgp_start_timer(conn->connect_retry_timer, delay);
721 }
722
723 /**
724 * bgp_connect - initiate an outgoing connection
725 * @p: BGP instance
726 *
727 * The bgp_connect() function creates a new &bgp_conn and initiates
728 * a TCP connection to the peer. The rest of connection setup is governed
729 * by the BGP state machine as described in the standard.
730 */
731 static void
732 bgp_connect(struct bgp_proto *p) /* Enter Connect state and start establishing connection */
733 {
734 sock *s;
735 struct bgp_conn *conn = &p->outgoing_conn;
736 int hops = p->cf->multihop ? : 1;
737
738 DBG("BGP: Connecting\n");
739 s = sk_new(p->p.pool);
740 s->type = SK_TCP_ACTIVE;
741 s->saddr = p->source_addr;
742 s->daddr = p->cf->remote_ip;
743 s->dport = p->cf->remote_port;
744 s->iface = p->neigh ? p->neigh->iface : NULL;
745 s->ttl = p->cf->ttl_security ? 255 : hops;
746 s->rbsize = p->cf->enable_extended_messages ? BGP_RX_BUFFER_EXT_SIZE : BGP_RX_BUFFER_SIZE;
747 s->tbsize = p->cf->enable_extended_messages ? BGP_TX_BUFFER_EXT_SIZE : BGP_TX_BUFFER_SIZE;
748 s->tos = IP_PREC_INTERNET_CONTROL;
749 s->password = p->cf->password;
750 s->tx_hook = bgp_connected;
751 BGP_TRACE(D_EVENTS, "Connecting to %I%J from local address %I%J", s->daddr, p->cf->iface,
752 s->saddr, ipa_is_link_local(s->saddr) ? s->iface : NULL);
753 bgp_setup_conn(p, conn);
754 bgp_setup_sk(conn, s);
755 bgp_conn_set_state(conn, BS_CONNECT);
756
757 if (sk_open(s) < 0)
758 goto err;
759
760 /* Set minimal receive TTL if needed */
761 if (p->cf->ttl_security)
762 if (sk_set_min_ttl(s, 256 - hops) < 0)
763 goto err;
764
765 DBG("BGP: Waiting for connect success\n");
766 bgp_start_timer(conn->connect_retry_timer, p->cf->connect_retry_time);
767 return;
768
769 err:
770 sk_log_error(s, p->p.name);
771 bgp_sock_err(s, 0);
772 return;
773 }
774
775 /**
776 * bgp_find_proto - find existing proto for incoming connection
777 * @sk: TCP socket
778 *
779 */
780 static struct bgp_proto *
781 bgp_find_proto(sock *sk)
782 {
783 struct proto_config *pc;
784
785 WALK_LIST(pc, config->protos)
786 if ((pc->protocol == &proto_bgp) && pc->proto)
787 {
788 struct bgp_proto *p = (struct bgp_proto *) pc->proto;
789 if (ipa_equal(p->cf->remote_ip, sk->daddr) &&
790 (!ipa_is_link_local(sk->daddr) || (p->cf->iface == sk->iface)))
791 return p;
792 }
793
794 return NULL;
795 }
796
797 /**
798 * bgp_incoming_connection - handle an incoming connection
799 * @sk: TCP socket
800 * @dummy: unused
801 *
802 * This function serves as a socket hook for accepting of new BGP
803 * connections. It searches a BGP instance corresponding to the peer
804 * which has connected and if such an instance exists, it creates a
805 * &bgp_conn structure, attaches it to the instance and either sends
806 * an Open message or (if there already is an active connection) it
807 * closes the new connection by sending a Notification message.
808 */
809 static int
810 bgp_incoming_connection(sock *sk, uint dummy UNUSED)
811 {
812 struct bgp_proto *p;
813 int acc, hops;
814
815 DBG("BGP: Incoming connection from %I port %d\n", sk->daddr, sk->dport);
816 p = bgp_find_proto(sk);
817 if (!p)
818 {
819 log(L_WARN "BGP: Unexpected connect from unknown address %I%J (port %d)",
820 sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL, sk->dport);
821 rfree(sk);
822 return 0;
823 }
824
825 /*
826 * BIRD should keep multiple incoming connections in OpenSent state (for
827 * details RFC 4271 8.2.1 par 3), but it keeps just one. Duplicate incoming
828 * connections are rejected istead. The exception is the case where an
829 * incoming connection triggers a graceful restart.
830 */
831
832 acc = (p->p.proto_state == PS_START || p->p.proto_state == PS_UP) &&
833 (p->start_state >= BSS_CONNECT) && (!p->incoming_conn.sk);
834
835 if (p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready)
836 {
837 bgp_store_error(p, NULL, BE_MISC, BEM_GRACEFUL_RESTART);
838 bgp_handle_graceful_restart(p);
839 bgp_conn_enter_idle_state(p->conn);
840 acc = 1;
841
842 /* There might be separate incoming connection in OpenSent state */
843 if (p->incoming_conn.state > BS_ACTIVE)
844 bgp_close_conn(&p->incoming_conn);
845 }
846
847 BGP_TRACE(D_EVENTS, "Incoming connection from %I%J (port %d) %s",
848 sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL,
849 sk->dport, acc ? "accepted" : "rejected");
850
851 if (!acc)
852 {
853 rfree(sk);
854 return 0;
855 }
856
857 hops = p->cf->multihop ? : 1;
858
859 if (sk_set_ttl(sk, p->cf->ttl_security ? 255 : hops) < 0)
860 goto err;
861
862 if (p->cf->ttl_security)
863 if (sk_set_min_ttl(sk, 256 - hops) < 0)
864 goto err;
865
866 if (p->cf->enable_extended_messages)
867 {
868 sk->rbsize = BGP_RX_BUFFER_EXT_SIZE;
869 sk->tbsize = BGP_TX_BUFFER_EXT_SIZE;
870 sk_reallocate(sk);
871 }
872
873 bgp_setup_conn(p, &p->incoming_conn);
874 bgp_setup_sk(&p->incoming_conn, sk);
875 bgp_send_open(&p->incoming_conn);
876 return 0;
877
878 err:
879 sk_log_error(sk, p->p.name);
880 log(L_ERR "%s: Incoming connection aborted", p->p.name);
881 rfree(sk);
882 return 0;
883 }
884
885 static void
886 bgp_listen_sock_err(sock *sk UNUSED, int err)
887 {
888 if (err == ECONNABORTED)
889 log(L_WARN "BGP: Incoming connection aborted");
890 else
891 log(L_ERR "BGP: Error on listening socket: %M", err);
892 }
893
894 static sock *
895 bgp_setup_listen_sk(ip_addr addr, unsigned port, u32 flags)
896 {
897 sock *s = sk_new(&root_pool);
898 DBG("BGP: Creating listening socket\n");
899 s->type = SK_TCP_PASSIVE;
900 s->ttl = 255;
901 s->saddr = addr;
902 s->sport = port ? port : BGP_PORT;
903 s->flags = flags ? 0 : SKF_V6ONLY;
904 s->tos = IP_PREC_INTERNET_CONTROL;
905 s->rbsize = BGP_RX_BUFFER_SIZE;
906 s->tbsize = BGP_TX_BUFFER_SIZE;
907 s->rx_hook = bgp_incoming_connection;
908 s->err_hook = bgp_listen_sock_err;
909
910 if (sk_open(s) < 0)
911 goto err;
912
913 return s;
914
915 err:
916 sk_log_error(s, "BGP");
917 log(L_ERR "BGP: Cannot open listening socket");
918 rfree(s);
919 return NULL;
920 }
921
922 static void
923 bgp_start_neighbor(struct bgp_proto *p)
924 {
925 /* Called only for single-hop BGP sessions */
926
927 if (ipa_zero(p->source_addr))
928 p->source_addr = p->neigh->ifa->ip;
929
930 #ifdef IPV6
931 {
932 struct ifa *a;
933 p->local_link = IPA_NONE;
934 WALK_LIST(a, p->neigh->iface->addrs)
935 if (a->scope == SCOPE_LINK)
936 {
937 p->local_link = a->ip;
938 break;
939 }
940
941 if (! ipa_nonzero(p->local_link))
942 log(L_WARN "%s: Missing link local address on interface %s", p->p.name, p->neigh->iface->name);
943
944 DBG("BGP: Selected link-level address %I\n", p->local_link);
945 }
946 #endif
947
948 bgp_initiate(p);
949 }
950
951 static void
952 bgp_neigh_notify(neighbor *n)
953 {
954 struct bgp_proto *p = (struct bgp_proto *) n->proto;
955 int ps = p->p.proto_state;
956
957 if (n != p->neigh)
958 return;
959
960 if ((ps == PS_DOWN) || (ps == PS_STOP))
961 return;
962
963 int prepare = (ps == PS_START) && (p->start_state == BSS_PREPARE);
964
965 if (n->scope <= 0)
966 {
967 if (!prepare)
968 {
969 BGP_TRACE(D_EVENTS, "Neighbor lost");
970 bgp_store_error(p, NULL, BE_MISC, BEM_NEIGHBOR_LOST);
971 /* Perhaps also run bgp_update_startup_delay(p)? */
972 bgp_stop(p, 0);
973 }
974 }
975 else if (p->cf->check_link && !(n->iface->flags & IF_LINK_UP))
976 {
977 if (!prepare)
978 {
979 BGP_TRACE(D_EVENTS, "Link down");
980 bgp_store_error(p, NULL, BE_MISC, BEM_LINK_DOWN);
981 if (ps == PS_UP)
982 bgp_update_startup_delay(p);
983 bgp_stop(p, 0);
984 }
985 }
986 else
987 {
988 if (prepare)
989 {
990 BGP_TRACE(D_EVENTS, "Neighbor ready");
991 bgp_start_neighbor(p);
992 }
993 }
994 }
995
996 static void
997 bgp_bfd_notify(struct bfd_request *req)
998 {
999 struct bgp_proto *p = req->data;
1000 int ps = p->p.proto_state;
1001
1002 if (req->down && ((ps == PS_START) || (ps == PS_UP)))
1003 {
1004 BGP_TRACE(D_EVENTS, "BFD session down");
1005 bgp_store_error(p, NULL, BE_MISC, BEM_BFD_DOWN);
1006 if (ps == PS_UP)
1007 bgp_update_startup_delay(p);
1008 bgp_stop(p, 0);
1009 }
1010 }
1011
1012 static void
1013 bgp_update_bfd(struct bgp_proto *p, int use_bfd)
1014 {
1015 if (use_bfd && !p->bfd_req)
1016 p->bfd_req = bfd_request_session(p->p.pool, p->cf->remote_ip, p->source_addr,
1017 p->cf->multihop ? NULL : p->neigh->iface,
1018 bgp_bfd_notify, p);
1019
1020 if (!use_bfd && p->bfd_req)
1021 {
1022 rfree(p->bfd_req);
1023 p->bfd_req = NULL;
1024 }
1025 }
1026
1027 static int
1028 bgp_reload_routes(struct proto *P)
1029 {
1030 struct bgp_proto *p = (struct bgp_proto *) P;
1031 if (!p->conn || !p->conn->peer_refresh_support)
1032 return 0;
1033
1034 bgp_schedule_packet(p->conn, PKT_ROUTE_REFRESH);
1035 return 1;
1036 }
1037
1038 static void
1039 bgp_feed_begin(struct proto *P, int initial)
1040 {
1041 struct bgp_proto *p = (struct bgp_proto *) P;
1042
1043 /* This should not happen */
1044 if (!p->conn)
1045 return;
1046
1047 if (initial && p->cf->gr_mode)
1048 p->feed_state = BFS_LOADING;
1049
1050 /* It is refeed and both sides support enhanced route refresh */
1051 if (!initial && p->cf->enable_refresh &&
1052 p->conn->peer_enhanced_refresh_support)
1053 {
1054 /* BoRR must not be sent before End-of-RIB */
1055 if (p->feed_state == BFS_LOADING || p->feed_state == BFS_LOADED)
1056 return;
1057
1058 p->feed_state = BFS_REFRESHING;
1059 bgp_schedule_packet(p->conn, PKT_BEGIN_REFRESH);
1060 }
1061 }
1062
1063 static void
1064 bgp_feed_end(struct proto *P)
1065 {
1066 struct bgp_proto *p = (struct bgp_proto *) P;
1067
1068 /* This should not happen */
1069 if (!p->conn)
1070 return;
1071
1072 /* Non-demarcated feed ended, nothing to do */
1073 if (p->feed_state == BFS_NONE)
1074 return;
1075
1076 /* Schedule End-of-RIB packet */
1077 if (p->feed_state == BFS_LOADING)
1078 p->feed_state = BFS_LOADED;
1079
1080 /* Schedule EoRR packet */
1081 if (p->feed_state == BFS_REFRESHING)
1082 p->feed_state = BFS_REFRESHED;
1083
1084 /* Kick TX hook */
1085 bgp_schedule_packet(p->conn, PKT_UPDATE);
1086 }
1087
1088
1089 static void
1090 bgp_start_locked(struct object_lock *lock)
1091 {
1092 struct bgp_proto *p = lock->data;
1093 struct bgp_config *cf = p->cf;
1094
1095 if (p->p.proto_state != PS_START)
1096 {
1097 DBG("BGP: Got lock in different state %d\n", p->p.proto_state);
1098 return;
1099 }
1100
1101 DBG("BGP: Got lock\n");
1102
1103 if (cf->multihop)
1104 {
1105 /* Multi-hop sessions do not use neighbor entries */
1106 bgp_initiate(p);
1107 return;
1108 }
1109
1110 neighbor *n = neigh_find2(&p->p, &cf->remote_ip, cf->iface, NEF_STICKY);
1111 if (!n)
1112 {
1113 log(L_ERR "%s: Invalid remote address %I%J", p->p.name, cf->remote_ip, cf->iface);
1114 /* As we do not start yet, we can just disable protocol */
1115 p->p.disabled = 1;
1116 bgp_store_error(p, NULL, BE_MISC, BEM_INVALID_NEXT_HOP);
1117 proto_notify_state(&p->p, PS_DOWN);
1118 return;
1119 }
1120
1121 p->neigh = n;
1122
1123 if (n->scope <= 0)
1124 BGP_TRACE(D_EVENTS, "Waiting for %I%J to become my neighbor", cf->remote_ip, cf->iface);
1125 else if (p->cf->check_link && !(n->iface->flags & IF_LINK_UP))
1126 BGP_TRACE(D_EVENTS, "Waiting for link on %s", n->iface->name);
1127 else
1128 bgp_start_neighbor(p);
1129 }
1130
1131 static int
1132 bgp_start(struct proto *P)
1133 {
1134 struct bgp_proto *p = (struct bgp_proto *) P;
1135 struct object_lock *lock;
1136
1137 DBG("BGP: Startup.\n");
1138 p->start_state = BSS_PREPARE;
1139 p->outgoing_conn.state = BS_IDLE;
1140 p->incoming_conn.state = BS_IDLE;
1141 p->neigh = NULL;
1142 p->bfd_req = NULL;
1143 p->gr_ready = 0;
1144 p->gr_active = 0;
1145
1146 rt_lock_table(p->igp_table);
1147
1148 p->event = ev_new(p->p.pool);
1149 p->event->hook = bgp_decision;
1150 p->event->data = p;
1151
1152 p->startup_timer = tm_new(p->p.pool);
1153 p->startup_timer->hook = bgp_startup_timeout;
1154 p->startup_timer->data = p;
1155
1156 p->gr_timer = tm_new(p->p.pool);
1157 p->gr_timer->hook = bgp_graceful_restart_timeout;
1158 p->gr_timer->data = p;
1159
1160 p->local_id = proto_get_router_id(P->cf);
1161 if (p->rr_client)
1162 p->rr_cluster_id = p->cf->rr_cluster_id ? p->cf->rr_cluster_id : p->local_id;
1163
1164 p->remote_id = 0;
1165 p->source_addr = p->cf->source_addr;
1166
1167 if (p->p.gr_recovery && p->cf->gr_mode)
1168 proto_graceful_restart_lock(P);
1169
1170 /*
1171 * Before attempting to create the connection, we need to lock the
1172 * port, so that are sure we're the only instance attempting to talk
1173 * with that neighbor.
1174 */
1175
1176 lock = p->lock = olock_new(P->pool);
1177 lock->addr = p->cf->remote_ip;
1178 lock->port = p->cf->remote_port;
1179 lock->iface = p->cf->iface;
1180 lock->type = OBJLOCK_TCP;
1181 lock->hook = bgp_start_locked;
1182 lock->data = p;
1183 olock_acquire(lock);
1184
1185 return PS_START;
1186 }
1187
1188 extern int proto_restart;
1189
1190 static int
1191 bgp_shutdown(struct proto *P)
1192 {
1193 struct bgp_proto *p = (struct bgp_proto *) P;
1194 unsigned subcode = 0;
1195
1196 BGP_TRACE(D_EVENTS, "Shutdown requested");
1197
1198 switch (P->down_code)
1199 {
1200 case PDC_CF_REMOVE:
1201 case PDC_CF_DISABLE:
1202 subcode = 3; // Errcode 6, 3 - peer de-configured
1203 break;
1204
1205 case PDC_CF_RESTART:
1206 subcode = 6; // Errcode 6, 6 - other configuration change
1207 break;
1208
1209 case PDC_CMD_DISABLE:
1210 case PDC_CMD_SHUTDOWN:
1211 subcode = 2; // Errcode 6, 2 - administrative shutdown
1212 break;
1213
1214 case PDC_CMD_RESTART:
1215 subcode = 4; // Errcode 6, 4 - administrative reset
1216 break;
1217
1218 case PDC_RX_LIMIT_HIT:
1219 case PDC_IN_LIMIT_HIT:
1220 subcode = 1; // Errcode 6, 1 - max number of prefixes reached
1221 /* log message for compatibility */
1222 log(L_WARN "%s: Route limit exceeded, shutting down", p->p.name);
1223 goto limit;
1224
1225 case PDC_OUT_LIMIT_HIT:
1226 subcode = proto_restart ? 4 : 2; // Administrative reset or shutdown
1227
1228 limit:
1229 bgp_store_error(p, NULL, BE_AUTO_DOWN, BEA_ROUTE_LIMIT_EXCEEDED);
1230 if (proto_restart)
1231 bgp_update_startup_delay(p);
1232 else
1233 p->startup_delay = 0;
1234 goto done;
1235 }
1236
1237 bgp_store_error(p, NULL, BE_MAN_DOWN, 0);
1238 p->startup_delay = 0;
1239
1240 done:
1241 bgp_stop(p, subcode);
1242 return p->p.proto_state;
1243 }
1244
1245 static void
1246 bgp_cleanup(struct proto *P)
1247 {
1248 struct bgp_proto *p = (struct bgp_proto *) P;
1249 rt_unlock_table(p->igp_table);
1250 }
1251
1252 static rtable *
1253 get_igp_table(struct bgp_config *cf)
1254 {
1255 return cf->igp_table ? cf->igp_table->table : cf->c.table->table;
1256 }
1257
1258 static struct proto *
1259 bgp_init(struct proto_config *C)
1260 {
1261 struct proto *P = proto_new(C, sizeof(struct bgp_proto));
1262 struct bgp_config *c = (struct bgp_config *) C;
1263 struct bgp_proto *p = (struct bgp_proto *) P;
1264
1265 P->accept_ra_types = c->secondary ? RA_ACCEPTED : RA_OPTIMAL;
1266 P->rt_notify = bgp_rt_notify;
1267 P->import_control = bgp_import_control;
1268 P->neigh_notify = bgp_neigh_notify;
1269 P->reload_routes = bgp_reload_routes;
1270 P->feed_begin = bgp_feed_begin;
1271 P->feed_end = bgp_feed_end;
1272 P->rte_better = bgp_rte_better;
1273 P->rte_mergable = bgp_rte_mergable;
1274 P->rte_recalculate = c->deterministic_med ? bgp_rte_recalculate : NULL;
1275
1276 p->cf = c;
1277 p->local_as = c->local_as;
1278 p->remote_as = c->remote_as;
1279 p->is_internal = (c->local_as == c->remote_as);
1280 p->rs_client = c->rs_client;
1281 p->rr_client = c->rr_client;
1282 p->igp_table = get_igp_table(c);
1283
1284 return P;
1285 }
1286
1287
1288 void
1289 bgp_check_config(struct bgp_config *c)
1290 {
1291 int internal = (c->local_as == c->remote_as);
1292
1293 /* Do not check templates at all */
1294 if (c->c.class == SYM_TEMPLATE)
1295 return;
1296
1297
1298 /* EBGP direct by default, IBGP multihop by default */
1299 if (c->multihop < 0)
1300 c->multihop = internal ? 64 : 0;
1301
1302 /* Different default for gw_mode */
1303 if (!c->gw_mode)
1304 c->gw_mode = c->multihop ? GW_RECURSIVE : GW_DIRECT;
1305
1306 /* Different default based on rs_client */
1307 if (!c->missing_lladdr)
1308 c->missing_lladdr = c->rs_client ? MLL_IGNORE : MLL_SELF;
1309
1310 /* Disable after error incompatible with restart limit action */
1311 if (c->c.in_limit && (c->c.in_limit->action == PLA_RESTART) && c->disable_after_error)
1312 c->c.in_limit->action = PLA_DISABLE;
1313
1314
1315 if (!c->local_as)
1316 cf_error("Local AS number must be set");
1317
1318 if (ipa_zero(c->remote_ip))
1319 cf_error("Neighbor must be configured");
1320
1321 if (!c->remote_as)
1322 cf_error("Remote AS number must be set");
1323
1324 // if (ipa_is_link_local(c->remote_ip) && !c->iface)
1325 // cf_error("Link-local neighbor address requires specified interface");
1326
1327 if (!ipa_is_link_local(c->remote_ip) != !c->iface)
1328 cf_error("Link-local address and interface scope must be used together");
1329
1330 if (!(c->capabilities && c->enable_as4) && (c->remote_as > 0xFFFF))
1331 cf_error("Neighbor AS number out of range (AS4 not available)");
1332
1333 if (!internal && c->rr_client)
1334 cf_error("Only internal neighbor can be RR client");
1335
1336 if (internal && c->rs_client)
1337 cf_error("Only external neighbor can be RS client");
1338
1339 if (c->multihop && (c->gw_mode == GW_DIRECT))
1340 cf_error("Multihop BGP cannot use direct gateway mode");
1341
1342 if (c->multihop && (ipa_is_link_local(c->remote_ip) ||
1343 ipa_is_link_local(c->source_addr)))
1344 cf_error("Multihop BGP cannot be used with link-local addresses");
1345
1346 if (c->multihop && c->check_link)
1347 cf_error("Multihop BGP cannot depend on link state");
1348
1349 if (c->multihop && c->bfd && ipa_zero(c->source_addr))
1350 cf_error("Multihop BGP with BFD requires specified source address");
1351
1352 if ((c->gw_mode == GW_RECURSIVE) && c->c.table->sorted)
1353 cf_error("BGP in recursive mode prohibits sorted table");
1354
1355 if (c->deterministic_med && c->c.table->sorted)
1356 cf_error("BGP with deterministic MED prohibits sorted table");
1357
1358 if (c->secondary && !c->c.table->sorted)
1359 cf_error("BGP with secondary option requires sorted table");
1360 }
1361
1362 static int
1363 bgp_reconfigure(struct proto *P, struct proto_config *C)
1364 {
1365 struct bgp_config *new = (struct bgp_config *) C;
1366 struct bgp_proto *p = (struct bgp_proto *) P;
1367 struct bgp_config *old = p->cf;
1368
1369 if (proto_get_router_id(C) != p->local_id)
1370 return 0;
1371
1372 int same = !memcmp(((byte *) old) + sizeof(struct proto_config),
1373 ((byte *) new) + sizeof(struct proto_config),
1374 // password item is last and must be checked separately
1375 OFFSETOF(struct bgp_config, password) - sizeof(struct proto_config))
1376 && ((!old->password && !new->password)
1377 || (old->password && new->password && !strcmp(old->password, new->password)))
1378 && (get_igp_table(old) == get_igp_table(new));
1379
1380 if (same && (p->start_state > BSS_PREPARE))
1381 bgp_update_bfd(p, new->bfd);
1382
1383 /* We should update our copy of configuration ptr as old configuration will be freed */
1384 if (same)
1385 p->cf = new;
1386
1387 return same;
1388 }
1389
1390 static void
1391 bgp_copy_config(struct proto_config *dest, struct proto_config *src)
1392 {
1393 /* Just a shallow copy */
1394 proto_copy_rest(dest, src, sizeof(struct bgp_config));
1395 }
1396
1397
1398 /**
1399 * bgp_error - report a protocol error
1400 * @c: connection
1401 * @code: error code (according to the RFC)
1402 * @subcode: error sub-code
1403 * @data: data to be passed in the Notification message
1404 * @len: length of the data
1405 *
1406 * bgp_error() sends a notification packet to tell the other side that a protocol
1407 * error has occurred (including the data considered erroneous if possible) and
1408 * closes the connection.
1409 */
1410 void
1411 bgp_error(struct bgp_conn *c, unsigned code, unsigned subcode, byte *data, int len)
1412 {
1413 struct bgp_proto *p = c->bgp;
1414
1415 if (c->state == BS_CLOSE)
1416 return;
1417
1418 bgp_log_error(p, BE_BGP_TX, "Error", code, subcode, data, (len > 0) ? len : -len);
1419 bgp_store_error(p, c, BE_BGP_TX, (code << 16) | subcode);
1420 bgp_conn_enter_close_state(c);
1421
1422 c->notify_code = code;
1423 c->notify_subcode = subcode;
1424 c->notify_data = data;
1425 c->notify_size = (len > 0) ? len : 0;
1426 bgp_schedule_packet(c, PKT_NOTIFICATION);
1427
1428 if (code != 6)
1429 {
1430 bgp_update_startup_delay(p);
1431 bgp_stop(p, 0);
1432 }
1433 }
1434
1435 /**
1436 * bgp_store_error - store last error for status report
1437 * @p: BGP instance
1438 * @c: connection
1439 * @class: error class (BE_xxx constants)
1440 * @code: error code (class specific)
1441 *
1442 * bgp_store_error() decides whether given error is interesting enough
1443 * and store that error to last_error variables of @p
1444 */
1445 void
1446 bgp_store_error(struct bgp_proto *p, struct bgp_conn *c, u8 class, u32 code)
1447 {
1448 /* During PS_UP, we ignore errors on secondary connection */
1449 if ((p->p.proto_state == PS_UP) && c && (c != p->conn))
1450 return;
1451
1452 /* During PS_STOP, we ignore any errors, as we want to report
1453 * the error that caused transition to PS_STOP
1454 */
1455 if (p->p.proto_state == PS_STOP)
1456 return;
1457
1458 p->last_error_class = class;
1459 p->last_error_code = code;
1460 }
1461
1462 static char *bgp_state_names[] = { "Idle", "Connect", "Active", "OpenSent", "OpenConfirm", "Established", "Close" };
1463 static char *bgp_err_classes[] = { "", "Error: ", "Socket: ", "Received: ", "BGP Error: ", "Automatic shutdown: ", ""};
1464 static char *bgp_misc_errors[] = { "", "Neighbor lost", "Invalid next hop", "Kernel MD5 auth failed", "No listening socket", "Link down", "BFD session down", "Graceful restart"};
1465 static char *bgp_auto_errors[] = { "", "Route limit exceeded"};
1466
1467 static const char *
1468 bgp_last_errmsg(struct bgp_proto *p)
1469 {
1470 switch (p->last_error_class)
1471 {
1472 case BE_MISC:
1473 return bgp_misc_errors[p->last_error_code];
1474 case BE_SOCKET:
1475 return (p->last_error_code == 0) ? "Connection closed" : strerror(p->last_error_code);
1476 case BE_BGP_RX:
1477 case BE_BGP_TX:
1478 return bgp_error_dsc(p->last_error_code >> 16, p->last_error_code & 0xFF);
1479 case BE_AUTO_DOWN:
1480 return bgp_auto_errors[p->last_error_code];
1481 default:
1482 return "";
1483 }
1484 }
1485
1486 static const char *
1487 bgp_state_dsc(struct bgp_proto *p)
1488 {
1489 if (p->p.proto_state == PS_DOWN)
1490 return "Down";
1491
1492 int state = MAX(p->incoming_conn.state, p->outgoing_conn.state);
1493 if ((state == BS_IDLE) && (p->start_state >= BSS_CONNECT) && p->cf->passive)
1494 return "Passive";
1495
1496 return bgp_state_names[state];
1497 }
1498
1499 static void
1500 bgp_get_status(struct proto *P, byte *buf)
1501 {
1502 struct bgp_proto *p = (struct bgp_proto *) P;
1503
1504 const char *err1 = bgp_err_classes[p->last_error_class];
1505 const char *err2 = bgp_last_errmsg(p);
1506
1507 if (P->proto_state == PS_DOWN)
1508 bsprintf(buf, "%s%s", err1, err2);
1509 else
1510 bsprintf(buf, "%-14s%s%s", bgp_state_dsc(p), err1, err2);
1511 }
1512
1513 static void
1514 bgp_show_proto_info(struct proto *P)
1515 {
1516 struct bgp_proto *p = (struct bgp_proto *) P;
1517 struct bgp_conn *c = p->conn;
1518
1519 proto_show_basic_info(P);
1520
1521 cli_msg(-1006, " BGP state: %s", bgp_state_dsc(p));
1522 cli_msg(-1006, " Neighbor address: %I%J", p->cf->remote_ip, p->cf->iface);
1523 cli_msg(-1006, " Neighbor AS: %u", p->remote_as);
1524
1525 if (p->gr_active)
1526 cli_msg(-1006, " Neighbor graceful restart active");
1527
1528 if (P->proto_state == PS_START)
1529 {
1530 struct bgp_conn *oc = &p->outgoing_conn;
1531
1532 if ((p->start_state < BSS_CONNECT) &&
1533 (p->startup_timer->expires))
1534 cli_msg(-1006, " Error wait: %d/%d",
1535 p->startup_timer->expires - now, p->startup_delay);
1536
1537 if ((oc->state == BS_ACTIVE) &&
1538 (oc->connect_retry_timer->expires))
1539 cli_msg(-1006, " Connect delay: %d/%d",
1540 oc->connect_retry_timer->expires - now, p->cf->connect_delay_time);
1541
1542 if (p->gr_active && p->gr_timer->expires)
1543 cli_msg(-1006, " Restart timer: %d/-", p->gr_timer->expires - now);
1544 }
1545 else if (P->proto_state == PS_UP)
1546 {
1547 cli_msg(-1006, " Neighbor ID: %R", p->remote_id);
1548 cli_msg(-1006, " Neighbor caps: %s%s%s%s%s%s%s",
1549 c->peer_refresh_support ? " refresh" : "",
1550 c->peer_enhanced_refresh_support ? " enhanced-refresh" : "",
1551 c->peer_gr_able ? " restart-able" : (c->peer_gr_aware ? " restart-aware" : ""),
1552 c->peer_as4_support ? " AS4" : "",
1553 (c->peer_add_path & ADD_PATH_RX) ? " add-path-rx" : "",
1554 (c->peer_add_path & ADD_PATH_TX) ? " add-path-tx" : "",
1555 c->peer_ext_messages_support ? " ext-messages" : "");
1556 cli_msg(-1006, " Session: %s%s%s%s%s%s%s%s",
1557 p->is_internal ? "internal" : "external",
1558 p->cf->multihop ? " multihop" : "",
1559 p->rr_client ? " route-reflector" : "",
1560 p->rs_client ? " route-server" : "",
1561 p->as4_session ? " AS4" : "",
1562 p->add_path_rx ? " add-path-rx" : "",
1563 p->add_path_tx ? " add-path-tx" : "",
1564 p->ext_messages ? " ext-messages" : "");
1565 cli_msg(-1006, " Source address: %I", p->source_addr);
1566 if (P->cf->in_limit)
1567 cli_msg(-1006, " Route limit: %d/%d",
1568 p->p.stats.imp_routes + p->p.stats.filt_routes, P->cf->in_limit->limit);
1569 cli_msg(-1006, " Hold timer: %d/%d",
1570 tm_remains(c->hold_timer), c->hold_time);
1571 cli_msg(-1006, " Keepalive timer: %d/%d",
1572 tm_remains(c->keepalive_timer), c->keepalive_time);
1573 }
1574
1575 if ((p->last_error_class != BE_NONE) &&
1576 (p->last_error_class != BE_MAN_DOWN))
1577 {
1578 const char *err1 = bgp_err_classes[p->last_error_class];
1579 const char *err2 = bgp_last_errmsg(p);
1580 cli_msg(-1006, " Last error: %s%s", err1, err2);
1581 }
1582 }
1583
1584 struct protocol proto_bgp = {
1585 .name = "BGP",
1586 .template = "bgp%d",
1587 .attr_class = EAP_BGP,
1588 .preference = DEF_PREF_BGP,
1589 .config_size = sizeof(struct bgp_config),
1590 .init = bgp_init,
1591 .start = bgp_start,
1592 .shutdown = bgp_shutdown,
1593 .cleanup = bgp_cleanup,
1594 .reconfigure = bgp_reconfigure,
1595 .copy_config = bgp_copy_config,
1596 .get_status = bgp_get_status,
1597 .get_attr = bgp_get_attr,
1598 .get_route_info = bgp_get_route_info,
1599 .show_proto_info = bgp_show_proto_info
1600 };