Statistics
| Branch: | Revision:

iof-bird-daemon / proto / bgp / bgp.c @ c8236a50

History | View | Annotate | Download (72.7 KB)

1
/*
2
 *        BIRD -- The Border Gateway Protocol
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
/**
12
 * DOC: Border Gateway Protocol
13
 *
14
 * The BGP protocol is implemented in three parts: |bgp.c| which takes care of
15
 * the connection and most of the interface with BIRD core, |packets.c| handling
16
 * both incoming and outgoing BGP packets and |attrs.c| containing functions for
17
 * manipulation with BGP attribute lists.
18
 *
19
 * As opposed to the other existing routing daemons, BIRD has a sophisticated
20
 * core architecture which is able to keep all the information needed by BGP in
21
 * the primary routing table, therefore no complex data structures like a
22
 * central BGP table are needed. This increases memory footprint of a BGP router
23
 * with many connections, but not too much and, which is more important, it
24
 * makes BGP much easier to implement.
25
 *
26
 * Each instance of BGP (corresponding to a single BGP peer) is described by a
27
 * &bgp_proto structure to which are attached individual connections represented
28
 * by &bgp_connection (usually, there exists only one connection, but during BGP
29
 * session setup, there can be more of them). The connections are handled
30
 * according to the BGP state machine defined in the RFC with all the timers and
31
 * all the parameters configurable.
32
 *
33
 * In incoming direction, we listen on the connection's socket and each time we
34
 * receive some input, we pass it to bgp_rx(). It decodes packet headers and the
35
 * markers and passes complete packets to bgp_rx_packet() which distributes the
36
 * packet according to its type.
37
 *
38
 * In outgoing direction, we gather all the routing updates and sort them to
39
 * buckets (&bgp_bucket) according to their attributes (we keep a hash table for
40
 * fast comparison of &rta's and a &fib which helps us to find if we already
41
 * have another route for the same destination queued for sending, so that we
42
 * can replace it with the new one immediately instead of sending both
43
 * updates). There also exists a special bucket holding all the route
44
 * withdrawals which cannot be queued anywhere else as they don't have any
45
 * attributes. If we have any packet to send (due to either new routes or the
46
 * connection tracking code wanting to send a Open, Keepalive or Notification
47
 * message), we call bgp_schedule_packet() which sets the corresponding bit in a
48
 * @packet_to_send bit field in &bgp_conn and as soon as the transmit socket
49
 * buffer becomes empty, we call bgp_fire_tx(). It inspects state of all the
50
 * packet type bits and calls the corresponding bgp_create_xx() functions,
51
 * eventually rescheduling the same packet type if we have more data of the same
52
 * type to send.
53
 *
54
 * The processing of attributes consists of two functions: bgp_decode_attrs()
55
 * for checking of the attribute blocks and translating them to the language of
56
 * BIRD's extended attributes and bgp_encode_attrs() which does the
57
 * converse. Both functions are built around a @bgp_attr_table array describing
58
 * all important characteristics of all known attributes.  Unknown transitive
59
 * attributes are attached to the route as %EAF_TYPE_OPAQUE byte streams.
60
 *
61
 * BGP protocol implements graceful restart in both restarting (local restart)
62
 * and receiving (neighbor restart) roles. The first is handled mostly by the
63
 * graceful restart code in the nest, BGP protocol just handles capabilities,
64
 * sets @gr_wait and locks graceful restart until end-of-RIB mark is received.
65
 * The second is implemented by internal restart of the BGP state to %BS_IDLE
66
 * and protocol state to %PS_START, but keeping the protocol up from the core
67
 * point of view and therefore maintaining received routes. Routing table
68
 * refresh cycle (rt_refresh_begin(), rt_refresh_end()) is used for removing
69
 * stale routes after reestablishment of BGP session during graceful restart.
70
 *
71
 * Supported standards:
72
 * <itemize>
73
 * <item> <rfc id="4271"> - Border Gateway Protocol 4 (BGP)
74
 * <item> <rfc id="1997"> - BGP Communities Attribute
75
 * <item> <rfc id="2385"> - Protection of BGP Sessions via TCP MD5 Signature
76
 * <item> <rfc id="2545"> - Use of BGP Multiprotocol Extensions for IPv6
77
 * <item> <rfc id="2918"> - Route Refresh Capability
78
 * <item> <rfc id="3107"> - Carrying Label Information in BGP
79
 * <item> <rfc id="4360"> - BGP Extended Communities Attribute
80
 * <item> <rfc id="4364"> - BGP/MPLS IPv4 Virtual Private Networks
81
 * <item> <rfc id="4456"> - BGP Route Reflection
82
 * <item> <rfc id="4486"> - Subcodes for BGP Cease Notification Message
83
 * <item> <rfc id="4659"> - BGP/MPLS IPv6 Virtual Private Networks
84
 * <item> <rfc id="4724"> - Graceful Restart Mechanism for BGP
85
 * <item> <rfc id="4760"> - Multiprotocol extensions for BGP
86
 * <item> <rfc id="4798"> - Connecting IPv6 Islands over IPv4 MPLS
87
 * <item> <rfc id="5065"> - AS confederations for BGP
88
 * <item> <rfc id="5082"> - Generalized TTL Security Mechanism
89
 * <item> <rfc id="5492"> - Capabilities Advertisement with BGP
90
 * <item> <rfc id="5549"> - Advertising IPv4 NLRI with an IPv6 Next Hop
91
 * <item> <rfc id="5575"> - Dissemination of Flow Specification Rules
92
 * <item> <rfc id="5668"> - 4-Octet AS Specific BGP Extended Community
93
 * <item> <rfc id="6286"> - AS-Wide Unique BGP Identifier
94
 * <item> <rfc id="6608"> - Subcodes for BGP Finite State Machine Error
95
 * <item> <rfc id="6793"> - BGP Support for 4-Octet AS Numbers
96
 * <item> <rfc id="7313"> - Enhanced Route Refresh Capability for BGP
97
 * <item> <rfc id="7606"> - Revised Error Handling for BGP UPDATE Messages
98
 * <item> <rfc id="7911"> - Advertisement of Multiple Paths in BGP
99
 * <item> <rfc id="7947"> - Internet Exchange BGP Route Server
100
 * <item> <rfc id="8092"> - BGP Large Communities Attribute
101
 * <item> <rfc id="8203"> - BGP Administrative Shutdown Communication
102
 * <item> <rfc id="8212"> - Default EBGP Route Propagation Behavior without Policies
103
 * </itemize>
104
*/
105

    
106
#undef LOCAL_DEBUG
107

    
108
#include <stdlib.h>
109
#include <time.h>
110

    
111
#include "nest/bird.h"
112
#include "nest/iface.h"
113
#include "nest/protocol.h"
114
#include "nest/route.h"
115
#include "nest/cli.h"
116
#include "nest/locks.h"
117
#include "conf/conf.h"
118
#include "filter/filter.h"
119
#include "lib/socket.h"
120
#include "lib/resource.h"
121
#include "lib/string.h"
122

    
123
#include "bgp.h"
124

    
125
struct linpool *bgp_linpool;                /* Global temporary pool */
126
struct linpool *bgp_linpool2;                /* Global temporary pool for bgp_rt_notify() */
127
static list bgp_sockets;                /* Global list of listening sockets */
128

    
129

    
130
static void bgp_connect(struct bgp_proto *p);
131
static void bgp_active(struct bgp_proto *p);
132
static void bgp_update_bfd(struct bgp_proto *p, int use_bfd);
133

    
134
static int bgp_incoming_connection(sock *sk, uint dummy UNUSED);
135
static void bgp_listen_sock_err(sock *sk UNUSED, int err);
136

    
137
/**
138
 * bgp_open - open a BGP instance
139
 * @p: BGP instance
140
 *
141
 * This function allocates and configures shared BGP resources, mainly listening
142
 * sockets. Should be called as the last step during initialization (when lock
143
 * is acquired and neighbor is ready). When error, caller should change state to
144
 * PS_DOWN and return immediately.
145
 */
146
static int
147
bgp_open(struct bgp_proto *p)
148
{
149
    struct bgp_socket *bs = NULL;
150
    struct iface *ifa = p->cf->strict_bind ? p->cf->iface : NULL;
151
    ip_addr addr = p->cf->strict_bind ? p->cf->local_ip :
152
                   (ipa_is_ip4(p->cf->remote_ip) ? IPA_NONE4 : IPA_NONE6);
153
    uint port = p->cf->local_port;
154

    
155
    /* FIXME: Add some global init? */
156
    if (!bgp_linpool)
157
        init_list(&bgp_sockets);
158

    
159
    /* We assume that cf->iface is defined iff cf->local_ip is link-local */
160

    
161
    WALK_LIST(bs, bgp_sockets)
162
    if (ipa_equal(bs->sk->saddr, addr) && (bs->sk->iface == ifa) && (bs->sk->sport == port))
163
    {
164
        bs->uc++;
165
        p->sock = bs;
166
        return 0;
167
    }
168

    
169
    sock *sk = sk_new(proto_pool);
170
    sk->type = SK_TCP_PASSIVE;
171
    sk->ttl = 255;
172
    sk->saddr = addr;
173
    sk->sport = port;
174
    sk->flags = 0;
175
    sk->tos = IP_PREC_INTERNET_CONTROL;
176
    sk->rbsize = BGP_RX_BUFFER_SIZE;
177
    sk->tbsize = BGP_TX_BUFFER_SIZE;
178
    sk->rx_hook = bgp_incoming_connection;
179
    sk->err_hook = bgp_listen_sock_err;
180

    
181
    if (sk_open(sk) < 0)
182
        goto err;
183

    
184
    bs = mb_allocz(proto_pool, sizeof(struct bgp_socket));
185
    bs->sk = sk;
186
    bs->uc = 1;
187
    p->sock = bs;
188

    
189
    add_tail(&bgp_sockets, &bs->n);
190

    
191
    if (!bgp_linpool)
192
    {
193
        bgp_linpool  = lp_new_default(proto_pool);
194
        bgp_linpool2 = lp_new_default(proto_pool);
195
    }
196

    
197
    return 0;
198

    
199
    err:
200
    sk_log_error(sk, p->p.name);
201
    log(L_ERR "%s: Cannot open listening socket", p->p.name);
202
    rfree(sk);
203
    return -1;
204
}
205

    
206
/**
207
 * bgp_close - close a BGP instance
208
 * @p: BGP instance
209
 *
210
 * This function frees and deconfigures shared BGP resources.
211
 */
212
static void
213
bgp_close(struct bgp_proto *p)
214
{
215
    struct bgp_socket *bs = p->sock;
216

    
217
    ASSERT(bs && bs->uc);
218

    
219
    if (--bs->uc)
220
        return;
221

    
222
    rfree(bs->sk);
223
    rem_node(&bs->n);
224
    mb_free(bs);
225

    
226
    if (!EMPTY_LIST(bgp_sockets))
227
        return;
228

    
229
    rfree(bgp_linpool);
230
    bgp_linpool = NULL;
231

    
232
    rfree(bgp_linpool2);
233
    bgp_linpool2 = NULL;
234
}
235

    
236
static inline int
237
bgp_setup_auth(struct bgp_proto *p, int enable)
238
{
239
    if (p->cf->password)
240
    {
241
        int rv = sk_set_md5_auth(p->sock->sk,
242
                                 p->cf->local_ip, p->cf->remote_ip, p->cf->iface,
243
                                 enable ? p->cf->password : NULL, p->cf->setkey);
244

    
245
        if (rv < 0)
246
            sk_log_error(p->sock->sk, p->p.name);
247

    
248
        return rv;
249
    }
250
    else
251
        return 0;
252
}
253

    
254
static inline struct bgp_channel *
255
bgp_find_channel(struct bgp_proto *p, u32 afi)
256
{
257
    struct bgp_channel *c;
258
    WALK_LIST(c, p->p.channels)
259
    if (c->afi == afi)
260
        return c;
261

    
262
    return NULL;
263
}
264

    
265
static void
266
bgp_startup(struct bgp_proto *p)
267
{
268
    //sameMetricUpdater = 3;
269
    BGP_TRACE(D_EVENTS, "Started");
270
    p->start_state = BSS_CONNECT;
271

    
272
    if (!p->cf->passive)
273
        bgp_active(p);
274

    
275
    //initRTmap();
276
    //loadComplessivo = 0;
277
    sent_prefix_slab = NULL;
278
}
279

    
280
static void
281
bgp_startup_timeout(timer *t)
282
{
283
    bgp_startup(t->data);
284
}
285

    
286
static inline struct bgp_channel *
287
bgp_get_channel_to_send(struct bgp_proto *p, struct bgp_conn *conn)
288
{
289
    uint i = conn->last_channel;
290

    
291
    /* Try the last channel, but at most several times */
292
    if ((conn->channels_to_send & (1 << i)) &&
293
        (conn->last_channel_count < 16))
294
        goto found;
295

    
296
    /* Find channel with non-zero channels_to_send */
297
    do
298
    {
299
        i++;
300
        if (i >= p->channel_count)
301
            i = 0;
302
    }
303
    while (! (conn->channels_to_send & (1 << i)));
304

    
305
    /* Use that channel */
306
    conn->last_channel = i;
307
    conn->last_channel_count = 0;
308

    
309
    found:
310
    conn->last_channel_count++;
311
    return p->channel_map[i];
312
}
313

    
314
void
315
conn_mrai_timeout(timer *t)
316
{
317
    //How to extract data from the timer
318
    struct bgp_conn *conn = t->data;
319
    struct bgp_proto *p = conn->bgp;
320

    
321
    BGP_TRACE(D_EVENTS, "MRAI timeout");
322
    bgp_fire_tx(conn);
323
}
324

    
325
void
326
dest_mrai_timeout(timer *t)
327
{
328
    list *connections = t->data;
329
    /* If there is something into the list i will trigger an update on the first connection FCFS*/
330
    if (list_length(connections) > 0) {
331
        struct conn_list_node *head = HEAD(*connections);
332
        struct bgp_conn *conn = head->conn;
333
        struct bgp_proto *p = conn->bgp;
334
        BGP_TRACE(D_EVENTS, "MRAI timeout");
335

    
336
        bgp_fire_tx(conn);
337
        bgp_free_conn_from_prefix(head);
338
    }
339
}
340

    
341
static void
342
bgp_initiate(struct bgp_proto *p)
343
{
344
    int err_val;
345

    
346
    if (bgp_open(p) < 0)
347
    { err_val = BEM_NO_SOCKET; goto err1; }
348

    
349
    if (bgp_setup_auth(p, 1) < 0)
350
    { err_val = BEM_INVALID_MD5; goto err2; }
351

    
352
    if (p->cf->bfd)
353
        bgp_update_bfd(p, p->cf->bfd);
354

    
355

    
356

    
357
    if (p->startup_delay)
358
    {
359
        p->start_state = BSS_DELAY;
360
        BGP_TRACE(D_EVENTS, "Startup delayed by %d seconds due to errors", p->startup_delay);
361
        bgp_start_timer(p->startup_timer, p->startup_delay);
362
    }
363
    else
364
        bgp_startup(p);
365

    
366
    return;
367

    
368
    err2:
369
    bgp_close(p);
370
    err1:
371
    p->p.disabled = 1;
372
    bgp_store_error(p, NULL, BE_MISC, err_val);
373
    proto_notify_state(&p->p, PS_DOWN);
374

    
375
    return;
376
}
377

    
378
/**
379
 * bgp_start_timer - start a BGP timer
380
 * @t: timer
381
 * @value: time (in seconds) to fire (0 to disable the timer)
382
 *
383
 * This functions calls tm_start() on @t with time @value and the amount of
384
 * randomization suggested by the BGP standard. Please use it for all BGP
385
 * timers.
386
 */
387
void
388
bgp_start_timer(timer *t, uint value)
389
{
390
    if (value)
391
    {
392
        /* The randomization procedure is specified in RFC 4271 section 10 */
393
        btime time = value S;
394
        btime randomize = random() % ((time / 4) + 1);
395
        tm_start(t, time - randomize);
396
    }
397
    else
398
        tm_stop(t);
399
}
400

    
401
void
402
bgp_start_ms_timer(timer *t, uint value, uint jitter)
403
{
404
    if (value)
405
    {
406
        /* The randomization procedure is specified in RFC 4271 section 10 */
407
        btime time = value MS;
408
        if(jitter > 100){
409
            jitter = 25;
410
        } else if(jitter == 0) {
411
            jitter = 1;
412
        }
413
        int divisor = 100 / jitter;
414
        log(L_INFO "divisor: %d", divisor);
415
        btime randomize = random() % ((time / divisor) + 1);
416
        log(L_INFO "Timer avviato con un delay di %d ms", time - randomize);
417
        tm_start(t, time - randomize);
418
    }
419
    else
420
        tm_stop(t);
421
}
422

    
423
/**
424
 * bgp_close_conn - close a BGP connection
425
 * @conn: connection to close
426
 *
427
 * This function takes a connection described by the &bgp_conn structure, closes
428
 * its socket and frees all resources associated with it.
429
 */
430
void
431
bgp_close_conn(struct bgp_conn *conn)
432
{
433
    DBG("BGP: Closing connection\n");
434

    
435
    //log(L_INFO "AS del vicino con cui si vuole chiudere la connessione: %d",conn->bgp->remote_as);
436
    const char *keyRTmap;
437
    map_iter_t iterRTmap;
438
    const char *keyNHmap_RTmap;
439
    map_iter_t iterNHmap_RTmap;
440

    
441
    //NH removing from the data structure
442
    /*iterRTmap = map_iter(&RTmap);
443
    while ((keyRTmap = map_next(&RTmap, &iterRTmap))) {
444
        RTable *RTmap_element = map_get(&RTmap, keyRTmap);
445
        iterNHmap_RTmap = map_iter(&RTmap_element->NH);
446
        while ((keyNHmap_RTmap = map_next(&RTmap_element->NH, &iterNHmap_RTmap))) {
447
            int *NH_AS_value = map_get(&RTmap_element->NH, keyNHmap_RTmap);
448
            if(NH_AS_value != NULL) {
449
                if (*NH_AS_value == conn->bgp->remote_as)
450
                    map_remove(&RTmap, keyRTmap);
451
            }
452
        }
453

454
        //Load removing from the data structure
455
        const char *keyLoadInmap_RTmap;
456
        map_iter_t iterLoadInmap_RTmap = map_iter(&RTmap_element->loadin);
457
        while ((keyLoadInmap_RTmap = map_next(&RTmap_element->loadin, &iterLoadInmap_RTmap))) {
458
            int keyValue = (int) strtol(keyLoadInmap_RTmap, (char **)NULL, 16);
459

460
            if(keyValue == conn->bgp->remote_as)
461
                map_remove(&RTmap_element->loadin, keyLoadInmap_RTmap);
462
        }
463
    }*/
464

    
465
    conn->packets_to_send = 0;
466
    conn->channels_to_send = 0;
467
    rfree(conn->connect_timer);
468
    conn->connect_timer = NULL;
469
    rfree(conn->keepalive_timer);
470
    conn->keepalive_timer = NULL;
471
    rfree(conn->hold_timer);
472
    conn->hold_timer = NULL;
473

    
474
    /* My MRAI timer */
475
    rfree(conn->conn_mrai_timer);
476
    conn->conn_mrai_timer = NULL;
477

    
478
    rfree(conn->tx_ev);
479
    conn->tx_ev = NULL;
480
    rfree(conn->sk);
481
    conn->sk = NULL;
482

    
483
    mb_free(conn->local_caps);
484
    conn->local_caps = NULL;
485
    mb_free(conn->remote_caps);
486
    conn->remote_caps = NULL;
487
}
488

    
489
/**
490
 * bgp_update_startup_delay - update a startup delay
491
 * @p: BGP instance
492
 *
493
 * This function updates a startup delay that is used to postpone next BGP
494
 * connect. It also handles disable_after_error and might stop BGP instance
495
 * when error happened and disable_after_error is on.
496
 *
497
 * It should be called when BGP protocol error happened.
498
 */
499
void
500
bgp_update_startup_delay(struct bgp_proto *p)
501
{
502
    struct bgp_config *cf = p->cf;
503

    
504
    DBG("BGP: Updating startup delay\n");
505

    
506
    if (p->last_proto_error && ((current_time() - p->last_proto_error) >= cf->error_amnesia_time S))
507
    p->startup_delay = 0;
508

    
509
    p->last_proto_error = current_time();
510

    
511
    if (cf->disable_after_error)
512
    {
513
        p->startup_delay = 0;
514
        p->p.disabled = 1;
515
        return;
516
    }
517

    
518
    if (!p->startup_delay)
519
        p->startup_delay = cf->error_delay_time_min;
520
    else
521
        p->startup_delay = MIN(2 * p->startup_delay, cf->error_delay_time_max);
522
}
523

    
524
static void
525
bgp_graceful_close_conn(struct bgp_conn *conn, uint subcode, byte *data, uint len)
526
{
527
    switch (conn->state)
528
    {
529
        case BS_IDLE:
530
        case BS_CLOSE:
531
            return;
532

    
533
        case BS_CONNECT:
534
        case BS_ACTIVE:
535
            bgp_conn_enter_idle_state(conn);
536
            return;
537

    
538
        case BS_OPENSENT:
539
        case BS_OPENCONFIRM:
540
        case BS_ESTABLISHED:
541
            bgp_error(conn, 6, subcode, data, len);
542
            return;
543

    
544
        default:
545
            bug("bgp_graceful_close_conn: Unknown state %d", conn->state);
546
    }
547
}
548

    
549
static void
550
bgp_down(struct bgp_proto *p)
551
{
552
    if (p->start_state > BSS_PREPARE)
553
    {
554
        bgp_setup_auth(p, 0);
555
        bgp_close(p);
556
    }
557

    
558
    BGP_TRACE(D_EVENTS, "Down");
559
    proto_notify_state(&p->p, PS_DOWN);
560
}
561

    
562
static void
563
bgp_decision(void *vp)
564
{
565
    struct bgp_proto *p = vp;
566

    
567
    DBG("BGP: Decision start\n");
568
    if ((p->p.proto_state == PS_START) &&
569
        (p->outgoing_conn.state == BS_IDLE) &&
570
        (p->incoming_conn.state != BS_OPENCONFIRM) &&
571
        !p->cf->passive)
572
        bgp_active(p);
573

    
574
    if ((p->p.proto_state == PS_STOP) &&
575
        (p->outgoing_conn.state == BS_IDLE) &&
576
        (p->incoming_conn.state == BS_IDLE))
577
        bgp_down(p);
578
}
579

    
580
void
581
bgp_stop(struct bgp_proto *p, uint subcode, byte *data, uint len)
582
{
583
    proto_notify_state(&p->p, PS_STOP);
584
    bgp_graceful_close_conn(&p->outgoing_conn, subcode, data, len);
585
    bgp_graceful_close_conn(&p->incoming_conn, subcode, data, len);
586
    ev_schedule(p->event);
587
}
588

    
589
static inline void
590
bgp_conn_set_state(struct bgp_conn *conn, uint new_state)
591
{
592
    if (conn->bgp->p.mrtdump & MD_STATES)
593
        mrt_dump_bgp_state_change(conn, conn->state, new_state);
594

    
595
    conn->state = new_state;
596
}
597

    
598
void
599
bgp_conn_enter_openconfirm_state(struct bgp_conn *conn)
600
{
601
    /* Really, most of the work is done in bgp_rx_open(). */
602
    bgp_conn_set_state(conn, BS_OPENCONFIRM);
603
}
604

    
605
static const struct bgp_af_caps dummy_af_caps = { };
606

    
607
void
608
bgp_conn_enter_established_state(struct bgp_conn *conn)
609
{
610
    struct bgp_proto *p = conn->bgp;
611
    struct bgp_caps *local = conn->local_caps;
612
    struct bgp_caps *peer = conn->remote_caps;
613
    struct bgp_channel *c;
614

    
615
    BGP_TRACE(D_EVENTS, "BGP session established");
616

    
617
    /* For multi-hop BGP sessions */
618
    if (ipa_zero(p->source_addr))
619
        p->source_addr = conn->sk->saddr;
620

    
621
    conn->sk->fast_rx = 0;
622

    
623
    p->conn = conn;
624
    p->last_error_class = 0;
625
    p->last_error_code = 0;
626

    
627
    p->as4_session = conn->as4_session;
628

    
629
    p->route_refresh = peer->route_refresh;
630
    p->enhanced_refresh = local->enhanced_refresh && peer->enhanced_refresh;
631

    
632
    /* Whether we may handle possible GR of peer (it has some AF GR-able) */
633
    p->gr_ready = 0;        /* Updated later */
634

    
635
    /* Whether peer is ready to handle our GR recovery */
636
    int peer_gr_ready = peer->gr_aware && !(peer->gr_flags & BGP_GRF_RESTART);
637

    
638
    if (p->gr_active_num)
639
        tm_stop(p->gr_timer);
640

    
641
    /* Number of active channels */
642
    int num = 0;
643

    
644
    WALK_LIST(c, p->p.channels)
645
    {
646
        const struct bgp_af_caps *loc = bgp_find_af_caps(local, c->afi);
647
        const struct bgp_af_caps *rem = bgp_find_af_caps(peer,  c->afi);
648

    
649
        /* Ignore AFIs that were not announced in multiprotocol capability */
650
        if (!loc || !loc->ready)
651
            loc = &dummy_af_caps;
652

    
653
        if (!rem || !rem->ready)
654
            rem = &dummy_af_caps;
655

    
656
        int active = loc->ready && rem->ready;
657
        c->c.disabled = !active;
658
        c->c.reloadable = p->route_refresh;
659

    
660
        c->index = active ? num++ : 0;
661

    
662
        c->feed_state = BFS_NONE;
663
        c->load_state = BFS_NONE;
664

    
665
        /* Channels where peer may do GR */
666
        c->gr_ready = active && local->gr_aware && rem->gr_able;
667
        p->gr_ready = p->gr_ready || c->gr_ready;
668

    
669
        /* Channels not able to recover gracefully */
670
        if (p->p.gr_recovery && (!active || !peer_gr_ready))
671
            channel_graceful_restart_unlock(&c->c);
672

    
673
        /* Channels waiting for local convergence */
674
        if (p->p.gr_recovery && loc->gr_able && peer_gr_ready)
675
            c->c.gr_wait = 1;
676

    
677
        /* Channels where peer is not able to recover gracefully */
678
        if (c->gr_active && ! (c->gr_ready && (rem->gr_af_flags & BGP_GRF_FORWARDING)))
679
            bgp_graceful_restart_done(c);
680

    
681
        /* GR capability implies that neighbor will send End-of-RIB */
682
        if (peer->gr_aware)
683
            c->load_state = BFS_LOADING;
684

    
685
        c->ext_next_hop = c->cf->ext_next_hop && (bgp_channel_is_ipv6(c) || rem->ext_next_hop);
686
        c->add_path_rx = (loc->add_path & BGP_ADD_PATH_RX) && (rem->add_path & BGP_ADD_PATH_TX);
687
        c->add_path_tx = (loc->add_path & BGP_ADD_PATH_TX) && (rem->add_path & BGP_ADD_PATH_RX);
688

    
689
        /* Update RA mode */
690
        if (c->add_path_tx)
691
            c->c.ra_mode = RA_ANY;
692
        else if (c->cf->secondary)
693
            c->c.ra_mode = RA_ACCEPTED;
694
        else
695
            c->c.ra_mode = RA_OPTIMAL;
696
    }
697

    
698
    p->afi_map = mb_alloc(p->p.pool, num * sizeof(u32));
699
    p->channel_map = mb_alloc(p->p.pool, num * sizeof(void *));
700
    p->channel_count = num;
701

    
702
    WALK_LIST(c, p->p.channels)
703
    {
704
        if (c->c.disabled)
705
            continue;
706

    
707
        p->afi_map[c->index] = c->afi;
708
        p->channel_map[c->index] = c;
709
    }
710

    
711
    /* proto_notify_state() will likely call bgp_feed_begin(), setting c->feed_state */
712

    
713
    bgp_conn_set_state(conn, BS_ESTABLISHED);
714
    proto_notify_state(&p->p, PS_UP);
715
}
716

    
717
static void
718
bgp_conn_leave_established_state(struct bgp_proto *p)
719
{
720
    BGP_TRACE(D_EVENTS, "BGP session closed");
721
    p->conn = NULL;
722

    
723
    if (p->p.proto_state == PS_UP)
724
        bgp_stop(p, 0, NULL, 0);
725
}
726

    
727
void
728
bgp_conn_enter_close_state(struct bgp_conn *conn)
729
{
730
    struct bgp_proto *p = conn->bgp;
731
    int os = conn->state;
732

    
733
    bgp_conn_set_state(conn, BS_CLOSE);
734
    tm_stop(conn->keepalive_timer);
735
    conn->sk->rx_hook = NULL;
736

    
737
    /* Timeout for CLOSE state, if we cannot send notification soon then we just hangup */
738
    bgp_start_timer(conn->hold_timer, 10);
739

    
740
    if (os == BS_ESTABLISHED)
741
        bgp_conn_leave_established_state(p);
742
}
743

    
744
void
745
bgp_conn_enter_idle_state(struct bgp_conn *conn)
746
{
747
    struct bgp_proto *p = conn->bgp;
748
    int os = conn->state;
749

    
750
    bgp_close_conn(conn);
751
    bgp_conn_set_state(conn, BS_IDLE);
752
    ev_schedule(p->event);
753

    
754
    if (os == BS_ESTABLISHED)
755
        bgp_conn_leave_established_state(p);
756
}
757

    
758
/**
759
 * bgp_handle_graceful_restart - handle detected BGP graceful restart
760
 * @p: BGP instance
761
 *
762
 * This function is called when a BGP graceful restart of the neighbor is
763
 * detected (when the TCP connection fails or when a new TCP connection
764
 * appears). The function activates processing of the restart - starts routing
765
 * table refresh cycle and activates BGP restart timer. The protocol state goes
766
 * back to %PS_START, but changing BGP state back to %BS_IDLE is left for the
767
 * caller.
768
 */
769
void
770
bgp_handle_graceful_restart(struct bgp_proto *p)
771
{
772
    ASSERT(p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready);
773

    
774
    BGP_TRACE(D_EVENTS, "Neighbor graceful restart detected%s",
775
              p->gr_active_num ? " - already pending" : "");
776

    
777
    p->gr_active_num = 0;
778

    
779
    struct bgp_channel *c;
780
    WALK_LIST(c, p->p.channels)
781
    {
782
        /* FIXME: perhaps check for channel state instead of disabled flag? */
783
        if (c->c.disabled)
784
            continue;
785

    
786
        if (c->gr_ready)
787
        {
788
            if (c->gr_active)
789
                rt_refresh_end(c->c.table, &c->c);
790

    
791
            c->gr_active = 1;
792
            p->gr_active_num++;
793
            rt_refresh_begin(c->c.table, &c->c);
794
        }
795
        else
796
        {
797
            /* Just flush the routes */
798
            rt_refresh_begin(c->c.table, &c->c);
799
            rt_refresh_end(c->c.table, &c->c);
800
        }
801

    
802
        /* Reset bucket and prefix tables */
803
        bgp_free_bucket_table(c);
804
        bgp_free_prefix_table(c);
805
        bgp_init_bucket_table(c);
806
        bgp_init_prefix_table(c);
807
        c->packets_to_send = 0;
808

    
809
        /* Reset MRAI timer */
810
        if(tm_active(p->conn->conn_mrai_timer)){
811
            tm_stop(p->conn->conn_mrai_timer);
812
        }
813
    }
814

    
815
    /* p->gr_ready -> at least one active channel is c->gr_ready */
816
    ASSERT(p->gr_active_num > 0);
817

    
818
    proto_notify_state(&p->p, PS_START);
819
    bgp_start_timer(p->gr_timer, p->conn->remote_caps->gr_time);
820
}
821

    
822
/**
823
 * bgp_graceful_restart_done - finish active BGP graceful restart
824
 * @c: BGP channel
825
 *
826
 * This function is called when the active BGP graceful restart of the neighbor
827
 * should be finished for channel @c - either successfully (the neighbor sends
828
 * all paths and reports end-of-RIB for given AFI/SAFI on the new session) or
829
 * unsuccessfully (the neighbor does not support BGP graceful restart on the new
830
 * session). The function ends the routing table refresh cycle.
831
 */
832
void
833
bgp_graceful_restart_done(struct bgp_channel *c)
834
{
835
    struct bgp_proto *p = (void *) c->c.proto;
836

    
837
    ASSERT(c->gr_active);
838
    c->gr_active = 0;
839
    p->gr_active_num--;
840

    
841
    if (!p->gr_active_num)
842
        BGP_TRACE(D_EVENTS, "Neighbor graceful restart done");
843

    
844
    rt_refresh_end(c->c.table, &c->c);
845
}
846

    
847
/**
848
 * bgp_graceful_restart_timeout - timeout of graceful restart 'restart timer'
849
 * @t: timer
850
 *
851
 * This function is a timeout hook for @gr_timer, implementing BGP restart time
852
 * limit for reestablisment of the BGP session after the graceful restart. When
853
 * fired, we just proceed with the usual protocol restart.
854
 */
855

    
856
static void
857
bgp_graceful_restart_timeout(timer *t)
858
{
859
    struct bgp_proto *p = t->data;
860

    
861
    BGP_TRACE(D_EVENTS, "Neighbor graceful restart timeout");
862
    bgp_stop(p, 0, NULL, 0);
863
}
864

    
865

    
866
/**
867
 * bgp_refresh_begin - start incoming enhanced route refresh sequence
868
 * @c: BGP channel
869
 *
870
 * This function is called when an incoming enhanced route refresh sequence is
871
 * started by the neighbor, demarcated by the BoRR packet. The function updates
872
 * the load state and starts the routing table refresh cycle. Note that graceful
873
 * restart also uses routing table refresh cycle, but RFC 7313 and load states
874
 * ensure that these two sequences do not overlap.
875
 */
876
void
877
bgp_refresh_begin(struct bgp_channel *c)
878
{
879
    struct bgp_proto *p = (void *) c->c.proto;
880

    
881
    if (c->load_state == BFS_LOADING)
882
    { log(L_WARN "%s: BEGIN-OF-RR received before END-OF-RIB, ignoring", p->p.name); return; }
883

    
884
    c->load_state = BFS_REFRESHING;
885
    rt_refresh_begin(c->c.table, &c->c);
886
}
887

    
888
/**
889
 * bgp_refresh_end - finish incoming enhanced route refresh sequence
890
 * @c: BGP channel
891
 *
892
 * This function is called when an incoming enhanced route refresh sequence is
893
 * finished by the neighbor, demarcated by the EoRR packet. The function updates
894
 * the load state and ends the routing table refresh cycle. Routes not received
895
 * during the sequence are removed by the nest.
896
 */
897
void
898
bgp_refresh_end(struct bgp_channel *c)
899
{
900
    struct bgp_proto *p = (void *) c->c.proto;
901

    
902
    if (c->load_state != BFS_REFRESHING)
903
    { log(L_WARN "%s: END-OF-RR received without prior BEGIN-OF-RR, ignoring", p->p.name); return; }
904

    
905
    c->load_state = BFS_NONE;
906
    rt_refresh_end(c->c.table, &c->c);
907
}
908

    
909

    
910
static void
911
bgp_send_open(struct bgp_conn *conn)
912
{
913
    DBG("BGP: Sending open\n");
914
    conn->sk->rx_hook = bgp_rx;
915
    conn->sk->tx_hook = bgp_tx;
916
    tm_stop(conn->connect_timer);
917
    bgp_schedule_packet(conn, NULL, PKT_OPEN);
918
    bgp_conn_set_state(conn, BS_OPENSENT);
919
    bgp_start_timer(conn->hold_timer, conn->bgp->cf->initial_hold_time);
920
}
921

    
922
static void
923
bgp_connected(sock *sk)
924
{
925
    struct bgp_conn *conn = sk->data;
926
    struct bgp_proto *p = conn->bgp;
927

    
928
    BGP_TRACE(D_EVENTS, "Connected");
929
    bgp_send_open(conn);
930
}
931

    
932
static void
933
bgp_connect_timeout(timer *t)
934
{
935
    struct bgp_conn *conn = t->data;
936
    struct bgp_proto *p = conn->bgp;
937

    
938
    DBG("BGP: connect_timeout\n");
939
    if (p->p.proto_state == PS_START)
940
    {
941
        bgp_close_conn(conn);
942
        bgp_connect(p);
943
    }
944
    else
945
        bgp_conn_enter_idle_state(conn);
946
}
947

    
948
static void
949
bgp_sock_err(sock *sk, int err)
950
{
951
    struct bgp_conn *conn = sk->data;
952
    struct bgp_proto *p = conn->bgp;
953

    
954
    /*
955
     * This error hook may be called either asynchronously from main
956
     * loop, or synchronously from sk_send().  But sk_send() is called
957
     * only from bgp_tx() and bgp_kick_tx(), which are both called
958
     * asynchronously from main loop. Moreover, they end if err hook is
959
     * called. Therefore, we could suppose that it is always called
960
     * asynchronously.
961
     */
962

    
963
    bgp_store_error(p, conn, BE_SOCKET, err);
964

    
965
    if (err)
966
        BGP_TRACE(D_EVENTS, "Connection lost (%M)", err);
967
    else
968
        BGP_TRACE(D_EVENTS, "Connection closed");
969

    
970
    if ((conn->state == BS_ESTABLISHED) && p->gr_ready)
971
        bgp_handle_graceful_restart(p);
972

    
973
    bgp_conn_enter_idle_state(conn);
974
}
975

    
976
static void
977
bgp_hold_timeout(timer *t)
978
{
979
    struct bgp_conn *conn = t->data;
980
    struct bgp_proto *p = conn->bgp;
981

    
982
    DBG("BGP: Hold timeout\n");
983

    
984
    /* We are already closing the connection - just do hangup */
985
    if (conn->state == BS_CLOSE)
986
    {
987
        BGP_TRACE(D_EVENTS, "Connection stalled");
988
        bgp_conn_enter_idle_state(conn);
989
        return;
990
    }
991

    
992
    /* If there is something in input queue, we are probably congested
993
       and perhaps just not processed BGP packets in time. */
994

    
995
    if (sk_rx_ready(conn->sk) > 0)
996
        bgp_start_timer(conn->hold_timer, 10);
997
    else
998
        bgp_error(conn, 4, 0, NULL, 0);
999
}
1000

    
1001
static void
1002
bgp_keepalive_timeout(timer *t)
1003
{
1004
    struct bgp_conn *conn = t->data;
1005

    
1006
    DBG("BGP: Keepalive timer\n");
1007
    bgp_schedule_packet(conn, NULL, PKT_KEEPALIVE);
1008

    
1009
    /* Kick TX a bit faster */
1010
    if (ev_active(conn->tx_ev))
1011
        ev_run(conn->tx_ev);
1012
}
1013

    
1014
static void
1015
bgp_setup_conn(struct bgp_proto *p, struct bgp_conn *conn)
1016
{
1017
    conn->sk = NULL;
1018
    conn->bgp = p;
1019

    
1020
    conn->packets_to_send = 0;
1021
    conn->channels_to_send = 0;
1022
    conn->last_channel = 0;
1023
    conn->last_channel_count = 0;
1024
    p->number_of_update_sent = 0;
1025

    
1026
    conn->connect_timer        = tm_new_init(p->p.pool, bgp_connect_timeout,         conn, 0, 0);
1027
    conn->hold_timer         = tm_new_init(p->p.pool, bgp_hold_timeout,         conn, 0, 0);
1028
    conn->keepalive_timer        = tm_new_init(p->p.pool, bgp_keepalive_timeout, conn, 0, 0);
1029

    
1030
    //global_mrai_timer->data = (void *)p->p.pool;
1031
    /* My personal timer */
1032
    conn->conn_mrai_timer = tm_new_init(p->p.pool, conn_mrai_timeout, conn, 0, 0);
1033

    
1034
    conn->tx_ev = ev_new(p->p.pool);
1035
    conn->tx_ev->hook = bgp_kick_tx;
1036
    conn->tx_ev->data = conn;
1037
}
1038

    
1039
static void
1040
bgp_setup_sk(struct bgp_conn *conn, sock *s)
1041
{
1042
    s->data = conn;
1043
    s->err_hook = bgp_sock_err;
1044
    s->fast_rx = 1;
1045
    conn->sk = s;
1046
}
1047

    
1048
static void
1049
bgp_active(struct bgp_proto *p)
1050
{
1051
    int delay = MAX(1, p->cf->connect_delay_time);
1052
    struct bgp_conn *conn = &p->outgoing_conn;
1053

    
1054
    BGP_TRACE(D_EVENTS, "Connect delayed by %d seconds", delay);
1055
    bgp_setup_conn(p, conn);
1056
    bgp_conn_set_state(conn, BS_ACTIVE);
1057
    bgp_start_timer(conn->connect_timer, delay);
1058
}
1059

    
1060
/**
1061
 * bgp_connect - initiate an outgoing connection
1062
 * @p: BGP instance
1063
 *
1064
 * The bgp_connect() function creates a new &bgp_conn and initiates
1065
 * a TCP connection to the peer. The rest of connection setup is governed
1066
 * by the BGP state machine as described in the standard.
1067
 */
1068
static void
1069
bgp_connect(struct bgp_proto *p)        /* Enter Connect state and start establishing connection */
1070
{
1071
    struct bgp_conn *conn = &p->outgoing_conn;
1072
    int hops = p->cf->multihop ? : 1;
1073

    
1074
    srand((unsigned int)time(NULL));
1075

    
1076
    DBG("BGP: Connecting\n");
1077
    sock *s = sk_new(p->p.pool);
1078
    s->type = SK_TCP_ACTIVE;
1079
    s->saddr = p->source_addr;
1080
    s->daddr = p->cf->remote_ip;
1081
    s->dport = p->cf->remote_port;
1082
    s->iface = p->neigh ? p->neigh->iface : NULL;
1083
    s->vrf = p->p.vrf;
1084
    s->ttl = p->cf->ttl_security ? 255 : hops;
1085
    s->rbsize = p->cf->enable_extended_messages ? BGP_RX_BUFFER_EXT_SIZE : BGP_RX_BUFFER_SIZE;
1086
    s->tbsize = p->cf->enable_extended_messages ? BGP_TX_BUFFER_EXT_SIZE : BGP_TX_BUFFER_SIZE;
1087
    s->tos = IP_PREC_INTERNET_CONTROL;
1088
    s->password = p->cf->password;
1089
    s->tx_hook = bgp_connected;
1090
    BGP_TRACE(D_EVENTS, "Connecting to %I%J from local address %I%J", s->daddr, p->cf->iface,
1091
              s->saddr, ipa_is_link_local(s->saddr) ? s->iface : NULL);
1092
    bgp_setup_conn(p, conn);
1093
    bgp_setup_sk(conn, s);
1094
    bgp_conn_set_state(conn, BS_CONNECT);
1095

    
1096
    if (sk_open(s) < 0)
1097
        goto err;
1098

    
1099
    /* Set minimal receive TTL if needed */
1100
    if (p->cf->ttl_security)
1101
        if (sk_set_min_ttl(s, 256 - hops) < 0)
1102
            goto err;
1103

    
1104
    DBG("BGP: Waiting for connect success\n");
1105
    bgp_start_timer(conn->connect_timer, p->cf->connect_retry_time);
1106
    return;
1107

    
1108
    err:
1109
    sk_log_error(s, p->p.name);
1110
    bgp_sock_err(s, 0);
1111
    return;
1112
}
1113

    
1114
/**
1115
 * bgp_find_proto - find existing proto for incoming connection
1116
 * @sk: TCP socket
1117
 *
1118
 */
1119
static struct bgp_proto *
1120
bgp_find_proto(sock *sk)
1121
{
1122
    struct bgp_proto *p;
1123

    
1124
    WALK_LIST(p, proto_list)
1125
    if ((p->p.proto == &proto_bgp) &&
1126
        ipa_equal(p->cf->remote_ip, sk->daddr) &&
1127
        (!p->cf->iface  || (p->cf->iface == sk->iface)) &&
1128
        (ipa_zero(p->cf->local_ip) || ipa_equal(p->cf->local_ip, sk->saddr)) &&
1129
        (p->cf->local_port == sk->sport))
1130
        return p;
1131

    
1132
    return NULL;
1133
}
1134

    
1135
/**
1136
 * bgp_incoming_connection - handle an incoming connection
1137
 * @sk: TCP socket
1138
 * @dummy: unused
1139
 *
1140
 * This function serves as a socket hook for accepting of new BGP
1141
 * connections. It searches a BGP instance corresponding to the peer
1142
 * which has connected and if such an instance exists, it creates a
1143
 * &bgp_conn structure, attaches it to the instance and either sends
1144
 * an Open message or (if there already is an active connection) it
1145
 * closes the new connection by sending a Notification message.
1146
 */
1147
static int
1148
bgp_incoming_connection(sock *sk, uint dummy UNUSED)
1149
{
1150
    struct bgp_proto *p;
1151
    int acc, hops;
1152

    
1153
    DBG("BGP: Incoming connection from %I port %d\n", sk->daddr, sk->dport);
1154
    p = bgp_find_proto(sk);
1155
    if (!p)
1156
    {
1157
        log(L_WARN "BGP: Unexpected connect from unknown address %I%J (port %d)",
1158
                sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL, sk->dport);
1159
        rfree(sk);
1160
        return 0;
1161
    }
1162

    
1163
    /*
1164
     * BIRD should keep multiple incoming connections in OpenSent state (for
1165
     * details RFC 4271 8.2.1 par 3), but it keeps just one. Duplicate incoming
1166
     * connections are rejected istead. The exception is the case where an
1167
     * incoming connection triggers a graceful restart.
1168
     */
1169

    
1170
    acc = (p->p.proto_state == PS_START || p->p.proto_state == PS_UP) &&
1171
          (p->start_state >= BSS_CONNECT) && (!p->incoming_conn.sk);
1172

    
1173
    if (p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready)
1174
    {
1175
        bgp_store_error(p, NULL, BE_MISC, BEM_GRACEFUL_RESTART);
1176
        bgp_handle_graceful_restart(p);
1177
        bgp_conn_enter_idle_state(p->conn);
1178
        acc = 1;
1179

    
1180
        /* There might be separate incoming connection in OpenSent state */
1181
        if (p->incoming_conn.state > BS_ACTIVE)
1182
            bgp_close_conn(&p->incoming_conn);
1183
    }
1184

    
1185
    BGP_TRACE(D_EVENTS, "Incoming connection from %I%J (port %d) %s",
1186
              sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL,
1187
              sk->dport, acc ? "accepted" : "rejected");
1188

    
1189
    if (!acc)
1190
    {
1191
        rfree(sk);
1192
        return 0;
1193
    }
1194

    
1195
    hops = p->cf->multihop ? : 1;
1196

    
1197
    if (sk_set_ttl(sk, p->cf->ttl_security ? 255 : hops) < 0)
1198
        goto err;
1199

    
1200
    if (p->cf->ttl_security)
1201
        if (sk_set_min_ttl(sk, 256 - hops) < 0)
1202
            goto err;
1203

    
1204
    if (p->cf->enable_extended_messages)
1205
    {
1206
        sk->rbsize = BGP_RX_BUFFER_EXT_SIZE;
1207
        sk->tbsize = BGP_TX_BUFFER_EXT_SIZE;
1208
        sk_reallocate(sk);
1209
    }
1210

    
1211
    bgp_setup_conn(p, &p->incoming_conn);
1212
    bgp_setup_sk(&p->incoming_conn, sk);
1213
    bgp_send_open(&p->incoming_conn);
1214
    return 0;
1215

    
1216
    err:
1217
    sk_log_error(sk, p->p.name);
1218
    log(L_ERR "%s: Incoming connection aborted", p->p.name);
1219
    rfree(sk);
1220
    return 0;
1221
}
1222

    
1223
static void
1224
bgp_listen_sock_err(sock *sk UNUSED, int err)
1225
{
1226
    if (err == ECONNABORTED)
1227
        log(L_WARN "BGP: Incoming connection aborted");
1228
    else
1229
    log(L_ERR "BGP: Error on listening socket: %M", err);
1230
}
1231

    
1232
static void
1233
bgp_start_neighbor(struct bgp_proto *p)
1234
{
1235
    /* Called only for single-hop BGP sessions */
1236

    
1237
    if (ipa_zero(p->source_addr))
1238
        p->source_addr = p->neigh->ifa->ip;
1239

    
1240
    if (ipa_is_link_local(p->source_addr))
1241
        p->link_addr = p->source_addr;
1242
    else if (p->neigh->iface->llv6)
1243
        p->link_addr = p->neigh->iface->llv6->ip;
1244

    
1245
    bgp_initiate(p);
1246
}
1247

    
1248
static void
1249
bgp_neigh_notify(neighbor *n)
1250
{
1251
    struct bgp_proto *p = (struct bgp_proto *) n->proto;
1252
    int ps = p->p.proto_state;
1253

    
1254
    if (n != p->neigh)
1255
        return;
1256

    
1257
    if ((ps == PS_DOWN) || (ps == PS_STOP))
1258
        return;
1259

    
1260
    int prepare = (ps == PS_START) && (p->start_state == BSS_PREPARE);
1261

    
1262
    if (n->scope <= 0)
1263
    {
1264
        if (!prepare)
1265
        {
1266
            BGP_TRACE(D_EVENTS, "Neighbor lost");
1267
            bgp_store_error(p, NULL, BE_MISC, BEM_NEIGHBOR_LOST);
1268
            /* Perhaps also run bgp_update_startup_delay(p)? */
1269
            bgp_stop(p, 0, NULL, 0);
1270
        }
1271
    }
1272
    else if (p->cf->check_link && !(n->iface->flags & IF_LINK_UP))
1273
    {
1274
        if (!prepare)
1275
        {
1276
            BGP_TRACE(D_EVENTS, "Link down");
1277
            bgp_store_error(p, NULL, BE_MISC, BEM_LINK_DOWN);
1278
            if (ps == PS_UP)
1279
                bgp_update_startup_delay(p);
1280
            bgp_stop(p, 0, NULL, 0);
1281
        }
1282
    }
1283
    else
1284
    {
1285
        if (prepare)
1286
        {
1287
            BGP_TRACE(D_EVENTS, "Neighbor ready");
1288
            bgp_start_neighbor(p);
1289
        }
1290
    }
1291
}
1292

    
1293
static void
1294
bgp_bfd_notify(struct bfd_request *req)
1295
{
1296
    struct bgp_proto *p = req->data;
1297
    int ps = p->p.proto_state;
1298

    
1299
    if (req->down && ((ps == PS_START) || (ps == PS_UP)))
1300
    {
1301
        BGP_TRACE(D_EVENTS, "BFD session down");
1302
        bgp_store_error(p, NULL, BE_MISC, BEM_BFD_DOWN);
1303
        if (ps == PS_UP)
1304
            bgp_update_startup_delay(p);
1305
        bgp_stop(p, 0, NULL, 0);
1306
    }
1307
}
1308

    
1309
static void
1310
bgp_update_bfd(struct bgp_proto *p, int use_bfd)
1311
{
1312
    if (use_bfd && !p->bfd_req)
1313
        p->bfd_req = bfd_request_session(p->p.pool, p->cf->remote_ip, p->source_addr,
1314
                                         p->cf->multihop ? NULL : p->neigh->iface,
1315
                                         bgp_bfd_notify, p);
1316

    
1317
    if (!use_bfd && p->bfd_req)
1318
    {
1319
        rfree(p->bfd_req);
1320
        p->bfd_req = NULL;
1321
    }
1322
}
1323

    
1324
static void
1325
bgp_reload_routes(struct channel *C)
1326
{
1327
    log(L_INFO "mi trovo in bgp_reload_routes");
1328
    struct bgp_proto *p = (void *) C->proto;
1329
    struct bgp_channel *c = (void *) C;
1330

    
1331
    ASSERT(p->conn && p->route_refresh);
1332

    
1333
    bgp_schedule_packet(p->conn, c, PKT_ROUTE_REFRESH);
1334
}
1335

    
1336
static void
1337
bgp_feed_begin(struct channel *C, int initial)
1338
{
1339
    //log(L_INFO "mi trovo in bgp_feed_begin, initial: %d", initial);
1340
    struct bgp_proto *p = (void *) C->proto;
1341
    struct bgp_channel *c = (void *) C;
1342

    
1343
    /* This should not happen */
1344
    if (!p->conn)
1345
        return;
1346

    
1347
    if (initial && p->cf->gr_mode)
1348
        c->feed_state = BFS_LOADING;
1349

    
1350
    /* It is refeed and both sides support enhanced route refresh */
1351
    if (!initial && p->enhanced_refresh)
1352
    {
1353
        /* BoRR must not be sent before End-of-RIB */
1354
        if (c->feed_state == BFS_LOADING || c->feed_state == BFS_LOADED)
1355
            return;
1356

    
1357
        c->feed_state = BFS_REFRESHING;
1358
        bgp_schedule_packet(p->conn, c, PKT_BEGIN_REFRESH);
1359
    }
1360
}
1361

    
1362
static void
1363
bgp_feed_end(struct channel *C)
1364
{
1365
    struct bgp_proto *p = (void *) C->proto;
1366
    struct bgp_channel *c = (void *) C;
1367

    
1368
    /* This should not happen */
1369
    if (!p->conn)
1370
        return;
1371

    
1372
    /* Non-demarcated feed ended, nothing to do */
1373
    if (c->feed_state == BFS_NONE)
1374
        return;
1375

    
1376
    /* Schedule End-of-RIB packet */
1377
    if (c->feed_state == BFS_LOADING)
1378
        c->feed_state = BFS_LOADED;
1379

    
1380
    /* Schedule EoRR packet */
1381
    if (c->feed_state == BFS_REFRESHING)
1382
        c->feed_state = BFS_REFRESHED;
1383

    
1384
    /* Kick TX hook */
1385
    bgp_schedule_packet(p->conn, c, PKT_UPDATE);
1386
}
1387

    
1388

    
1389
static void
1390
bgp_start_locked(struct object_lock *lock)
1391
{
1392
    struct bgp_proto *p = lock->data;
1393
    struct bgp_config *cf = p->cf;
1394

    
1395
    if (p->p.proto_state != PS_START)
1396
    {
1397
        DBG("BGP: Got lock in different state %d\n", p->p.proto_state);
1398
        return;
1399
    }
1400

    
1401
    DBG("BGP: Got lock\n");
1402

    
1403
    if (cf->multihop)
1404
    {
1405
        /* Multi-hop sessions do not use neighbor entries */
1406
        bgp_initiate(p);
1407
        return;
1408
    }
1409

    
1410
    neighbor *n = neigh_find2(&p->p, &cf->remote_ip, cf->iface, NEF_STICKY);
1411
    if (!n)
1412
    {
1413
        log(L_ERR "%s: Invalid remote address %I%J", p->p.name, cf->remote_ip, cf->iface);
1414
        /* As we do not start yet, we can just disable protocol */
1415
        p->p.disabled = 1;
1416
        bgp_store_error(p, NULL, BE_MISC, BEM_INVALID_NEXT_HOP);
1417
        proto_notify_state(&p->p, PS_DOWN);
1418
        return;
1419
    }
1420

    
1421
    p->neigh = n;
1422

    
1423
    if (n->scope <= 0)
1424
        BGP_TRACE(D_EVENTS, "Waiting for %I%J to become my neighbor", cf->remote_ip, cf->iface);
1425
    else if (p->cf->check_link && !(n->iface->flags & IF_LINK_UP))
1426
        BGP_TRACE(D_EVENTS, "Waiting for link on %s", n->iface->name);
1427
    else
1428
        bgp_start_neighbor(p);
1429
}
1430

    
1431
static int
1432
bgp_start(struct proto *P)
1433
{
1434
    struct bgp_proto *p = (struct bgp_proto *) P;
1435
    struct object_lock *lock;
1436

    
1437
    DBG("BGP: Startup.\n");
1438
    p->start_state = BSS_PREPARE;
1439
    p->outgoing_conn.state = BS_IDLE;
1440
    p->incoming_conn.state = BS_IDLE;
1441
    p->neigh = NULL;
1442
    p->bfd_req = NULL;
1443
    p->gr_ready = 0;
1444
    p->gr_active_num = 0;
1445

    
1446
    p->event = ev_new(p->p.pool);
1447
    p->event->hook = bgp_decision;
1448
    p->event->data = p;
1449

    
1450
    p->startup_timer = tm_new_init(p->p.pool, bgp_startup_timeout, p, 0, 0);
1451
    p->gr_timer = tm_new_init(p->p.pool, bgp_graceful_restart_timeout, p, 0, 0);
1452

    
1453
    p->local_id = proto_get_router_id(P->cf);
1454
    if (p->rr_client)
1455
        p->rr_cluster_id = p->cf->rr_cluster_id ? p->cf->rr_cluster_id : p->local_id;
1456

    
1457
    p->remote_id = 0;
1458
    p->source_addr = p->cf->local_ip;
1459
    p->link_addr = IPA_NONE;
1460

    
1461
    /* Lock all channels when in GR recovery mode */
1462
    if (p->p.gr_recovery && p->cf->gr_mode)
1463
    {
1464
        struct bgp_channel *c;
1465
        WALK_LIST(c, p->p.channels)
1466
        channel_graceful_restart_lock(&c->c);
1467
    }
1468

    
1469
    /*
1470
     * Before attempting to create the connection, we need to lock the port,
1471
     * so that we are the only instance attempting to talk with that neighbor.
1472
     */
1473

    
1474
    lock = p->lock = olock_new(P->pool);
1475
    lock->addr = p->cf->remote_ip;
1476
    lock->port = p->cf->remote_port;
1477
    lock->iface = p->cf->iface;
1478
    lock->vrf = p->cf->iface ? NULL : p->p.vrf;
1479
    lock->type = OBJLOCK_TCP;
1480
    lock->hook = bgp_start_locked;
1481
    lock->data = p;
1482
    olock_acquire(lock);
1483

    
1484
    return PS_START;
1485
}
1486

    
1487
extern int proto_restart;
1488

    
1489
static int
1490
bgp_shutdown(struct proto *P)
1491
{
1492
    struct bgp_proto *p = (struct bgp_proto *) P;
1493
    uint subcode = 0;
1494

    
1495
    char *message = NULL;
1496
    byte *data = NULL;
1497
    uint len = 0;
1498

    
1499
    BGP_TRACE(D_EVENTS, "Shutdown requested");
1500

    
1501
    switch (P->down_code)
1502
    {
1503
        case PDC_CF_REMOVE:
1504
        case PDC_CF_DISABLE:
1505
            subcode = 3; // Errcode 6, 3 - peer de-configured
1506
            break;
1507

    
1508
        case PDC_CF_RESTART:
1509
            subcode = 6; // Errcode 6, 6 - other configuration change
1510
            break;
1511

    
1512
        case PDC_CMD_DISABLE:
1513
        case PDC_CMD_SHUTDOWN:
1514
            subcode = 2; // Errcode 6, 2 - administrative shutdown
1515
            message = P->message;
1516
            break;
1517

    
1518
        case PDC_CMD_RESTART:
1519
            subcode = 4; // Errcode 6, 4 - administrative reset
1520
            message = P->message;
1521
            break;
1522

    
1523
        case PDC_RX_LIMIT_HIT:
1524
        case PDC_IN_LIMIT_HIT:
1525
            subcode = 1; // Errcode 6, 1 - max number of prefixes reached
1526
            /* log message for compatibility */
1527
            log(L_WARN "%s: Route limit exceeded, shutting down", p->p.name);
1528
            goto limit;
1529

    
1530
        case PDC_OUT_LIMIT_HIT:
1531
            subcode = proto_restart ? 4 : 2; // Administrative reset or shutdown
1532

    
1533
        limit:
1534
            bgp_store_error(p, NULL, BE_AUTO_DOWN, BEA_ROUTE_LIMIT_EXCEEDED);
1535
            if (proto_restart)
1536
                bgp_update_startup_delay(p);
1537
            else
1538
                p->startup_delay = 0;
1539
            goto done;
1540
    }
1541

    
1542
    bgp_store_error(p, NULL, BE_MAN_DOWN, 0);
1543
    p->startup_delay = 0;
1544

    
1545
    /* RFC 8203 - shutdown communication */
1546
    if (message)
1547
    {
1548
        uint msg_len = strlen(message);
1549
        msg_len = MIN(msg_len, 128);
1550

    
1551
        /* Buffer will be freed automatically by protocol shutdown */
1552
        data = mb_alloc(p->p.pool, msg_len + 1);
1553
        len = msg_len + 1;
1554

    
1555
        data[0] = msg_len;
1556
        memcpy(data+1, message, msg_len);
1557
    }
1558

    
1559
    done:
1560
    bgp_stop(p, subcode, data, len);
1561
    return p->p.proto_state;
1562
}
1563

    
1564
static struct proto *
1565
bgp_init(struct proto_config *CF)
1566
{
1567
    struct proto *P = proto_new(CF);
1568
    struct bgp_proto *p = (struct bgp_proto *) P;
1569
    struct bgp_config *cf = (struct bgp_config *) CF;
1570

    
1571
    P->rt_notify = bgp_rt_notify;
1572
    P->import_control = bgp_import_control;
1573
    P->neigh_notify = bgp_neigh_notify;
1574
    P->reload_routes = bgp_reload_routes;
1575
    P->feed_begin = bgp_feed_begin;
1576
    P->feed_end = bgp_feed_end;
1577
    P->rte_better = bgp_rte_better;
1578
    P->rte_mergable = bgp_rte_mergable;
1579
    P->rte_recalculate = cf->deterministic_med ? bgp_rte_recalculate : NULL;
1580

    
1581
    p->cf = cf;
1582
    p->local_as = cf->local_as;
1583
    p->remote_as = cf->remote_as;
1584
    p->public_as = cf->local_as;
1585
    p->is_internal = (cf->local_as == cf->remote_as);
1586
    p->is_interior = p->is_internal || cf->confederation_member;
1587
    p->rs_client = cf->rs_client;
1588
    p->rr_client = cf->rr_client;
1589

    
1590
    /* Confederation ID is used for truly external peers */
1591
    if (cf->confederation && !p->is_interior)
1592
        p->public_as = cf->confederation;
1593

    
1594
    /* Add all channels */
1595
    struct bgp_channel_config *cc;
1596
    WALK_LIST(cc, CF->channels)
1597
    proto_add_channel(P, &cc->c);
1598

    
1599
    return P;
1600
}
1601

    
1602
static void
1603
bgp_channel_init(struct channel *C, struct channel_config *CF)
1604
{
1605
    struct bgp_channel *c = (void *) C;
1606
    struct bgp_channel_config *cf = (void *) CF;
1607

    
1608
    c->cf = cf;
1609
    c->afi = cf->afi;
1610
    c->desc = cf->desc;
1611

    
1612
    if (cf->igp_table_ip4)
1613
        c->igp_table_ip4 = cf->igp_table_ip4->table;
1614

    
1615
    if (cf->igp_table_ip6)
1616
        c->igp_table_ip6 = cf->igp_table_ip6->table;
1617
}
1618

    
1619
static int
1620
bgp_channel_start(struct channel *C)
1621
{
1622
    struct bgp_proto *p = (void *) C->proto;
1623
    struct bgp_channel *c = (void *) C;
1624
    ip_addr src = p->source_addr;
1625

    
1626
    if (c->igp_table_ip4)
1627
        rt_lock_table(c->igp_table_ip4);
1628

    
1629
    if (c->igp_table_ip6)
1630
        rt_lock_table(c->igp_table_ip6);
1631

    
1632
    c->pool = p->p.pool; // XXXX
1633
    bgp_init_bucket_table(c);
1634
    bgp_init_prefix_table(c);
1635

    
1636
    c->next_hop_addr = c->cf->next_hop_addr;
1637
    c->link_addr = IPA_NONE;
1638
    c->packets_to_send = 0;
1639

    
1640
    /* Try to use source address as next hop address */
1641
    if (ipa_zero(c->next_hop_addr))
1642
    {
1643
        if (bgp_channel_is_ipv4(c) && (ipa_is_ip4(src) || c->ext_next_hop))
1644
            c->next_hop_addr = src;
1645

    
1646
        if (bgp_channel_is_ipv6(c) && (ipa_is_ip6(src) || c->ext_next_hop))
1647
            c->next_hop_addr = src;
1648
    }
1649

    
1650
    /* Use preferred addresses associated with interface / source address */
1651
    if (ipa_zero(c->next_hop_addr))
1652
    {
1653
        /* We know the iface for single-hop, we make lookup for multihop */
1654
        struct neighbor *nbr = p->neigh ?: neigh_find2(&p->p, &src, NULL, 0);
1655
        struct iface *iface = nbr ? nbr->iface : NULL;
1656

    
1657
        if (bgp_channel_is_ipv4(c) && iface && iface->addr4)
1658
            c->next_hop_addr = iface->addr4->ip;
1659

    
1660
        if (bgp_channel_is_ipv6(c) && iface && iface->addr6)
1661
            c->next_hop_addr = iface->addr6->ip;
1662
    }
1663

    
1664
    /* Exit if no feasible next hop address is found */
1665
    if (ipa_zero(c->next_hop_addr))
1666
    {
1667
        log(L_WARN "%s: Missing next hop address", p->p.name);
1668
        return 0;
1669
    }
1670

    
1671
    /* Set link-local address for IPv6 single-hop BGP */
1672
    if (ipa_is_ip6(c->next_hop_addr) && p->neigh)
1673
    {
1674
        c->link_addr = p->link_addr;
1675

    
1676
        if (ipa_zero(c->link_addr))
1677
            log(L_WARN "%s: Missing link-local address", p->p.name);
1678
    }
1679

    
1680
    /* Link local address is already in c->link_addr */
1681
    if (ipa_is_link_local(c->next_hop_addr))
1682
        c->next_hop_addr = IPA_NONE;
1683

    
1684
    return 0; /* XXXX: Currently undefined */
1685
}
1686

    
1687
static void
1688
bgp_channel_shutdown(struct channel *C)
1689
{
1690
    struct bgp_channel *c = (void *) C;
1691

    
1692
    c->next_hop_addr = IPA_NONE;
1693
    c->link_addr = IPA_NONE;
1694
    c->packets_to_send = 0;
1695
}
1696

    
1697
static void
1698
bgp_channel_cleanup(struct channel *C)
1699
{
1700
    struct bgp_channel *c = (void *) C;
1701

    
1702
    if (c->igp_table_ip4)
1703
        rt_unlock_table(c->igp_table_ip4);
1704

    
1705
    if (c->igp_table_ip6)
1706
        rt_unlock_table(c->igp_table_ip6);
1707
}
1708

    
1709
static inline struct bgp_channel_config *
1710
bgp_find_channel_config(struct bgp_config *cf, u32 afi)
1711
{
1712
    struct bgp_channel_config *cc;
1713

    
1714
    WALK_LIST(cc, cf->c.channels)
1715
    if (cc->afi == afi)
1716
        return cc;
1717

    
1718
    return NULL;
1719
}
1720

    
1721
struct rtable_config *
1722
bgp_default_igp_table(struct bgp_config *cf, struct bgp_channel_config *cc, u32 type)
1723
{
1724
    struct bgp_channel_config *cc2;
1725
    struct rtable_config *tab;
1726

    
1727
    /* First, try table connected by the channel */
1728
    if (cc->c.table->addr_type == type)
1729
        return cc->c.table;
1730

    
1731
    /* Find paired channel with the same SAFI but the other AFI */
1732
    u32 afi2 = cc->afi ^ 0x30000;
1733
    cc2 = bgp_find_channel_config(cf, afi2);
1734

    
1735
    /* Second, try IGP table configured in the paired channel */
1736
    if (cc2 && (tab = (type == NET_IP4) ? cc2->igp_table_ip4 : cc2->igp_table_ip6))
1737
        return tab;
1738

    
1739
    /* Third, try table connected by the paired channel */
1740
    if (cc2 && (cc2->c.table->addr_type == type))
1741
        return cc2->c.table;
1742

    
1743
    /* Last, try default table of given type */
1744
    if (tab = cf->c.global->def_tables[type])
1745
        return tab;
1746

    
1747
    cf_error("Undefined IGP table");
1748
}
1749

    
1750
void
1751
bgp_postconfig(struct proto_config *CF)
1752
{
1753
    struct bgp_config *cf = (void *) CF;
1754
    int internal = (cf->local_as == cf->remote_as);
1755
    int interior = internal || cf->confederation_member;
1756

    
1757
    /* Do not check templates at all */
1758
    if (cf->c.class == SYM_TEMPLATE)
1759
    return;
1760

    
1761

    
1762
    /* EBGP direct by default, IBGP multihop by default */
1763
    if (cf->multihop < 0)
1764
        cf->multihop = internal ? 64 : 0;
1765

    
1766
    /* Link check for single-hop BGP by default */
1767
    if (cf->check_link < 0)
1768
        cf->check_link = !cf->multihop;
1769

    
1770

    
1771
    if (!cf->local_as)
1772
        cf_error("Local AS number must be set");
1773

    
1774
    if (ipa_zero(cf->remote_ip))
1775
        cf_error("Neighbor must be configured");
1776

    
1777
    if (!cf->remote_as)
1778
        cf_error("Remote AS number must be set");
1779

    
1780
    if (ipa_is_link_local(cf->remote_ip) && !cf->iface)
1781
        cf_error("Link-local neighbor address requires specified interface");
1782

    
1783
    if (!(cf->capabilities && cf->enable_as4) && (cf->remote_as > 0xFFFF))
1784
        cf_error("Neighbor AS number out of range (AS4 not available)");
1785

    
1786
    if (!internal && cf->rr_client)
1787
        cf_error("Only internal neighbor can be RR client");
1788

    
1789
    if (internal && cf->rs_client)
1790
        cf_error("Only external neighbor can be RS client");
1791

    
1792
    if (!cf->confederation && cf->confederation_member)
1793
        cf_error("Confederation ID must be set for member sessions");
1794

    
1795
    if (cf->multihop && (ipa_is_link_local(cf->local_ip) ||
1796
                         ipa_is_link_local(cf->remote_ip)))
1797
        cf_error("Multihop BGP cannot be used with link-local addresses");
1798

    
1799
    if (cf->multihop && cf->iface)
1800
        cf_error("Multihop BGP cannot be bound to interface");
1801

    
1802
    if (cf->multihop && cf->check_link)
1803
        cf_error("Multihop BGP cannot depend on link state");
1804

    
1805
    if (cf->multihop && cf->bfd && ipa_zero(cf->local_ip))
1806
        cf_error("Multihop BGP with BFD requires specified local address");
1807

    
1808

    
1809
    struct bgp_channel_config *cc;
1810
    WALK_LIST(cc, CF->channels)
1811
    {
1812
        /* Handle undefined import filter */
1813
        if (cc->c.in_filter == FILTER_UNDEF)
1814
            if (interior)
1815
                cc->c.in_filter = FILTER_ACCEPT;
1816
            else
1817
                cf_error("EBGP requires explicit import policy");
1818

    
1819
        /* Handle undefined export filter */
1820
        if (cc->c.out_filter == FILTER_UNDEF)
1821
            if (interior)
1822
                cc->c.out_filter = FILTER_REJECT;
1823
            else
1824
                cf_error("EBGP requires explicit export policy");
1825

    
1826
        /* Disable after error incompatible with restart limit action */
1827
        if ((cc->c.in_limit.action == PLA_RESTART) && cf->disable_after_error)
1828
            cc->c.in_limit.action = PLA_DISABLE;
1829

    
1830
        /* Different default based on rs_client */
1831
        if (!cc->missing_lladdr)
1832
            cc->missing_lladdr = cf->rs_client ? MLL_IGNORE : MLL_SELF;
1833

    
1834
        /* Different default for gw_mode */
1835
        if (!cc->gw_mode)
1836
            cc->gw_mode = cf->multihop ? GW_RECURSIVE : GW_DIRECT;
1837

    
1838
        /* Default based on proto config */
1839
        if (cc->gr_able == 0xff)
1840
            cc->gr_able = (cf->gr_mode == BGP_GR_ABLE);
1841

    
1842
        /* Default values of IGP tables */
1843
        if ((cc->gw_mode == GW_RECURSIVE) && !cc->desc->no_igp)
1844
        {
1845
            if (!cc->igp_table_ip4 && (bgp_cc_is_ipv4(cc) || cc->ext_next_hop))
1846
                cc->igp_table_ip4 = bgp_default_igp_table(cf, cc, NET_IP4);
1847

    
1848
            if (!cc->igp_table_ip6 && (bgp_cc_is_ipv6(cc) || cc->ext_next_hop))
1849
                cc->igp_table_ip6 = bgp_default_igp_table(cf, cc, NET_IP6);
1850

    
1851
            if (cc->igp_table_ip4 && bgp_cc_is_ipv6(cc) && !cc->ext_next_hop)
1852
                cf_error("Mismatched IGP table type");
1853

    
1854
            if (cc->igp_table_ip6 && bgp_cc_is_ipv4(cc) && !cc->ext_next_hop)
1855
                cf_error("Mismatched IGP table type");
1856
        }
1857

    
1858
        if (cf->multihop && (cc->gw_mode == GW_DIRECT))
1859
            cf_error("Multihop BGP cannot use direct gateway mode");
1860

    
1861
        if ((cc->gw_mode == GW_RECURSIVE) && cc->c.table->sorted)
1862
            cf_error("BGP in recursive mode prohibits sorted table");
1863

    
1864
        if (cf->deterministic_med && cc->c.table->sorted)
1865
            cf_error("BGP with deterministic MED prohibits sorted table");
1866

    
1867
        if (cc->secondary && !cc->c.table->sorted)
1868
            cf_error("BGP with secondary option requires sorted table");
1869
    }
1870
}
1871

    
1872
static int
1873
bgp_reconfigure(struct proto *P, struct proto_config *CF)
1874
{
1875
    struct bgp_proto *p = (void *) P;
1876
    struct bgp_config *new = (void *) CF;
1877
    struct bgp_config *old = p->cf;
1878

    
1879
    if (proto_get_router_id(CF) != p->local_id)
1880
        return 0;
1881

    
1882
    int same = !memcmp(((byte *) old) + sizeof(struct proto_config),
1883
    ((byte *) new) + sizeof(struct proto_config),
1884
            // password item is last and must be checked separately
1885
            OFFSETOF(struct bgp_config, password) - sizeof(struct proto_config))
1886
    && ((!old->password && !new->password)
1887
       || (old->password && new->password && !strcmp(old->password, new->password)));
1888

    
1889
    /* FIXME: Move channel reconfiguration to generic protocol code ? */
1890
    struct channel *C, *C2;
1891
    struct bgp_channel_config *cc;
1892

    
1893
    WALK_LIST(C, p->p.channels)
1894
    C->stale = 1;
1895

    
1896
    WALK_LIST(cc, new->c.channels)
1897
    {
1898
        C = (struct channel *) bgp_find_channel(p, cc->afi);
1899
        same = proto_configure_channel(P, &C, &cc->c) && same;
1900
        C->stale = 0;
1901
    }
1902

    
1903
    WALK_LIST_DELSAFE(C, C2, p->p.channels)
1904
    if (C->stale)
1905
        same = proto_configure_channel(P, &C, NULL) && same;
1906

    
1907

    
1908
    if (same && (p->start_state > BSS_PREPARE))
1909
        bgp_update_bfd(p, new->bfd);
1910

    
1911
    /* We should update our copy of configuration ptr as old configuration will be freed */
1912
    if (same)
1913
        p->cf = new;
1914

    
1915
    return same;
1916
}
1917

    
1918
#define IGP_TABLE(cf, sym) ((cf)->igp_table_##sym ? (cf)->igp_table_##sym ->table : NULL )
1919

    
1920
static int
1921
bgp_channel_reconfigure(struct channel *C, struct channel_config *CC)
1922
{
1923
    struct bgp_channel *c = (void *) C;
1924
    struct bgp_channel_config *new = (void *) CC;
1925
    struct bgp_channel_config *old = c->cf;
1926

    
1927
    if (memcmp(((byte *) old) + sizeof(struct channel_config),
1928
               ((byte *) new) + sizeof(struct channel_config),
1929
            /* Remaining items must be checked separately */
1930
            OFFSETOF(struct bgp_channel_config, rest) - sizeof(struct channel_config)))
1931
    return 0;
1932

    
1933
    /* Check change in IGP tables */
1934
    if ((IGP_TABLE(old, ip4) != IGP_TABLE(new, ip4)) ||
1935
        (IGP_TABLE(old, ip6) != IGP_TABLE(new, ip6)))
1936
        return 0;
1937

    
1938
    c->cf = new;
1939
    return 1;
1940
}
1941

    
1942
static void
1943
bgp_copy_config(struct proto_config *dest UNUSED, struct proto_config *src UNUSED)
1944
{
1945
    /* Just a shallow copy */
1946
}
1947

    
1948

    
1949
/**
1950
 * bgp_error - report a protocol error
1951
 * @c: connection
1952
 * @code: error code (according to the RFC)
1953
 * @subcode: error sub-code
1954
 * @data: data to be passed in the Notification message
1955
 * @len: length of the data
1956
 *
1957
 * bgp_error() sends a notification packet to tell the other side that a protocol
1958
 * error has occurred (including the data considered erroneous if possible) and
1959
 * closes the connection.
1960
 */
1961
void
1962
bgp_error(struct bgp_conn *c, uint code, uint subcode, byte *data, int len)
1963
{
1964
    struct bgp_proto *p = c->bgp;
1965

    
1966
    if (c->state == BS_CLOSE)
1967
        return;
1968

    
1969
    bgp_log_error(p, BE_BGP_TX, "Error", code, subcode, data, ABS(len));
1970
    bgp_store_error(p, c, BE_BGP_TX, (code << 16) | subcode);
1971
    bgp_conn_enter_close_state(c);
1972

    
1973
    c->notify_code = code;
1974
    c->notify_subcode = subcode;
1975
    c->notify_data = data;
1976
    c->notify_size = (len > 0) ? len : 0;
1977
    bgp_schedule_packet(c, NULL, PKT_NOTIFICATION);
1978

    
1979
    if (code != 6)
1980
    {
1981
        bgp_update_startup_delay(p);
1982
        bgp_stop(p, 0, NULL, 0);
1983
    }
1984
}
1985

    
1986
/**
1987
 * bgp_store_error - store last error for status report
1988
 * @p: BGP instance
1989
 * @c: connection
1990
 * @class: error class (BE_xxx constants)
1991
 * @code: error code (class specific)
1992
 *
1993
 * bgp_store_error() decides whether given error is interesting enough
1994
 * and store that error to last_error variables of @p
1995
 */
1996
void
1997
bgp_store_error(struct bgp_proto *p, struct bgp_conn *c, u8 class, u32 code)
1998
{
1999
    /* During PS_UP, we ignore errors on secondary connection */
2000
    if ((p->p.proto_state == PS_UP) && c && (c != p->conn))
2001
        return;
2002

    
2003
    /* During PS_STOP, we ignore any errors, as we want to report
2004
     * the error that caused transition to PS_STOP
2005
     */
2006
    if (p->p.proto_state == PS_STOP)
2007
        return;
2008

    
2009
    p->last_error_class = class;
2010
    p->last_error_code = code;
2011
}
2012

    
2013
static char *bgp_state_names[] = { "Idle", "Connect", "Active", "OpenSent", "OpenConfirm", "Established", "Close" };
2014
static char *bgp_err_classes[] = { "", "Error: ", "Socket: ", "Received: ", "BGP Error: ", "Automatic shutdown: ", ""};
2015
static char *bgp_misc_errors[] = { "", "Neighbor lost", "Invalid next hop", "Kernel MD5 auth failed", "No listening socket", "Link down", "BFD session down", "Graceful restart"};
2016
static char *bgp_auto_errors[] = { "", "Route limit exceeded"};
2017

    
2018
static const char *
2019
bgp_last_errmsg(struct bgp_proto *p)
2020
{
2021
    switch (p->last_error_class)
2022
    {
2023
        case BE_MISC:
2024
            return bgp_misc_errors[p->last_error_code];
2025
        case BE_SOCKET:
2026
            return (p->last_error_code == 0) ? "Connection closed" : strerror(p->last_error_code);
2027
        case BE_BGP_RX:
2028
        case BE_BGP_TX:
2029
            return bgp_error_dsc(p->last_error_code >> 16, p->last_error_code & 0xFF);
2030
        case BE_AUTO_DOWN:
2031
            return bgp_auto_errors[p->last_error_code];
2032
        default:
2033
            return "";
2034
    }
2035
}
2036

    
2037
static const char *
2038
bgp_state_dsc(struct bgp_proto *p)
2039
{
2040
    if (p->p.proto_state == PS_DOWN)
2041
        return "Down";
2042

    
2043
    int state = MAX(p->incoming_conn.state, p->outgoing_conn.state);
2044
    if ((state == BS_IDLE) && (p->start_state >= BSS_CONNECT) && p->cf->passive)
2045
        return "Passive";
2046

    
2047
    return bgp_state_names[state];
2048
}
2049

    
2050
static void
2051
bgp_get_status(struct proto *P, byte *buf)
2052
{
2053
    struct bgp_proto *p = (struct bgp_proto *) P;
2054

    
2055
    const char *err1 = bgp_err_classes[p->last_error_class];
2056
    const char *err2 = bgp_last_errmsg(p);
2057

    
2058
    if (P->proto_state == PS_DOWN)
2059
        bsprintf(buf, "%s%s", err1, err2);
2060
    else
2061
        bsprintf(buf, "%-14s%s%s", bgp_state_dsc(p), err1, err2);
2062
}
2063

    
2064
static void
2065
bgp_show_afis(int code, char *s, u32 *afis, uint count)
2066
{
2067
    buffer b;
2068
    LOG_BUFFER_INIT(b);
2069

    
2070
    buffer_puts(&b, s);
2071

    
2072
    for (u32 *af = afis; af < (afis + count); af++)
2073
    {
2074
        const struct bgp_af_desc *desc = bgp_get_af_desc(*af);
2075
        if (desc)
2076
            buffer_print(&b, " %s", desc->name);
2077
        else
2078
            buffer_print(&b, " <%u/%u>", BGP_AFI(*af), BGP_SAFI(*af));
2079
    }
2080

    
2081
    if (b.pos == b.end)
2082
        strcpy(b.end - 32, " ... <too long>");
2083

    
2084
    cli_msg(code, b.start);
2085
}
2086

    
2087
static void
2088
bgp_show_capabilities(struct bgp_proto *p UNUSED, struct bgp_caps *caps)
2089
{
2090
    struct bgp_af_caps *ac;
2091
    uint any_mp_bgp = 0;
2092
    uint any_gr_able = 0;
2093
    uint any_add_path = 0;
2094
    uint any_ext_next_hop = 0;
2095
    u32 *afl1 = alloca(caps->af_count * sizeof(u32));
2096
    u32 *afl2 = alloca(caps->af_count * sizeof(u32));
2097
    uint afn1, afn2;
2098

    
2099
    WALK_AF_CAPS(caps, ac)
2100
    {
2101
        any_mp_bgp |= ac->ready;
2102
        any_gr_able |= ac->gr_able;
2103
        any_add_path |= ac->add_path;
2104
        any_ext_next_hop |= ac->ext_next_hop;
2105
    }
2106

    
2107
    if (any_mp_bgp)
2108
    {
2109
        cli_msg(-1006, "      Multiprotocol");
2110

    
2111
        afn1 = 0;
2112
        WALK_AF_CAPS(caps, ac)
2113
            if (ac->ready)
2114
                afl1[afn1++] = ac->afi;
2115

    
2116
        bgp_show_afis(-1006, "        AF announced:", afl1, afn1);
2117
    }
2118

    
2119
    if (caps->route_refresh)
2120
        cli_msg(-1006, "      Route refresh");
2121

    
2122
    if (any_ext_next_hop)
2123
    {
2124
        cli_msg(-1006, "      Extended next hop");
2125

    
2126
        afn1 = 0;
2127
        WALK_AF_CAPS(caps, ac)
2128
            if (ac->ext_next_hop)
2129
                afl1[afn1++] = ac->afi;
2130

    
2131
        bgp_show_afis(-1006, "        IPv6 nexthop:", afl1, afn1);
2132
    }
2133

    
2134
    if (caps->ext_messages)
2135
        cli_msg(-1006, "      Extended message");
2136

    
2137
    if (caps->gr_aware)
2138
        cli_msg(-1006, "      Graceful restart");
2139

    
2140
    if (any_gr_able)
2141
    {
2142
        /* Continues from gr_aware */
2143
        cli_msg(-1006, "        Restart time: %u", caps->gr_time);
2144
        if (caps->gr_flags & BGP_GRF_RESTART)
2145
            cli_msg(-1006, "        Restart recovery");
2146

    
2147
        afn1 = afn2 = 0;
2148
        WALK_AF_CAPS(caps, ac)
2149
        {
2150
            if (ac->gr_able)
2151
                afl1[afn1++] = ac->afi;
2152

    
2153
            if (ac->gr_af_flags & BGP_GRF_FORWARDING)
2154
                afl2[afn2++] = ac->afi;
2155
        }
2156

    
2157
        bgp_show_afis(-1006, "        AF supported:", afl1, afn1);
2158
        bgp_show_afis(-1006, "        AF preserved:", afl2, afn2);
2159
    }
2160

    
2161
    if (caps->as4_support)
2162
        cli_msg(-1006, "      4-octet AS numbers");
2163

    
2164
    if (any_add_path)
2165
    {
2166
        cli_msg(-1006, "      ADD-PATH");
2167

    
2168
        afn1 = afn2 = 0;
2169
        WALK_AF_CAPS(caps, ac)
2170
        {
2171
            if (ac->add_path & BGP_ADD_PATH_RX)
2172
                afl1[afn1++] = ac->afi;
2173

    
2174
            if (ac->add_path & BGP_ADD_PATH_TX)
2175
                afl2[afn2++] = ac->afi;
2176
        }
2177

    
2178
        bgp_show_afis(-1006, "        RX:", afl1, afn1);
2179
        bgp_show_afis(-1006, "        TX:", afl2, afn2);
2180
    }
2181

    
2182
    if (caps->enhanced_refresh)
2183
        cli_msg(-1006, "      Enhanced refresh");
2184
}
2185

    
2186
static void
2187
bgp_show_proto_info(struct proto *P)
2188
{
2189
    struct bgp_proto *p = (struct bgp_proto *) P;
2190

    
2191
    cli_msg(-1006, "  BGP state:          %s", bgp_state_dsc(p));
2192
    cli_msg(-1006, "    Neighbor address: %I%J", p->cf->remote_ip, p->cf->iface);
2193
    cli_msg(-1006, "    Neighbor AS:      %u", p->remote_as);
2194

    
2195
    if (p->gr_active_num)
2196
        cli_msg(-1006, "    Neighbor graceful restart active");
2197

    
2198
    if (P->proto_state == PS_START)
2199
    {
2200
        struct bgp_conn *oc = &p->outgoing_conn;
2201

    
2202
        if ((p->start_state < BSS_CONNECT) &&
2203
            (tm_active(p->startup_timer)))
2204
            cli_msg(-1006, "    Error wait:       %t/%u",
2205
                    tm_remains(p->startup_timer), p->startup_delay);
2206

    
2207
        if ((oc->state == BS_ACTIVE) &&
2208
            (tm_active(oc->connect_timer)))
2209
            cli_msg(-1006, "    Connect delay:    %t/%u",
2210
                    tm_remains(oc->connect_timer), p->cf->connect_delay_time);
2211

    
2212
        if (p->gr_active_num && tm_active(p->gr_timer))
2213
            cli_msg(-1006, "    Restart timer:    %t/-",
2214
                    tm_remains(p->gr_timer));
2215
    }
2216
    else if (P->proto_state == PS_UP)
2217
    {
2218
        cli_msg(-1006, "    Neighbor ID:      %R", p->remote_id);
2219
        cli_msg(-1006, "    Local capabilities");
2220
        bgp_show_capabilities(p, p->conn->local_caps);
2221
        cli_msg(-1006, "    Neighbor capabilities");
2222
        bgp_show_capabilities(p, p->conn->remote_caps);
2223
        cli_msg(-1006, "    Session:          %s%s%s%s%s",
2224
                p->is_internal ? "internal" : "external",
2225
                p->cf->multihop ? " multihop" : "",
2226
                p->rr_client ? " route-reflector" : "",
2227
                p->rs_client ? " route-server" : "",
2228
                p->as4_session ? " AS4" : "");
2229
        cli_msg(-1006, "    Source address:   %I", p->source_addr);
2230
        cli_msg(-1006, "    Hold timer:       %t/%u",
2231
                tm_remains(p->conn->hold_timer), p->conn->hold_time);
2232
        cli_msg(-1006, "    Keepalive timer:  %t/%u",
2233
                tm_remains(p->conn->keepalive_timer), p->conn->keepalive_time);
2234
    }
2235

    
2236
    if ((p->last_error_class != BE_NONE) &&
2237
        (p->last_error_class != BE_MAN_DOWN))
2238
    {
2239
        const char *err1 = bgp_err_classes[p->last_error_class];
2240
        const char *err2 = bgp_last_errmsg(p);
2241
        cli_msg(-1006, "    Last error:       %s%s", err1, err2);
2242
    }
2243

    
2244
    {
2245
        struct bgp_channel *c;
2246
        WALK_LIST(c, p->p.channels)
2247
        {
2248
            channel_show_info(&c->c);
2249

    
2250
            if (c->c.channel_state == CS_UP)
2251
            {
2252
                if (ipa_zero(c->link_addr))
2253
                    cli_msg(-1006, "    BGP Next hop:   %I", c->next_hop_addr);
2254
                else
2255
                    cli_msg(-1006, "    BGP Next hop:   %I %I", c->next_hop_addr, c->link_addr);
2256
            }
2257

    
2258
            if (c->igp_table_ip4)
2259
                cli_msg(-1006, "    IGP IPv4 table: %s", c->igp_table_ip4->name);
2260

    
2261
            if (c->igp_table_ip6)
2262
                cli_msg(-1006, "    IGP IPv6 table: %s", c->igp_table_ip6->name);
2263
        }
2264
    }
2265
}
2266

    
2267
// Next three function could be usefull in some situations
2268
/*void
2269
channel_show_info_mine(struct channel *c)
2270
{
2271
    log(L_INFO "  Channel %s", c->name);
2272
    //log(L_INFO "    State:          %s", c_states[c->channel_state]);
2273
    log(L_INFO "    Table:          %s", c->table->name);
2274
    log(L_INFO "    Preference:     %d", c->preference);
2275
    log(L_INFO "    Input filter:   %s", filter_name(c->in_filter));
2276
    log(L_INFO "    Output filter:  %s", filter_name(c->out_filter));
2277

2278
    ///*if (graceful_restart_state == GRS_ACTIVE)
2279
        log(L_INFO "    GR recovery:   %s%s",
2280
                c->gr_lock ? " pending" : "",
2281
                c->gr_wait ? " waiting" : "");//
2282

2283
    //channel_show_limit(&c->rx_limit, "Receive limit:");
2284
    //channel_show_limit(&c->in_limit, "Import limit:");
2285
    //channel_show_limit(&c->out_limit, "Export limit:");
2286

2287
    //if (c->channel_state != CS_DOWN)
2288
    //    channel_show_stats(c);
2289
}*/
2290

    
2291
/*static void
2292
bgp_show_capabilities_mine(struct bgp_proto *p UNUSED, struct bgp_caps *caps)
2293
{
2294
    struct bgp_af_caps *ac;
2295
    uint any_mp_bgp = 0;
2296
    uint any_gr_able = 0;
2297
    uint any_add_path = 0;
2298
    uint any_ext_next_hop = 0;
2299
    u32 *afl1 = alloca(caps->af_count * sizeof(u32));
2300
    u32 *afl2 = alloca(caps->af_count * sizeof(u32));
2301
    uint afn1, afn2;
2302

2303
    WALK_AF_CAPS(caps, ac)
2304
    {
2305
        any_mp_bgp |= ac->ready;
2306
        any_gr_able |= ac->gr_able;
2307
        any_add_path |= ac->add_path;
2308
        any_ext_next_hop |= ac->ext_next_hop;
2309
    }
2310

2311
    if (any_mp_bgp)
2312
    {
2313
        log(L_INFO "      Multiprotocol");
2314

2315
        afn1 = 0;
2316
        WALK_AF_CAPS(caps, ac)
2317
            if (ac->ready)
2318
                afl1[afn1++] = ac->afi;
2319

2320
        //bgp_show_afis(-1006, "        AF announced:", afl1, afn1);
2321
    }
2322

2323
    if (caps->route_refresh)
2324
        log(L_INFO "      Route refresh");
2325

2326
    if (any_ext_next_hop)
2327
    {
2328
        log(L_INFO "      Extended next hop");
2329

2330
        afn1 = 0;
2331
        WALK_AF_CAPS(caps, ac)
2332
            if (ac->ext_next_hop)
2333
                afl1[afn1++] = ac->afi;
2334

2335
        //bgp_show_afis(-1006, "        IPv6 nexthop:", afl1, afn1);
2336
    }
2337

2338
    if (caps->ext_messages)
2339
        log(L_INFO "      Extended message");
2340

2341
    if (caps->gr_aware)
2342
        log(L_INFO "      Graceful restart");
2343

2344
    if (any_gr_able)
2345
    {
2346
        // Continues from gr_aware
2347
        log(L_INFO "        Restart time: %u", caps->gr_time);
2348
        if (caps->gr_flags & BGP_GRF_RESTART)
2349
            log(L_INFO "        Restart recovery");
2350

2351
        afn1 = afn2 = 0;
2352
        WALK_AF_CAPS(caps, ac)
2353
        {
2354
            if (ac->gr_able)
2355
                afl1[afn1++] = ac->afi;
2356

2357
            if (ac->gr_af_flags & BGP_GRF_FORWARDING)
2358
                afl2[afn2++] = ac->afi;
2359
        }
2360

2361
        //bgp_show_afis(-1006, "        AF supported:", afl1, afn1);
2362
        //bgp_show_afis(-1006, "        AF preserved:", afl2, afn2);
2363
    }
2364

2365
    if (caps->as4_support)
2366
        log(L_INFO "      4-octet AS numbers");
2367

2368
    if (any_add_path)
2369
    {
2370
        log(L_INFO "      ADD-PATH");
2371

2372
        afn1 = afn2 = 0;
2373
        WALK_AF_CAPS(caps, ac)
2374
        {
2375
            if (ac->add_path & BGP_ADD_PATH_RX)
2376
                afl1[afn1++] = ac->afi;
2377

2378
            if (ac->add_path & BGP_ADD_PATH_TX)
2379
                afl2[afn2++] = ac->afi;
2380
        }
2381

2382
        //bgp_show_afis(-1006, "        RX:", afl1, afn1);
2383
        //bgp_show_afis(-1006, "        TX:", afl2, afn2);
2384
    }
2385

2386
    if (caps->enhanced_refresh)
2387
        log(L_INFO "      Enhanced refresh");
2388
}
2389
*/
2390

    
2391
/*void
2392
bgp_show_proto_info_mine(struct bgp_proto *P)
2393
{
2394
    struct bgp_proto *p = P;
2395

2396
    log(L_INFO "  BGP state:          %s", bgp_state_dsc(p));
2397
    log(L_INFO "    Neighbor address: %I%J", p->cf->remote_ip, p->cf->iface);
2398
    log(L_INFO "    Neighbor AS:      %u", p->remote_as);
2399

2400
    if (p->gr_active_num)
2401
        log(L_INFO "    Neighbor graceful restart active");
2402

2403
    if (P->p.proto_state == PS_START)
2404
    {
2405
        struct bgp_conn *oc = &p->outgoing_conn;
2406

2407
        if ((p->start_state < BSS_CONNECT) &&
2408
            (tm_active(p->startup_timer)))
2409
            log(L_INFO "    Error wait:       %t/%u",
2410
                    tm_remains(p->startup_timer), p->startup_delay);
2411

2412
        if ((oc->state == BS_ACTIVE) &&
2413
            (tm_active(oc->connect_timer)))
2414
            log(L_INFO "    Connect delay:    %t/%u",
2415
                    tm_remains(oc->connect_timer), p->cf->connect_delay_time);
2416

2417
        if (p->gr_active_num && tm_active(p->gr_timer))
2418
            log(L_INFO "    Restart timer:    %t/-",
2419
                    tm_remains(p->gr_timer));
2420
    }
2421
    else if (P->p.proto_state == PS_UP)
2422
    {
2423
        log(L_INFO "    Neighbor ID:      %R", p->remote_id);
2424
        log(L_INFO "    Local capabilities");
2425
        bgp_show_capabilities_mine(p, p->conn->local_caps);
2426
        log(L_INFO "    Neighbor capabilities");
2427
        bgp_show_capabilities_mine(p, p->conn->remote_caps);
2428
        log(L_INFO "    Session:          %s%s%s%s%s",
2429
                p->is_internal ? "internal" : "external",
2430
                p->cf->multihop ? " multihop" : "",
2431
                p->rr_client ? " route-reflector" : "",
2432
                p->rs_client ? " route-server" : "",
2433
                p->as4_session ? " AS4" : "");
2434
        log(L_INFO "    Source address:   %I", p->source_addr);
2435
        log(L_INFO "    Hold timer:       %t/%u",
2436
                tm_remains(p->conn->hold_timer), p->conn->hold_time);
2437
        log(L_INFO "    Keepalive timer:  %t/%u",
2438
                tm_remains(p->conn->keepalive_timer), p->conn->keepalive_time);
2439
    }
2440

2441
    if ((p->last_error_class != BE_NONE) &&
2442
        (p->last_error_class != BE_MAN_DOWN))
2443
    {
2444
        const char *err1 = bgp_err_classes[p->last_error_class];
2445
        const char *err2 = bgp_last_errmsg(p);
2446
        log(L_INFO "    Last error:       %s%s", err1, err2);
2447
    }
2448

2449
    {
2450
        struct bgp_channel *c;
2451
        WALK_LIST(c, p->p.channels)
2452
        {
2453
            channel_show_info_mine(&c->c);
2454

2455
            if (c->c.channel_state == CS_UP)
2456
            {
2457
                if (ipa_zero(c->link_addr))
2458
                    log(L_INFO "    BGP Next hop:   %I", c->next_hop_addr);
2459
                else
2460
                    log(L_INFO "    BGP Next hop:   %I %I", c->next_hop_addr, c->link_addr);
2461
            }
2462

2463
            if (c->igp_table_ip4)
2464
                log(L_INFO "    IGP IPv4 table: %s", c->igp_table_ip4->name);
2465

2466
            if (c->igp_table_ip6)
2467
                log(L_INFO "    IGP IPv6 table: %s", c->igp_table_ip6->name);
2468
        }
2469
    }
2470
}*/
2471

    
2472
struct channel_class channel_bgp = {
2473
        .channel_size =        sizeof(struct bgp_channel),
2474
        .config_size =        sizeof(struct bgp_channel_config),
2475
        .init =                bgp_channel_init,
2476
        .start =                bgp_channel_start,
2477
        .shutdown =                bgp_channel_shutdown,
2478
        .cleanup =                bgp_channel_cleanup,
2479
        .reconfigure =        bgp_channel_reconfigure,
2480
};
2481

    
2482
struct protocol proto_bgp = {
2483
        .name =                 "BGP",
2484
        .template =                 "bgp%d",
2485
        .attr_class =         EAP_BGP,
2486
        .preference =         DEF_PREF_BGP,
2487
        .channel_mask =        NB_IP | NB_VPN | NB_FLOW,
2488
        .proto_size =                sizeof(struct bgp_proto),
2489
        .config_size =        sizeof(struct bgp_config),
2490
        .postconfig =                bgp_postconfig,
2491
        .init =                 bgp_init,
2492
        .start =                 bgp_start,
2493
        .shutdown =                 bgp_shutdown,
2494
        .reconfigure =         bgp_reconfigure,
2495
        .copy_config =         bgp_copy_config,
2496
        .get_status =         bgp_get_status,
2497
        .get_attr =                 bgp_get_attr,
2498
        .get_route_info =         bgp_get_route_info,
2499
        .show_proto_info =         bgp_show_proto_info
2500
};