Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (74.5 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
#include <stdio.h>
111

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

    
124
#include "bgp.h"
125

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

    
130

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

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

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

    
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
    as_obj_slab = NULL;
279
    as_list_slab = NULL;
280
}
281

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

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

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

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

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

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

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

    
323
    BGP_TRACE(D_EVENTS, "MRAI timeout");
324
    bgp_fire_tx(conn);
325
}
326

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

    
338
        bgp_fire_tx(conn);
339
        bgp_free_conn_from_prefix(head);
340
    }
341
}
342

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

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

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

    
354
    if (p->cf->bfd)
355
        bgp_update_bfd(p, p->cf->bfd);
356

    
357

    
358

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

    
368
    return;
369

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

    
377
    return;
378
}
379

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

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

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

    
439
    log(L_INFO "AS del vicino con cui si vuole chiudere la connessione: %d",conn->bgp->remote_as);
440
    const char *keyRTmap;
441
    map_iter_t iterRTmap;
442
    const char *keyNHmap_RTmap;
443
    map_iter_t iterNHmap_RTmap;
444

    
445
    //NH removing from the data structure
446
    iterRTmap = map_iter(RTmap);
447
    while ((keyRTmap = map_next(RTmap, &iterRTmap))) {
448
        RTable *RTmap_element = map_get(RTmap, keyRTmap);
449
        if(RTmap_element != NULL) {
450
            iterNHmap_RTmap = map_iter(RTmap_element->NH);
451

    
452
            //Load removing from the data structure
453
            const char *keyLoadInmap_RTmap;
454
            map_iter_t iterLoadInmap_RTmap = map_iter(RTmap_element->loadin);
455
            while ((keyLoadInmap_RTmap = map_next(RTmap_element->loadin, &iterLoadInmap_RTmap))) {
456
                int keyValue = (int) strtol(keyLoadInmap_RTmap, (char **) NULL, 10);
457
                log(L_INFO "keyValue: %d - %s", keyValue, *keyLoadInmap_RTmap);
458
                if (keyValue == conn->bgp->remote_as) {
459
                    log(L_INFO "REMOVE LOADIN 2 %d %d", keyValue, conn->bgp->remote_as);
460
                    map_remove(RTmap_element->loadin, keyLoadInmap_RTmap);
461
                    iterLoadInmap_RTmap = map_iter(RTmap_element->loadin);
462
                }
463
            }
464
            //map_deinit(&RTmap_element->loadin);
465

    
466
            while ((keyNHmap_RTmap = map_next(RTmap_element->NH, &iterNHmap_RTmap))) {
467
                int *NH_AS_value = map_get(RTmap_element->NH, keyNHmap_RTmap);
468
                if (NH_AS_value != NULL) {
469
                    if (*NH_AS_value == conn->bgp->remote_as) {
470
                        //map_remove(&RTmap_element->NH, keyNHmap_RTmap);
471
                        //map_deinit(&RTmap_element->NH);
472
                        //map_deinit(&RTmap_element->loadin);
473
                        //iterNHmap_RTmap = map_iter(&RTmap_element->NH);
474
                        map_remove(RTmap, keyRTmap);
475
                        iterRTmap = map_iter(RTmap);
476
                        break;
477
                    }
478
                }
479
            }
480

    
481
            ASLoad *ASLoad_element = map_get(&ASLoad_map, ASLocale);
482
            if (ASLoad_element){
483
                char bufProto[16] = "";
484
                sprintf(bufProto, "%u", conn->bgp->remote_id);
485
                if(map_get(&ASLoad_element->remoteMap, bufProto)){
486
                    map_remove(&ASLoad_element->remoteMap, bufProto);
487
                }
488
            }
489
        }
490
    }
491

    
492
    conn->packets_to_send = 0;
493
    conn->channels_to_send = 0;
494
    rfree(conn->connect_timer);
495
    conn->connect_timer = NULL;
496
    rfree(conn->keepalive_timer);
497
    conn->keepalive_timer = NULL;
498
    rfree(conn->hold_timer);
499
    conn->hold_timer = NULL;
500

    
501
    /* My MRAI timer */
502
    rfree(conn->conn_mrai_timer);
503
    conn->conn_mrai_timer = NULL;
504

    
505
    rfree(conn->tx_ev);
506
    conn->tx_ev = NULL;
507
    rfree(conn->sk);
508
    conn->sk = NULL;
509

    
510
    mb_free(conn->local_caps);
511
    conn->local_caps = NULL;
512
    mb_free(conn->remote_caps);
513
    conn->remote_caps = NULL;
514
}
515

    
516
/**
517
 * bgp_update_startup_delay - update a startup delay
518
 * @p: BGP instance
519
 *
520
 * This function updates a startup delay that is used to postpone next BGP
521
 * connect. It also handles disable_after_error and might stop BGP instance
522
 * when error happened and disable_after_error is on.
523
 *
524
 * It should be called when BGP protocol error happened.
525
 */
526
void
527
bgp_update_startup_delay(struct bgp_proto *p)
528
{
529
    struct bgp_config *cf = p->cf;
530

    
531
    DBG("BGP: Updating startup delay\n");
532

    
533
    if (p->last_proto_error && ((current_time() - p->last_proto_error) >= cf->error_amnesia_time S))
534
    p->startup_delay = 0;
535

    
536
    p->last_proto_error = current_time();
537

    
538
    if (cf->disable_after_error)
539
    {
540
        p->startup_delay = 0;
541
        p->p.disabled = 1;
542
        return;
543
    }
544

    
545
    if (!p->startup_delay)
546
        p->startup_delay = cf->error_delay_time_min;
547
    else
548
        p->startup_delay = MIN(2 * p->startup_delay, cf->error_delay_time_max);
549
}
550

    
551
static void
552
bgp_graceful_close_conn(struct bgp_conn *conn, uint subcode, byte *data, uint len)
553
{
554
    switch (conn->state)
555
    {
556
        case BS_IDLE:
557
        case BS_CLOSE:
558
            return;
559

    
560
        case BS_CONNECT:
561
        case BS_ACTIVE:
562
            bgp_conn_enter_idle_state(conn);
563
            return;
564

    
565
        case BS_OPENSENT:
566
        case BS_OPENCONFIRM:
567
        case BS_ESTABLISHED:
568
            bgp_error(conn, 6, subcode, data, len);
569
            return;
570

    
571
        default:
572
            bug("bgp_graceful_close_conn: Unknown state %d", conn->state);
573
    }
574
}
575

    
576
static void
577
bgp_down(struct bgp_proto *p)
578
{
579
    if (p->start_state > BSS_PREPARE)
580
    {
581
        bgp_setup_auth(p, 0);
582
        bgp_close(p);
583
    }
584

    
585
    BGP_TRACE(D_EVENTS, "Down");
586
    proto_notify_state(&p->p, PS_DOWN);
587
}
588

    
589
static void
590
bgp_decision(void *vp)
591
{
592
    struct bgp_proto *p = vp;
593

    
594
    DBG("BGP: Decision start\n");
595
    if ((p->p.proto_state == PS_START) &&
596
        (p->outgoing_conn.state == BS_IDLE) &&
597
        (p->incoming_conn.state != BS_OPENCONFIRM) &&
598
        !p->cf->passive)
599
        bgp_active(p);
600

    
601
    if ((p->p.proto_state == PS_STOP) &&
602
        (p->outgoing_conn.state == BS_IDLE) &&
603
        (p->incoming_conn.state == BS_IDLE))
604
        bgp_down(p);
605
}
606

    
607
void
608
bgp_stop(struct bgp_proto *p, uint subcode, byte *data, uint len)
609
{
610
    proto_notify_state(&p->p, PS_STOP);
611
    bgp_graceful_close_conn(&p->outgoing_conn, subcode, data, len);
612
    bgp_graceful_close_conn(&p->incoming_conn, subcode, data, len);
613
    ev_schedule(p->event);
614

    
615
    //log(L_FATAL "NOW I FREE ALL THE DPC MEMORY");
616

    
617
    /*const char *keyRTmap;
618
    map_iter_t iterRTmap;
619

620
    //NH removing from the data structure
621
    iterRTmap = map_iter(&RTmap);
622
    while ((keyRTmap = map_next(&RTmap, &iterRTmap))) {
623
        RTable *RTmap_element = map_get(&RTmap, keyRTmap);*/
624
        /*if(RTmap_element != NULL) {
625
            map_deinit(&RTmap_element->loadin);
626
            map_deinit(&RTmap_element->NH);
627
        }*/
628
    /*}
629
    map_deinit(&RTmap);*/
630
}
631

    
632
static inline void
633
bgp_conn_set_state(struct bgp_conn *conn, uint new_state)
634
{
635
    if (conn->bgp->p.mrtdump & MD_STATES)
636
        mrt_dump_bgp_state_change(conn, conn->state, new_state);
637

    
638
    conn->state = new_state;
639
}
640

    
641
void
642
bgp_conn_enter_openconfirm_state(struct bgp_conn *conn)
643
{
644
    /* Really, most of the work is done in bgp_rx_open(). */
645
    bgp_conn_set_state(conn, BS_OPENCONFIRM);
646
}
647

    
648
static const struct bgp_af_caps dummy_af_caps = { };
649

    
650
void
651
bgp_conn_enter_established_state(struct bgp_conn *conn)
652
{
653
    struct bgp_proto *p = conn->bgp;
654
    struct bgp_caps *local = conn->local_caps;
655
    struct bgp_caps *peer = conn->remote_caps;
656
    struct bgp_channel *c;
657

    
658
    BGP_TRACE(D_EVENTS, "BGP session established");
659

    
660
    /* For multi-hop BGP sessions */
661
    if (ipa_zero(p->source_addr))
662
        p->source_addr = conn->sk->saddr;
663

    
664
    conn->sk->fast_rx = 0;
665

    
666
    p->conn = conn;
667
    p->last_error_class = 0;
668
    p->last_error_code = 0;
669

    
670
    p->as4_session = conn->as4_session;
671

    
672
    p->route_refresh = peer->route_refresh;
673
    p->enhanced_refresh = local->enhanced_refresh && peer->enhanced_refresh;
674

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

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

    
681
    if (p->gr_active_num)
682
        tm_stop(p->gr_timer);
683

    
684
    /* Number of active channels */
685
    int num = 0;
686

    
687
    WALK_LIST(c, p->p.channels)
688
    {
689
        const struct bgp_af_caps *loc = bgp_find_af_caps(local, c->afi);
690
        const struct bgp_af_caps *rem = bgp_find_af_caps(peer,  c->afi);
691

    
692
        /* Ignore AFIs that were not announced in multiprotocol capability */
693
        if (!loc || !loc->ready)
694
            loc = &dummy_af_caps;
695

    
696
        if (!rem || !rem->ready)
697
            rem = &dummy_af_caps;
698

    
699
        int active = loc->ready && rem->ready;
700
        c->c.disabled = !active;
701
        c->c.reloadable = p->route_refresh;
702

    
703
        c->index = active ? num++ : 0;
704

    
705
        c->feed_state = BFS_NONE;
706
        c->load_state = BFS_NONE;
707

    
708
        /* Channels where peer may do GR */
709
        c->gr_ready = active && local->gr_aware && rem->gr_able;
710
        p->gr_ready = p->gr_ready || c->gr_ready;
711

    
712
        /* Channels not able to recover gracefully */
713
        if (p->p.gr_recovery && (!active || !peer_gr_ready))
714
            channel_graceful_restart_unlock(&c->c);
715

    
716
        /* Channels waiting for local convergence */
717
        if (p->p.gr_recovery && loc->gr_able && peer_gr_ready)
718
            c->c.gr_wait = 1;
719

    
720
        /* Channels where peer is not able to recover gracefully */
721
        if (c->gr_active && ! (c->gr_ready && (rem->gr_af_flags & BGP_GRF_FORWARDING)))
722
            bgp_graceful_restart_done(c);
723

    
724
        /* GR capability implies that neighbor will send End-of-RIB */
725
        if (peer->gr_aware)
726
            c->load_state = BFS_LOADING;
727

    
728
        c->ext_next_hop = c->cf->ext_next_hop && (bgp_channel_is_ipv6(c) || rem->ext_next_hop);
729
        c->add_path_rx = (loc->add_path & BGP_ADD_PATH_RX) && (rem->add_path & BGP_ADD_PATH_TX);
730
        c->add_path_tx = (loc->add_path & BGP_ADD_PATH_TX) && (rem->add_path & BGP_ADD_PATH_RX);
731

    
732
        /* Update RA mode */
733
        if (c->add_path_tx)
734
            c->c.ra_mode = RA_ANY;
735
        else if (c->cf->secondary)
736
            c->c.ra_mode = RA_ACCEPTED;
737
        else
738
            c->c.ra_mode = RA_OPTIMAL;
739
    }
740

    
741
    p->afi_map = mb_alloc(p->p.pool, num * sizeof(u32));
742
    p->channel_map = mb_alloc(p->p.pool, num * sizeof(void *));
743
    p->channel_count = num;
744

    
745
    WALK_LIST(c, p->p.channels)
746
    {
747
        if (c->c.disabled)
748
            continue;
749

    
750
        p->afi_map[c->index] = c->afi;
751
        p->channel_map[c->index] = c;
752
    }
753

    
754
    /* proto_notify_state() will likely call bgp_feed_begin(), setting c->feed_state */
755

    
756
    bgp_conn_set_state(conn, BS_ESTABLISHED);
757
    proto_notify_state(&p->p, PS_UP);
758
}
759

    
760
static void
761
bgp_conn_leave_established_state(struct bgp_proto *p)
762
{
763
    BGP_TRACE(D_EVENTS, "BGP session closed");
764
    p->conn = NULL;
765

    
766
    if (p->p.proto_state == PS_UP)
767
        bgp_stop(p, 0, NULL, 0);
768
}
769

    
770
void
771
bgp_conn_enter_close_state(struct bgp_conn *conn)
772
{
773
    struct bgp_proto *p = conn->bgp;
774
    int os = conn->state;
775

    
776
    bgp_conn_set_state(conn, BS_CLOSE);
777
    tm_stop(conn->keepalive_timer);
778
    conn->sk->rx_hook = NULL;
779

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

    
783
    if (os == BS_ESTABLISHED)
784
        bgp_conn_leave_established_state(p);
785
}
786

    
787
void
788
bgp_conn_enter_idle_state(struct bgp_conn *conn)
789
{
790
    struct bgp_proto *p = conn->bgp;
791
    int os = conn->state;
792
    log(L_TRACE "connection in idle");
793
    bgp_close_conn(conn);
794
    bgp_conn_set_state(conn, BS_IDLE);
795
    ev_schedule(p->event);
796

    
797
    if (os == BS_ESTABLISHED)
798
        bgp_conn_leave_established_state(p);
799
}
800

    
801
/**
802
 * bgp_handle_graceful_restart - handle detected BGP graceful restart
803
 * @p: BGP instance
804
 *
805
 * This function is called when a BGP graceful restart of the neighbor is
806
 * detected (when the TCP connection fails or when a new TCP connection
807
 * appears). The function activates processing of the restart - starts routing
808
 * table refresh cycle and activates BGP restart timer. The protocol state goes
809
 * back to %PS_START, but changing BGP state back to %BS_IDLE is left for the
810
 * caller.
811
 */
812
void
813
bgp_handle_graceful_restart(struct bgp_proto *p)
814
{
815
    ASSERT(p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready);
816

    
817
    BGP_TRACE(D_EVENTS, "Neighbor graceful restart detected%s",
818
              p->gr_active_num ? " - already pending" : "");
819

    
820
    p->gr_active_num = 0;
821

    
822
    struct bgp_channel *c;
823
    WALK_LIST(c, p->p.channels)
824
    {
825
        /* FIXME: perhaps check for channel state instead of disabled flag? */
826
        if (c->c.disabled)
827
            continue;
828

    
829
        if (c->gr_ready)
830
        {
831
            if (c->gr_active)
832
                rt_refresh_end(c->c.table, &c->c);
833

    
834
            c->gr_active = 1;
835
            p->gr_active_num++;
836
            rt_refresh_begin(c->c.table, &c->c);
837
        }
838
        else
839
        {
840
            /* Just flush the routes */
841
            rt_refresh_begin(c->c.table, &c->c);
842
            rt_refresh_end(c->c.table, &c->c);
843
        }
844

    
845
        /* Reset bucket and prefix tables */
846
        bgp_free_bucket_table(c);
847
        bgp_free_prefix_table(c);
848
        bgp_init_bucket_table(c);
849
        bgp_init_prefix_table(c);
850
        c->packets_to_send = 0;
851

    
852
        /* Reset MRAI timer */
853
        if(tm_active(p->conn->conn_mrai_timer)){
854
            tm_stop(p->conn->conn_mrai_timer);
855
        }
856
    }
857

    
858
    /* p->gr_ready -> at least one active channel is c->gr_ready */
859
    ASSERT(p->gr_active_num > 0);
860

    
861
    proto_notify_state(&p->p, PS_START);
862
    bgp_start_timer(p->gr_timer, p->conn->remote_caps->gr_time);
863
}
864

    
865
/**
866
 * bgp_graceful_restart_done - finish active BGP graceful restart
867
 * @c: BGP channel
868
 *
869
 * This function is called when the active BGP graceful restart of the neighbor
870
 * should be finished for channel @c - either successfully (the neighbor sends
871
 * all paths and reports end-of-RIB for given AFI/SAFI on the new session) or
872
 * unsuccessfully (the neighbor does not support BGP graceful restart on the new
873
 * session). The function ends the routing table refresh cycle.
874
 */
875
void
876
bgp_graceful_restart_done(struct bgp_channel *c)
877
{
878
    struct bgp_proto *p = (void *) c->c.proto;
879

    
880
    ASSERT(c->gr_active);
881
    c->gr_active = 0;
882
    p->gr_active_num--;
883

    
884
    if (!p->gr_active_num)
885
        BGP_TRACE(D_EVENTS, "Neighbor graceful restart done");
886

    
887
    rt_refresh_end(c->c.table, &c->c);
888
}
889

    
890
/**
891
 * bgp_graceful_restart_timeout - timeout of graceful restart 'restart timer'
892
 * @t: timer
893
 *
894
 * This function is a timeout hook for @gr_timer, implementing BGP restart time
895
 * limit for reestablisment of the BGP session after the graceful restart. When
896
 * fired, we just proceed with the usual protocol restart.
897
 */
898

    
899
static void
900
bgp_graceful_restart_timeout(timer *t)
901
{
902
    struct bgp_proto *p = t->data;
903

    
904
    BGP_TRACE(D_EVENTS, "Neighbor graceful restart timeout");
905
    bgp_stop(p, 0, NULL, 0);
906
}
907

    
908

    
909
/**
910
 * bgp_refresh_begin - start incoming enhanced route refresh sequence
911
 * @c: BGP channel
912
 *
913
 * This function is called when an incoming enhanced route refresh sequence is
914
 * started by the neighbor, demarcated by the BoRR packet. The function updates
915
 * the load state and starts the routing table refresh cycle. Note that graceful
916
 * restart also uses routing table refresh cycle, but RFC 7313 and load states
917
 * ensure that these two sequences do not overlap.
918
 */
919
void
920
bgp_refresh_begin(struct bgp_channel *c)
921
{
922
    struct bgp_proto *p = (void *) c->c.proto;
923

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

    
927
    c->load_state = BFS_REFRESHING;
928
    rt_refresh_begin(c->c.table, &c->c);
929
}
930

    
931
/**
932
 * bgp_refresh_end - finish incoming enhanced route refresh sequence
933
 * @c: BGP channel
934
 *
935
 * This function is called when an incoming enhanced route refresh sequence is
936
 * finished by the neighbor, demarcated by the EoRR packet. The function updates
937
 * the load state and ends the routing table refresh cycle. Routes not received
938
 * during the sequence are removed by the nest.
939
 */
940
void
941
bgp_refresh_end(struct bgp_channel *c)
942
{
943
    struct bgp_proto *p = (void *) c->c.proto;
944

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

    
948
    c->load_state = BFS_NONE;
949
    rt_refresh_end(c->c.table, &c->c);
950
}
951

    
952

    
953
static void
954
bgp_send_open(struct bgp_conn *conn)
955
{
956
    DBG("BGP: Sending open\n");
957
    conn->sk->rx_hook = bgp_rx;
958
    conn->sk->tx_hook = bgp_tx;
959
    tm_stop(conn->connect_timer);
960
    bgp_schedule_packet(conn, NULL, PKT_OPEN);
961
    bgp_conn_set_state(conn, BS_OPENSENT);
962
    bgp_start_timer(conn->hold_timer, conn->bgp->cf->initial_hold_time);
963
}
964

    
965
static void
966
bgp_connected(sock *sk)
967
{
968
    struct bgp_conn *conn = sk->data;
969
    struct bgp_proto *p = conn->bgp;
970

    
971
    BGP_TRACE(D_EVENTS, "Connected");
972
    bgp_send_open(conn);
973
}
974

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

    
981
    DBG("BGP: connect_timeout\n");
982
    if (p->p.proto_state == PS_START)
983
    {
984
        log(L_TRACE "connect_timeout");
985
        bgp_close_conn(conn);
986
        bgp_connect(p);
987
    }
988
    else
989
        bgp_conn_enter_idle_state(conn);
990
}
991

    
992
static void
993
bgp_sock_err(sock *sk, int err)
994
{
995
    struct bgp_conn *conn = sk->data;
996
    struct bgp_proto *p = conn->bgp;
997

    
998
    /*
999
     * This error hook may be called either asynchronously from main
1000
     * loop, or synchronously from sk_send().  But sk_send() is called
1001
     * only from bgp_tx() and bgp_kick_tx(), which are both called
1002
     * asynchronously from main loop. Moreover, they end if err hook is
1003
     * called. Therefore, we could suppose that it is always called
1004
     * asynchronously.
1005
     */
1006

    
1007
    bgp_store_error(p, conn, BE_SOCKET, err);
1008

    
1009
    if (err)
1010
        BGP_TRACE(D_EVENTS, "Connection lost (%M)", err);
1011
    else
1012
        BGP_TRACE(D_EVENTS, "Connection closed");
1013

    
1014
    if ((conn->state == BS_ESTABLISHED) && p->gr_ready)
1015
        bgp_handle_graceful_restart(p);
1016

    
1017
    bgp_conn_enter_idle_state(conn);
1018
}
1019

    
1020
static void
1021
bgp_hold_timeout(timer *t)
1022
{
1023
    struct bgp_conn *conn = t->data;
1024
    struct bgp_proto *p = conn->bgp;
1025

    
1026
    DBG("BGP: Hold timeout\n");
1027

    
1028
    /* We are already closing the connection - just do hangup */
1029
    if (conn->state == BS_CLOSE)
1030
    {
1031
        BGP_TRACE(D_EVENTS, "Connection stalled");
1032
        bgp_conn_enter_idle_state(conn);
1033
        return;
1034
    }
1035

    
1036
    /* If there is something in input queue, we are probably congested
1037
       and perhaps just not processed BGP packets in time. */
1038

    
1039
    if (sk_rx_ready(conn->sk) > 0)
1040
        bgp_start_timer(conn->hold_timer, 10);
1041
    else
1042
        bgp_error(conn, 4, 0, NULL, 0);
1043
}
1044

    
1045
static void
1046
bgp_keepalive_timeout(timer *t)
1047
{
1048
    struct bgp_conn *conn = t->data;
1049

    
1050
    DBG("BGP: Keepalive timer\n");
1051
    bgp_schedule_packet(conn, NULL, PKT_KEEPALIVE);
1052

    
1053
    /* Kick TX a bit faster */
1054
    if (ev_active(conn->tx_ev))
1055
        ev_run(conn->tx_ev);
1056
}
1057

    
1058
static void
1059
bgp_setup_conn(struct bgp_proto *p, struct bgp_conn *conn)
1060
{
1061
    conn->sk = NULL;
1062
    conn->bgp = p;
1063

    
1064
    conn->packets_to_send = 0;
1065
    conn->channels_to_send = 0;
1066
    conn->last_channel = 0;
1067
    conn->last_channel_count = 0;
1068
    p->number_of_update_sent = 0;
1069

    
1070
    conn->connect_timer        = tm_new_init(p->p.pool, bgp_connect_timeout,         conn, 0, 0);
1071
    conn->hold_timer         = tm_new_init(p->p.pool, bgp_hold_timeout,         conn, 0, 0);
1072
    conn->keepalive_timer        = tm_new_init(p->p.pool, bgp_keepalive_timeout, conn, 0, 0);
1073

    
1074
    //global_mrai_timer->data = (void *)p->p.pool;
1075
    /* My personal timer */
1076
    conn->conn_mrai_timer = tm_new_init(p->p.pool, conn_mrai_timeout, conn, 0, 0);
1077

    
1078
    conn->tx_ev = ev_new(p->p.pool);
1079
    conn->tx_ev->hook = bgp_kick_tx;
1080
    conn->tx_ev->data = conn;
1081
}
1082

    
1083
static void
1084
bgp_setup_sk(struct bgp_conn *conn, sock *s)
1085
{
1086
    s->data = conn;
1087
    s->err_hook = bgp_sock_err;
1088
    s->fast_rx = 1;
1089
    conn->sk = s;
1090
}
1091

    
1092
static void
1093
bgp_active(struct bgp_proto *p)
1094
{
1095
    int delay = MAX(1, p->cf->connect_delay_time);
1096
    struct bgp_conn *conn = &p->outgoing_conn;
1097

    
1098
    BGP_TRACE(D_EVENTS, "Connect delayed by %d seconds", delay);
1099
    bgp_setup_conn(p, conn);
1100
    bgp_conn_set_state(conn, BS_ACTIVE);
1101
    bgp_start_timer(conn->connect_timer, delay);
1102
}
1103

    
1104
/**
1105
 * bgp_connect - initiate an outgoing connection
1106
 * @p: BGP instance
1107
 *
1108
 * The bgp_connect() function creates a new &bgp_conn and initiates
1109
 * a TCP connection to the peer. The rest of connection setup is governed
1110
 * by the BGP state machine as described in the standard.
1111
 */
1112
static void
1113
bgp_connect(struct bgp_proto *p)        /* Enter Connect state and start establishing connection */
1114
{
1115
    struct bgp_conn *conn = &p->outgoing_conn;
1116
    int hops = p->cf->multihop ? : 1;
1117

    
1118
    srand((unsigned int)time(NULL));
1119

    
1120
    DBG("BGP: Connecting\n");
1121
    sock *s = sk_new(p->p.pool);
1122
    s->type = SK_TCP_ACTIVE;
1123
    s->saddr = p->source_addr;
1124
    s->daddr = p->cf->remote_ip;
1125
    s->dport = p->cf->remote_port;
1126
    s->iface = p->neigh ? p->neigh->iface : NULL;
1127
    s->vrf = p->p.vrf;
1128
    s->ttl = p->cf->ttl_security ? 255 : hops;
1129
    s->rbsize = p->cf->enable_extended_messages ? BGP_RX_BUFFER_EXT_SIZE : BGP_RX_BUFFER_SIZE;
1130
    s->tbsize = p->cf->enable_extended_messages ? BGP_TX_BUFFER_EXT_SIZE : BGP_TX_BUFFER_SIZE;
1131
    s->tos = IP_PREC_INTERNET_CONTROL;
1132
    s->password = p->cf->password;
1133
    s->tx_hook = bgp_connected;
1134
    BGP_TRACE(D_EVENTS, "Connecting to %I%J from local address %I%J", s->daddr, p->cf->iface,
1135
              s->saddr, ipa_is_link_local(s->saddr) ? s->iface : NULL);
1136
    bgp_setup_conn(p, conn);
1137
    bgp_setup_sk(conn, s);
1138
    bgp_conn_set_state(conn, BS_CONNECT);
1139

    
1140
    if (sk_open(s) < 0)
1141
        goto err;
1142

    
1143
    /* Set minimal receive TTL if needed */
1144
    if (p->cf->ttl_security)
1145
        if (sk_set_min_ttl(s, 256 - hops) < 0)
1146
            goto err;
1147

    
1148
    DBG("BGP: Waiting for connect success\n");
1149
    bgp_start_timer(conn->connect_timer, p->cf->connect_retry_time);
1150
    return;
1151

    
1152
    err:
1153
    sk_log_error(s, p->p.name);
1154
    bgp_sock_err(s, 0);
1155
    return;
1156
}
1157

    
1158
/**
1159
 * bgp_find_proto - find existing proto for incoming connection
1160
 * @sk: TCP socket
1161
 *
1162
 */
1163
static struct bgp_proto *
1164
bgp_find_proto(sock *sk)
1165
{
1166
    struct bgp_proto *p;
1167

    
1168
    WALK_LIST(p, proto_list)
1169
    if ((p->p.proto == &proto_bgp) &&
1170
        ipa_equal(p->cf->remote_ip, sk->daddr) &&
1171
        (!p->cf->iface  || (p->cf->iface == sk->iface)) &&
1172
        (ipa_zero(p->cf->local_ip) || ipa_equal(p->cf->local_ip, sk->saddr)) &&
1173
        (p->cf->local_port == sk->sport))
1174
        return p;
1175

    
1176
    return NULL;
1177
}
1178

    
1179
/**
1180
 * bgp_incoming_connection - handle an incoming connection
1181
 * @sk: TCP socket
1182
 * @dummy: unused
1183
 *
1184
 * This function serves as a socket hook for accepting of new BGP
1185
 * connections. It searches a BGP instance corresponding to the peer
1186
 * which has connected and if such an instance exists, it creates a
1187
 * &bgp_conn structure, attaches it to the instance and either sends
1188
 * an Open message or (if there already is an active connection) it
1189
 * closes the new connection by sending a Notification message.
1190
 */
1191
static int
1192
bgp_incoming_connection(sock *sk, uint dummy UNUSED)
1193
{
1194
    struct bgp_proto *p;
1195
    int acc, hops;
1196

    
1197
    DBG("BGP: Incoming connection from %I port %d\n", sk->daddr, sk->dport);
1198
    p = bgp_find_proto(sk);
1199
    if (!p)
1200
    {
1201
        log(L_WARN "BGP: Unexpected connect from unknown address %I%J (port %d)",
1202
                sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL, sk->dport);
1203
        rfree(sk);
1204
        return 0;
1205
    }
1206

    
1207
    /*
1208
     * BIRD should keep multiple incoming connections in OpenSent state (for
1209
     * details RFC 4271 8.2.1 par 3), but it keeps just one. Duplicate incoming
1210
     * connections are rejected istead. The exception is the case where an
1211
     * incoming connection triggers a graceful restart.
1212
     */
1213

    
1214
    acc = (p->p.proto_state == PS_START || p->p.proto_state == PS_UP) &&
1215
          (p->start_state >= BSS_CONNECT) && (!p->incoming_conn.sk);
1216

    
1217
    if (p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready)
1218
    {
1219
        bgp_store_error(p, NULL, BE_MISC, BEM_GRACEFUL_RESTART);
1220
        bgp_handle_graceful_restart(p);
1221
        bgp_conn_enter_idle_state(p->conn);
1222
        acc = 1;
1223

    
1224
        /* There might be separate incoming connection in OpenSent state */
1225
        if (p->incoming_conn.state > BS_ACTIVE)
1226
            bgp_close_conn(&p->incoming_conn);
1227
    }
1228

    
1229
    BGP_TRACE(D_EVENTS, "Incoming connection from %I%J (port %d) %s",
1230
              sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL,
1231
              sk->dport, acc ? "accepted" : "rejected");
1232

    
1233
    if (!acc)
1234
    {
1235
        rfree(sk);
1236
        return 0;
1237
    }
1238

    
1239
    hops = p->cf->multihop ? : 1;
1240

    
1241
    if (sk_set_ttl(sk, p->cf->ttl_security ? 255 : hops) < 0)
1242
        goto err;
1243

    
1244
    if (p->cf->ttl_security)
1245
        if (sk_set_min_ttl(sk, 256 - hops) < 0)
1246
            goto err;
1247

    
1248
    if (p->cf->enable_extended_messages)
1249
    {
1250
        sk->rbsize = BGP_RX_BUFFER_EXT_SIZE;
1251
        sk->tbsize = BGP_TX_BUFFER_EXT_SIZE;
1252
        sk_reallocate(sk);
1253
    }
1254

    
1255
    bgp_setup_conn(p, &p->incoming_conn);
1256
    bgp_setup_sk(&p->incoming_conn, sk);
1257
    bgp_send_open(&p->incoming_conn);
1258
    return 0;
1259

    
1260
    err:
1261
    sk_log_error(sk, p->p.name);
1262
    log(L_ERR "%s: Incoming connection aborted", p->p.name);
1263
    rfree(sk);
1264
    return 0;
1265
}
1266

    
1267
static void
1268
bgp_listen_sock_err(sock *sk UNUSED, int err)
1269
{
1270
    if (err == ECONNABORTED)
1271
        log(L_WARN "BGP: Incoming connection aborted");
1272
    else
1273
    log(L_ERR "BGP: Error on listening socket: %M", err);
1274
}
1275

    
1276
static void
1277
bgp_start_neighbor(struct bgp_proto *p)
1278
{
1279
    /* Called only for single-hop BGP sessions */
1280

    
1281
    if (ipa_zero(p->source_addr))
1282
        p->source_addr = p->neigh->ifa->ip;
1283

    
1284
    if (ipa_is_link_local(p->source_addr))
1285
        p->link_addr = p->source_addr;
1286
    else if (p->neigh->iface->llv6)
1287
        p->link_addr = p->neigh->iface->llv6->ip;
1288

    
1289
    bgp_initiate(p);
1290
}
1291

    
1292
static void
1293
bgp_neigh_notify(neighbor *n)
1294
{
1295
    struct bgp_proto *p = (struct bgp_proto *) n->proto;
1296
    int ps = p->p.proto_state;
1297

    
1298
    if (n != p->neigh)
1299
        return;
1300

    
1301
    if ((ps == PS_DOWN) || (ps == PS_STOP))
1302
        return;
1303

    
1304
    int prepare = (ps == PS_START) && (p->start_state == BSS_PREPARE);
1305

    
1306
    if (n->scope <= 0)
1307
    {
1308
        if (!prepare)
1309
        {
1310
            BGP_TRACE(D_EVENTS, "Neighbor lost");
1311
            bgp_store_error(p, NULL, BE_MISC, BEM_NEIGHBOR_LOST);
1312
            /* Perhaps also run bgp_update_startup_delay(p)? */
1313
            bgp_stop(p, 0, NULL, 0);
1314
        }
1315
    }
1316
    else if (p->cf->check_link && !(n->iface->flags & IF_LINK_UP))
1317
    {
1318
        if (!prepare)
1319
        {
1320
            BGP_TRACE(D_EVENTS, "Link down");
1321
            bgp_store_error(p, NULL, BE_MISC, BEM_LINK_DOWN);
1322
            if (ps == PS_UP)
1323
                bgp_update_startup_delay(p);
1324
            bgp_stop(p, 0, NULL, 0);
1325
        }
1326
    }
1327
    else
1328
    {
1329
        if (prepare)
1330
        {
1331
            BGP_TRACE(D_EVENTS, "Neighbor ready");
1332
            bgp_start_neighbor(p);
1333
        }
1334
    }
1335
}
1336

    
1337
static void
1338
bgp_bfd_notify(struct bfd_request *req)
1339
{
1340
    struct bgp_proto *p = req->data;
1341
    int ps = p->p.proto_state;
1342

    
1343
    if (req->down && ((ps == PS_START) || (ps == PS_UP)))
1344
    {
1345
        BGP_TRACE(D_EVENTS, "BFD session down");
1346
        bgp_store_error(p, NULL, BE_MISC, BEM_BFD_DOWN);
1347
        if (ps == PS_UP)
1348
            bgp_update_startup_delay(p);
1349
        bgp_stop(p, 0, NULL, 0);
1350
    }
1351
}
1352

    
1353
static void
1354
bgp_update_bfd(struct bgp_proto *p, int use_bfd)
1355
{
1356
    if (use_bfd && !p->bfd_req)
1357
        p->bfd_req = bfd_request_session(p->p.pool, p->cf->remote_ip, p->source_addr,
1358
                                         p->cf->multihop ? NULL : p->neigh->iface,
1359
                                         bgp_bfd_notify, p);
1360

    
1361
    if (!use_bfd && p->bfd_req)
1362
    {
1363
        rfree(p->bfd_req);
1364
        p->bfd_req = NULL;
1365
    }
1366
}
1367

    
1368
static void
1369
bgp_reload_routes(struct channel *C)
1370
{
1371
    log(L_INFO "mi trovo in bgp_reload_routes");
1372
    struct bgp_proto *p = (void *) C->proto;
1373
    struct bgp_channel *c = (void *) C;
1374

    
1375
    ASSERT(p->conn && p->route_refresh);
1376

    
1377
    bgp_schedule_packet(p->conn, c, PKT_ROUTE_REFRESH);
1378
}
1379

    
1380
static void
1381
bgp_feed_begin(struct channel *C, int initial)
1382
{
1383
    //log(L_INFO "mi trovo in bgp_feed_begin, initial: %d", initial);
1384
    struct bgp_proto *p = (void *) C->proto;
1385
    struct bgp_channel *c = (void *) C;
1386

    
1387
    /* This should not happen */
1388
    if (!p->conn)
1389
        return;
1390

    
1391
    if (initial && p->cf->gr_mode)
1392
        c->feed_state = BFS_LOADING;
1393

    
1394
    /* It is refeed and both sides support enhanced route refresh */
1395
    if (!initial && p->enhanced_refresh)
1396
    {
1397
        /* BoRR must not be sent before End-of-RIB */
1398
        if (c->feed_state == BFS_LOADING || c->feed_state == BFS_LOADED)
1399
            return;
1400

    
1401
        c->feed_state = BFS_REFRESHING;
1402
        bgp_schedule_packet(p->conn, c, PKT_BEGIN_REFRESH);
1403
    }
1404
}
1405

    
1406
static void
1407
bgp_feed_end(struct channel *C)
1408
{
1409
    struct bgp_proto *p = (void *) C->proto;
1410
    struct bgp_channel *c = (void *) C;
1411

    
1412
    /* This should not happen */
1413
    if (!p->conn)
1414
        return;
1415

    
1416
    /* Non-demarcated feed ended, nothing to do */
1417
    if (c->feed_state == BFS_NONE)
1418
        return;
1419

    
1420
    /* Schedule End-of-RIB packet */
1421
    if (c->feed_state == BFS_LOADING)
1422
        c->feed_state = BFS_LOADED;
1423

    
1424
    /* Schedule EoRR packet */
1425
    if (c->feed_state == BFS_REFRESHING)
1426
        c->feed_state = BFS_REFRESHED;
1427

    
1428
    /* Kick TX hook */
1429
    bgp_schedule_packet(p->conn, c, PKT_UPDATE);
1430
}
1431

    
1432

    
1433
static void
1434
bgp_start_locked(struct object_lock *lock)
1435
{
1436
    struct bgp_proto *p = lock->data;
1437
    struct bgp_config *cf = p->cf;
1438

    
1439
    if (p->p.proto_state != PS_START)
1440
    {
1441
        DBG("BGP: Got lock in different state %d\n", p->p.proto_state);
1442
        return;
1443
    }
1444

    
1445
    DBG("BGP: Got lock\n");
1446

    
1447
    if (cf->multihop)
1448
    {
1449
        /* Multi-hop sessions do not use neighbor entries */
1450
        bgp_initiate(p);
1451
        return;
1452
    }
1453

    
1454
    neighbor *n = neigh_find2(&p->p, &cf->remote_ip, cf->iface, NEF_STICKY);
1455
    if (!n)
1456
    {
1457
        log(L_ERR "%s: Invalid remote address %I%J", p->p.name, cf->remote_ip, cf->iface);
1458
        /* As we do not start yet, we can just disable protocol */
1459
        p->p.disabled = 1;
1460
        bgp_store_error(p, NULL, BE_MISC, BEM_INVALID_NEXT_HOP);
1461
        proto_notify_state(&p->p, PS_DOWN);
1462
        return;
1463
    }
1464

    
1465
    p->neigh = n;
1466

    
1467
    if (n->scope <= 0)
1468
        BGP_TRACE(D_EVENTS, "Waiting for %I%J to become my neighbor", cf->remote_ip, cf->iface);
1469
    else if (p->cf->check_link && !(n->iface->flags & IF_LINK_UP))
1470
        BGP_TRACE(D_EVENTS, "Waiting for link on %s", n->iface->name);
1471
    else
1472
        bgp_start_neighbor(p);
1473
}
1474

    
1475
static int
1476
bgp_start(struct proto *P)
1477
{
1478
    struct bgp_proto *p = (struct bgp_proto *) P;
1479
    struct object_lock *lock;
1480

    
1481
    DBG("BGP: Startup.\n");
1482
    p->start_state = BSS_PREPARE;
1483
    p->outgoing_conn.state = BS_IDLE;
1484
    p->incoming_conn.state = BS_IDLE;
1485
    p->neigh = NULL;
1486
    p->bfd_req = NULL;
1487
    p->gr_ready = 0;
1488
    p->gr_active_num = 0;
1489

    
1490
    p->event = ev_new(p->p.pool);
1491
    p->event->hook = bgp_decision;
1492
    p->event->data = p;
1493

    
1494
    p->startup_timer = tm_new_init(p->p.pool, bgp_startup_timeout, p, 0, 0);
1495
    p->gr_timer = tm_new_init(p->p.pool, bgp_graceful_restart_timeout, p, 0, 0);
1496

    
1497
    p->local_id = proto_get_router_id(P->cf);
1498
    if (p->rr_client)
1499
        p->rr_cluster_id = p->cf->rr_cluster_id ? p->cf->rr_cluster_id : p->local_id;
1500

    
1501
    p->remote_id = 0;
1502
    p->source_addr = p->cf->local_ip;
1503
    p->link_addr = IPA_NONE;
1504

    
1505
    /* Lock all channels when in GR recovery mode */
1506
    if (p->p.gr_recovery && p->cf->gr_mode)
1507
    {
1508
        struct bgp_channel *c;
1509
        WALK_LIST(c, p->p.channels)
1510
        channel_graceful_restart_lock(&c->c);
1511
    }
1512

    
1513
    /*
1514
     * Before attempting to create the connection, we need to lock the port,
1515
     * so that we are the only instance attempting to talk with that neighbor.
1516
     */
1517

    
1518
    lock = p->lock = olock_new(P->pool);
1519
    lock->addr = p->cf->remote_ip;
1520
    lock->port = p->cf->remote_port;
1521
    lock->iface = p->cf->iface;
1522
    lock->vrf = p->cf->iface ? NULL : p->p.vrf;
1523
    lock->type = OBJLOCK_TCP;
1524
    lock->hook = bgp_start_locked;
1525
    lock->data = p;
1526
    olock_acquire(lock);
1527

    
1528
    return PS_START;
1529
}
1530

    
1531
extern int proto_restart;
1532

    
1533
static int
1534
bgp_shutdown(struct proto *P)
1535
{
1536
    struct bgp_proto *p = (struct bgp_proto *) P;
1537
    uint subcode = 0;
1538

    
1539
    char *message = NULL;
1540
    byte *data = NULL;
1541
    uint len = 0;
1542

    
1543
    BGP_TRACE(D_EVENTS, "Shutdown requested");
1544

    
1545
    switch (P->down_code)
1546
    {
1547
        case PDC_CF_REMOVE:
1548
        case PDC_CF_DISABLE:
1549
            subcode = 3; // Errcode 6, 3 - peer de-configured
1550
            break;
1551

    
1552
        case PDC_CF_RESTART:
1553
            subcode = 6; // Errcode 6, 6 - other configuration change
1554
            break;
1555

    
1556
        case PDC_CMD_DISABLE:
1557
        case PDC_CMD_SHUTDOWN:
1558
            subcode = 2; // Errcode 6, 2 - administrative shutdown
1559
            message = P->message;
1560
            break;
1561

    
1562
        case PDC_CMD_RESTART:
1563
            subcode = 4; // Errcode 6, 4 - administrative reset
1564
            message = P->message;
1565
            break;
1566

    
1567
        case PDC_RX_LIMIT_HIT:
1568
        case PDC_IN_LIMIT_HIT:
1569
            subcode = 1; // Errcode 6, 1 - max number of prefixes reached
1570
            /* log message for compatibility */
1571
            log(L_WARN "%s: Route limit exceeded, shutting down", p->p.name);
1572
            goto limit;
1573

    
1574
        case PDC_OUT_LIMIT_HIT:
1575
            subcode = proto_restart ? 4 : 2; // Administrative reset or shutdown
1576

    
1577
        limit:
1578
            bgp_store_error(p, NULL, BE_AUTO_DOWN, BEA_ROUTE_LIMIT_EXCEEDED);
1579
            if (proto_restart)
1580
                bgp_update_startup_delay(p);
1581
            else
1582
                p->startup_delay = 0;
1583
            goto done;
1584
    }
1585

    
1586
    bgp_store_error(p, NULL, BE_MAN_DOWN, 0);
1587
    p->startup_delay = 0;
1588

    
1589
    /* RFC 8203 - shutdown communication */
1590
    if (message)
1591
    {
1592
        uint msg_len = strlen(message);
1593
        msg_len = MIN(msg_len, 128);
1594

    
1595
        /* Buffer will be freed automatically by protocol shutdown */
1596
        data = mb_alloc(p->p.pool, msg_len + 1);
1597
        len = msg_len + 1;
1598

    
1599
        data[0] = msg_len;
1600
        memcpy(data+1, message, msg_len);
1601
    }
1602

    
1603
    done:
1604
    bgp_stop(p, subcode, data, len);
1605
    return p->p.proto_state;
1606
}
1607

    
1608
static struct proto *
1609
bgp_init(struct proto_config *CF)
1610
{
1611
    struct proto *P = proto_new(CF);
1612
    struct bgp_proto *p = (struct bgp_proto *) P;
1613
    struct bgp_config *cf = (struct bgp_config *) CF;
1614

    
1615
    P->rt_notify = bgp_rt_notify;
1616
    P->import_control = bgp_import_control;
1617
    P->neigh_notify = bgp_neigh_notify;
1618
    P->reload_routes = bgp_reload_routes;
1619
    P->feed_begin = bgp_feed_begin;
1620
    P->feed_end = bgp_feed_end;
1621
    P->rte_better = bgp_rte_better;
1622
    P->rte_mergable = bgp_rte_mergable;
1623
    P->rte_recalculate = cf->deterministic_med ? bgp_rte_recalculate : NULL;
1624

    
1625
    p->cf = cf;
1626
    p->local_as = cf->local_as;
1627
    p->remote_as = cf->remote_as;
1628
    p->public_as = cf->local_as;
1629
    p->is_internal = (cf->local_as == cf->remote_as);
1630
    p->is_interior = p->is_internal || cf->confederation_member;
1631
    p->rs_client = cf->rs_client;
1632
    p->rr_client = cf->rr_client;
1633

    
1634
    /* Confederation ID is used for truly external peers */
1635
    if (cf->confederation && !p->is_interior)
1636
        p->public_as = cf->confederation;
1637

    
1638
    /* Add all channels */
1639
    struct bgp_channel_config *cc;
1640
    WALK_LIST(cc, CF->channels)
1641
    proto_add_channel(P, &cc->c);
1642

    
1643
    return P;
1644
}
1645

    
1646
static void
1647
bgp_channel_init(struct channel *C, struct channel_config *CF)
1648
{
1649
    struct bgp_channel *c = (void *) C;
1650
    struct bgp_channel_config *cf = (void *) CF;
1651

    
1652
    c->cf = cf;
1653
    c->afi = cf->afi;
1654
    c->desc = cf->desc;
1655

    
1656
    if (cf->igp_table_ip4)
1657
        c->igp_table_ip4 = cf->igp_table_ip4->table;
1658

    
1659
    if (cf->igp_table_ip6)
1660
        c->igp_table_ip6 = cf->igp_table_ip6->table;
1661
}
1662

    
1663
static int
1664
bgp_channel_start(struct channel *C)
1665
{
1666
    struct bgp_proto *p = (void *) C->proto;
1667
    struct bgp_channel *c = (void *) C;
1668
    ip_addr src = p->source_addr;
1669

    
1670
    if (c->igp_table_ip4)
1671
        rt_lock_table(c->igp_table_ip4);
1672

    
1673
    if (c->igp_table_ip6)
1674
        rt_lock_table(c->igp_table_ip6);
1675

    
1676
    c->pool = p->p.pool; // XXXX
1677
    bgp_init_bucket_table(c);
1678
    bgp_init_prefix_table(c);
1679

    
1680
    c->next_hop_addr = c->cf->next_hop_addr;
1681
    c->link_addr = IPA_NONE;
1682
    c->packets_to_send = 0;
1683

    
1684
    /* Try to use source address as next hop address */
1685
    if (ipa_zero(c->next_hop_addr))
1686
    {
1687
        if (bgp_channel_is_ipv4(c) && (ipa_is_ip4(src) || c->ext_next_hop))
1688
            c->next_hop_addr = src;
1689

    
1690
        if (bgp_channel_is_ipv6(c) && (ipa_is_ip6(src) || c->ext_next_hop))
1691
            c->next_hop_addr = src;
1692
    }
1693

    
1694
    /* Use preferred addresses associated with interface / source address */
1695
    if (ipa_zero(c->next_hop_addr))
1696
    {
1697
        /* We know the iface for single-hop, we make lookup for multihop */
1698
        struct neighbor *nbr = p->neigh ?: neigh_find2(&p->p, &src, NULL, 0);
1699
        struct iface *iface = nbr ? nbr->iface : NULL;
1700

    
1701
        if (bgp_channel_is_ipv4(c) && iface && iface->addr4)
1702
            c->next_hop_addr = iface->addr4->ip;
1703

    
1704
        if (bgp_channel_is_ipv6(c) && iface && iface->addr6)
1705
            c->next_hop_addr = iface->addr6->ip;
1706
    }
1707

    
1708
    /* Exit if no feasible next hop address is found */
1709
    if (ipa_zero(c->next_hop_addr))
1710
    {
1711
        log(L_WARN "%s: Missing next hop address", p->p.name);
1712
        return 0;
1713
    }
1714

    
1715
    /* Set link-local address for IPv6 single-hop BGP */
1716
    if (ipa_is_ip6(c->next_hop_addr) && p->neigh)
1717
    {
1718
        c->link_addr = p->link_addr;
1719

    
1720
        if (ipa_zero(c->link_addr))
1721
            log(L_WARN "%s: Missing link-local address", p->p.name);
1722
    }
1723

    
1724
    /* Link local address is already in c->link_addr */
1725
    if (ipa_is_link_local(c->next_hop_addr))
1726
        c->next_hop_addr = IPA_NONE;
1727

    
1728
    return 0; /* XXXX: Currently undefined */
1729
}
1730

    
1731
static void
1732
bgp_channel_shutdown(struct channel *C)
1733
{
1734
    struct bgp_channel *c = (void *) C;
1735

    
1736
    c->next_hop_addr = IPA_NONE;
1737
    c->link_addr = IPA_NONE;
1738
    c->packets_to_send = 0;
1739
}
1740

    
1741
static void
1742
bgp_channel_cleanup(struct channel *C)
1743
{
1744
    struct bgp_channel *c = (void *) C;
1745

    
1746
    if (c->igp_table_ip4)
1747
        rt_unlock_table(c->igp_table_ip4);
1748

    
1749
    if (c->igp_table_ip6)
1750
        rt_unlock_table(c->igp_table_ip6);
1751
}
1752

    
1753
static inline struct bgp_channel_config *
1754
bgp_find_channel_config(struct bgp_config *cf, u32 afi)
1755
{
1756
    struct bgp_channel_config *cc;
1757

    
1758
    WALK_LIST(cc, cf->c.channels)
1759
    if (cc->afi == afi)
1760
        return cc;
1761

    
1762
    return NULL;
1763
}
1764

    
1765
struct rtable_config *
1766
bgp_default_igp_table(struct bgp_config *cf, struct bgp_channel_config *cc, u32 type)
1767
{
1768
    struct bgp_channel_config *cc2;
1769
    struct rtable_config *tab;
1770

    
1771
    /* First, try table connected by the channel */
1772
    if (cc->c.table->addr_type == type)
1773
        return cc->c.table;
1774

    
1775
    /* Find paired channel with the same SAFI but the other AFI */
1776
    u32 afi2 = cc->afi ^ 0x30000;
1777
    cc2 = bgp_find_channel_config(cf, afi2);
1778

    
1779
    /* Second, try IGP table configured in the paired channel */
1780
    if (cc2 && (tab = (type == NET_IP4) ? cc2->igp_table_ip4 : cc2->igp_table_ip6))
1781
        return tab;
1782

    
1783
    /* Third, try table connected by the paired channel */
1784
    if (cc2 && (cc2->c.table->addr_type == type))
1785
        return cc2->c.table;
1786

    
1787
    /* Last, try default table of given type */
1788
    if (tab = cf->c.global->def_tables[type])
1789
        return tab;
1790

    
1791
    cf_error("Undefined IGP table");
1792
}
1793

    
1794
void
1795
bgp_postconfig(struct proto_config *CF)
1796
{
1797
    struct bgp_config *cf = (void *) CF;
1798
    int internal = (cf->local_as == cf->remote_as);
1799
    int interior = internal || cf->confederation_member;
1800

    
1801
    /* Do not check templates at all */
1802
    if (cf->c.class == SYM_TEMPLATE)
1803
    return;
1804

    
1805

    
1806
    /* EBGP direct by default, IBGP multihop by default */
1807
    if (cf->multihop < 0)
1808
        cf->multihop = internal ? 64 : 0;
1809

    
1810
    /* Link check for single-hop BGP by default */
1811
    if (cf->check_link < 0)
1812
        cf->check_link = !cf->multihop;
1813

    
1814

    
1815
    if (!cf->local_as)
1816
        cf_error("Local AS number must be set");
1817

    
1818
    if (ipa_zero(cf->remote_ip))
1819
        cf_error("Neighbor must be configured");
1820

    
1821
    if (!cf->remote_as)
1822
        cf_error("Remote AS number must be set");
1823

    
1824
    if (ipa_is_link_local(cf->remote_ip) && !cf->iface)
1825
        cf_error("Link-local neighbor address requires specified interface");
1826

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

    
1830
    if (!internal && cf->rr_client)
1831
        cf_error("Only internal neighbor can be RR client");
1832

    
1833
    if (internal && cf->rs_client)
1834
        cf_error("Only external neighbor can be RS client");
1835

    
1836
    if (!cf->confederation && cf->confederation_member)
1837
        cf_error("Confederation ID must be set for member sessions");
1838

    
1839
    if (cf->multihop && (ipa_is_link_local(cf->local_ip) ||
1840
                         ipa_is_link_local(cf->remote_ip)))
1841
        cf_error("Multihop BGP cannot be used with link-local addresses");
1842

    
1843
    if (cf->multihop && cf->iface)
1844
        cf_error("Multihop BGP cannot be bound to interface");
1845

    
1846
    if (cf->multihop && cf->check_link)
1847
        cf_error("Multihop BGP cannot depend on link state");
1848

    
1849
    if (cf->multihop && cf->bfd && ipa_zero(cf->local_ip))
1850
        cf_error("Multihop BGP with BFD requires specified local address");
1851

    
1852

    
1853
    struct bgp_channel_config *cc;
1854
    WALK_LIST(cc, CF->channels)
1855
    {
1856
        /* Handle undefined import filter */
1857
        if (cc->c.in_filter == FILTER_UNDEF)
1858
            if (interior)
1859
                cc->c.in_filter = FILTER_ACCEPT;
1860
            else
1861
                cf_error("EBGP requires explicit import policy");
1862

    
1863
        /* Handle undefined export filter */
1864
        if (cc->c.out_filter == FILTER_UNDEF)
1865
            if (interior)
1866
                cc->c.out_filter = FILTER_REJECT;
1867
            else
1868
                cf_error("EBGP requires explicit export policy");
1869

    
1870
        /* Disable after error incompatible with restart limit action */
1871
        if ((cc->c.in_limit.action == PLA_RESTART) && cf->disable_after_error)
1872
            cc->c.in_limit.action = PLA_DISABLE;
1873

    
1874
        /* Different default based on rs_client */
1875
        if (!cc->missing_lladdr)
1876
            cc->missing_lladdr = cf->rs_client ? MLL_IGNORE : MLL_SELF;
1877

    
1878
        /* Different default for gw_mode */
1879
        if (!cc->gw_mode)
1880
            cc->gw_mode = cf->multihop ? GW_RECURSIVE : GW_DIRECT;
1881

    
1882
        /* Default based on proto config */
1883
        if (cc->gr_able == 0xff)
1884
            cc->gr_able = (cf->gr_mode == BGP_GR_ABLE);
1885

    
1886
        /* Default values of IGP tables */
1887
        if ((cc->gw_mode == GW_RECURSIVE) && !cc->desc->no_igp)
1888
        {
1889
            if (!cc->igp_table_ip4 && (bgp_cc_is_ipv4(cc) || cc->ext_next_hop))
1890
                cc->igp_table_ip4 = bgp_default_igp_table(cf, cc, NET_IP4);
1891

    
1892
            if (!cc->igp_table_ip6 && (bgp_cc_is_ipv6(cc) || cc->ext_next_hop))
1893
                cc->igp_table_ip6 = bgp_default_igp_table(cf, cc, NET_IP6);
1894

    
1895
            if (cc->igp_table_ip4 && bgp_cc_is_ipv6(cc) && !cc->ext_next_hop)
1896
                cf_error("Mismatched IGP table type");
1897

    
1898
            if (cc->igp_table_ip6 && bgp_cc_is_ipv4(cc) && !cc->ext_next_hop)
1899
                cf_error("Mismatched IGP table type");
1900
        }
1901

    
1902
        if (cf->multihop && (cc->gw_mode == GW_DIRECT))
1903
            cf_error("Multihop BGP cannot use direct gateway mode");
1904

    
1905
        if ((cc->gw_mode == GW_RECURSIVE) && cc->c.table->sorted)
1906
            cf_error("BGP in recursive mode prohibits sorted table");
1907

    
1908
        if (cf->deterministic_med && cc->c.table->sorted)
1909
            cf_error("BGP with deterministic MED prohibits sorted table");
1910

    
1911
        if (cc->secondary && !cc->c.table->sorted)
1912
            cf_error("BGP with secondary option requires sorted table");
1913
    }
1914
}
1915

    
1916
static int
1917
bgp_reconfigure(struct proto *P, struct proto_config *CF)
1918
{
1919
    struct bgp_proto *p = (void *) P;
1920
    struct bgp_config *new = (void *) CF;
1921
    struct bgp_config *old = p->cf;
1922

    
1923
    if (proto_get_router_id(CF) != p->local_id)
1924
        return 0;
1925

    
1926
    int same = !memcmp(((byte *) old) + sizeof(struct proto_config),
1927
    ((byte *) new) + sizeof(struct proto_config),
1928
            // password item is last and must be checked separately
1929
            OFFSETOF(struct bgp_config, password) - sizeof(struct proto_config))
1930
    && ((!old->password && !new->password)
1931
       || (old->password && new->password && !strcmp(old->password, new->password)));
1932

    
1933
    /* FIXME: Move channel reconfiguration to generic protocol code ? */
1934
    struct channel *C, *C2;
1935
    struct bgp_channel_config *cc;
1936

    
1937
    WALK_LIST(C, p->p.channels)
1938
    C->stale = 1;
1939

    
1940
    WALK_LIST(cc, new->c.channels)
1941
    {
1942
        C = (struct channel *) bgp_find_channel(p, cc->afi);
1943
        same = proto_configure_channel(P, &C, &cc->c) && same;
1944
        C->stale = 0;
1945
    }
1946

    
1947
    WALK_LIST_DELSAFE(C, C2, p->p.channels)
1948
    if (C->stale)
1949
        same = proto_configure_channel(P, &C, NULL) && same;
1950

    
1951

    
1952
    if (same && (p->start_state > BSS_PREPARE))
1953
        bgp_update_bfd(p, new->bfd);
1954

    
1955
    /* We should update our copy of configuration ptr as old configuration will be freed */
1956
    if (same)
1957
        p->cf = new;
1958

    
1959
    return same;
1960
}
1961

    
1962
#define IGP_TABLE(cf, sym) ((cf)->igp_table_##sym ? (cf)->igp_table_##sym ->table : NULL )
1963

    
1964
static int
1965
bgp_channel_reconfigure(struct channel *C, struct channel_config *CC)
1966
{
1967
    struct bgp_channel *c = (void *) C;
1968
    struct bgp_channel_config *new = (void *) CC;
1969
    struct bgp_channel_config *old = c->cf;
1970

    
1971
    if (memcmp(((byte *) old) + sizeof(struct channel_config),
1972
               ((byte *) new) + sizeof(struct channel_config),
1973
            /* Remaining items must be checked separately */
1974
            OFFSETOF(struct bgp_channel_config, rest) - sizeof(struct channel_config)))
1975
    return 0;
1976

    
1977
    /* Check change in IGP tables */
1978
    if ((IGP_TABLE(old, ip4) != IGP_TABLE(new, ip4)) ||
1979
        (IGP_TABLE(old, ip6) != IGP_TABLE(new, ip6)))
1980
        return 0;
1981

    
1982
    c->cf = new;
1983
    return 1;
1984
}
1985

    
1986
static void
1987
bgp_copy_config(struct proto_config *dest UNUSED, struct proto_config *src UNUSED)
1988
{
1989
    /* Just a shallow copy */
1990
}
1991

    
1992

    
1993
/**
1994
 * bgp_error - report a protocol error
1995
 * @c: connection
1996
 * @code: error code (according to the RFC)
1997
 * @subcode: error sub-code
1998
 * @data: data to be passed in the Notification message
1999
 * @len: length of the data
2000
 *
2001
 * bgp_error() sends a notification packet to tell the other side that a protocol
2002
 * error has occurred (including the data considered erroneous if possible) and
2003
 * closes the connection.
2004
 */
2005
void
2006
bgp_error(struct bgp_conn *c, uint code, uint subcode, byte *data, int len)
2007
{
2008
    struct bgp_proto *p = c->bgp;
2009

    
2010
    if (c->state == BS_CLOSE)
2011
        return;
2012

    
2013
    bgp_log_error(p, BE_BGP_TX, "Error", code, subcode, data, ABS(len));
2014
    bgp_store_error(p, c, BE_BGP_TX, (code << 16) | subcode);
2015
    bgp_conn_enter_close_state(c);
2016

    
2017
    c->notify_code = code;
2018
    c->notify_subcode = subcode;
2019
    c->notify_data = data;
2020
    c->notify_size = (len > 0) ? len : 0;
2021
    bgp_schedule_packet(c, NULL, PKT_NOTIFICATION);
2022

    
2023
    if (code != 6)
2024
    {
2025
        bgp_update_startup_delay(p);
2026
        bgp_stop(p, 0, NULL, 0);
2027
    }
2028
}
2029

    
2030
/**
2031
 * bgp_store_error - store last error for status report
2032
 * @p: BGP instance
2033
 * @c: connection
2034
 * @class: error class (BE_xxx constants)
2035
 * @code: error code (class specific)
2036
 *
2037
 * bgp_store_error() decides whether given error is interesting enough
2038
 * and store that error to last_error variables of @p
2039
 */
2040
void
2041
bgp_store_error(struct bgp_proto *p, struct bgp_conn *c, u8 class, u32 code)
2042
{
2043
    /* During PS_UP, we ignore errors on secondary connection */
2044
    if ((p->p.proto_state == PS_UP) && c && (c != p->conn))
2045
        return;
2046

    
2047
    /* During PS_STOP, we ignore any errors, as we want to report
2048
     * the error that caused transition to PS_STOP
2049
     */
2050
    if (p->p.proto_state == PS_STOP)
2051
        return;
2052

    
2053
    p->last_error_class = class;
2054
    p->last_error_code = code;
2055
}
2056

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

    
2062
static const char *
2063
bgp_last_errmsg(struct bgp_proto *p)
2064
{
2065
    switch (p->last_error_class)
2066
    {
2067
        case BE_MISC:
2068
            return bgp_misc_errors[p->last_error_code];
2069
        case BE_SOCKET:
2070
            return (p->last_error_code == 0) ? "Connection closed" : strerror(p->last_error_code);
2071
        case BE_BGP_RX:
2072
        case BE_BGP_TX:
2073
            return bgp_error_dsc(p->last_error_code >> 16, p->last_error_code & 0xFF);
2074
        case BE_AUTO_DOWN:
2075
            return bgp_auto_errors[p->last_error_code];
2076
        default:
2077
            return "";
2078
    }
2079
}
2080

    
2081
static const char *
2082
bgp_state_dsc(struct bgp_proto *p)
2083
{
2084
    if (p->p.proto_state == PS_DOWN)
2085
        return "Down";
2086

    
2087
    int state = MAX(p->incoming_conn.state, p->outgoing_conn.state);
2088
    if ((state == BS_IDLE) && (p->start_state >= BSS_CONNECT) && p->cf->passive)
2089
        return "Passive";
2090

    
2091
    return bgp_state_names[state];
2092
}
2093

    
2094
static void
2095
bgp_get_status(struct proto *P, byte *buf)
2096
{
2097
    struct bgp_proto *p = (struct bgp_proto *) P;
2098

    
2099
    const char *err1 = bgp_err_classes[p->last_error_class];
2100
    const char *err2 = bgp_last_errmsg(p);
2101

    
2102
    if (P->proto_state == PS_DOWN)
2103
        bsprintf(buf, "%s%s", err1, err2);
2104
    else
2105
        bsprintf(buf, "%-14s%s%s", bgp_state_dsc(p), err1, err2);
2106
}
2107

    
2108
static void
2109
bgp_show_afis(int code, char *s, u32 *afis, uint count)
2110
{
2111
    buffer b;
2112
    LOG_BUFFER_INIT(b);
2113

    
2114
    buffer_puts(&b, s);
2115

    
2116
    for (u32 *af = afis; af < (afis + count); af++)
2117
    {
2118
        const struct bgp_af_desc *desc = bgp_get_af_desc(*af);
2119
        if (desc)
2120
            buffer_print(&b, " %s", desc->name);
2121
        else
2122
            buffer_print(&b, " <%u/%u>", BGP_AFI(*af), BGP_SAFI(*af));
2123
    }
2124

    
2125
    if (b.pos == b.end)
2126
        strcpy(b.end - 32, " ... <too long>");
2127

    
2128
    cli_msg(code, b.start);
2129
}
2130

    
2131
static void
2132
bgp_show_capabilities(struct bgp_proto *p UNUSED, struct bgp_caps *caps)
2133
{
2134
    struct bgp_af_caps *ac;
2135
    uint any_mp_bgp = 0;
2136
    uint any_gr_able = 0;
2137
    uint any_add_path = 0;
2138
    uint any_ext_next_hop = 0;
2139
    u32 *afl1 = alloca(caps->af_count * sizeof(u32));
2140
    u32 *afl2 = alloca(caps->af_count * sizeof(u32));
2141
    uint afn1, afn2;
2142

    
2143
    WALK_AF_CAPS(caps, ac)
2144
    {
2145
        any_mp_bgp |= ac->ready;
2146
        any_gr_able |= ac->gr_able;
2147
        any_add_path |= ac->add_path;
2148
        any_ext_next_hop |= ac->ext_next_hop;
2149
    }
2150

    
2151
    if (any_mp_bgp)
2152
    {
2153
        cli_msg(-1006, "      Multiprotocol");
2154

    
2155
        afn1 = 0;
2156
        WALK_AF_CAPS(caps, ac)
2157
            if (ac->ready)
2158
                afl1[afn1++] = ac->afi;
2159

    
2160
        bgp_show_afis(-1006, "        AF announced:", afl1, afn1);
2161
    }
2162

    
2163
    if (caps->route_refresh)
2164
        cli_msg(-1006, "      Route refresh");
2165

    
2166
    if (any_ext_next_hop)
2167
    {
2168
        cli_msg(-1006, "      Extended next hop");
2169

    
2170
        afn1 = 0;
2171
        WALK_AF_CAPS(caps, ac)
2172
            if (ac->ext_next_hop)
2173
                afl1[afn1++] = ac->afi;
2174

    
2175
        bgp_show_afis(-1006, "        IPv6 nexthop:", afl1, afn1);
2176
    }
2177

    
2178
    if (caps->ext_messages)
2179
        cli_msg(-1006, "      Extended message");
2180

    
2181
    if (caps->gr_aware)
2182
        cli_msg(-1006, "      Graceful restart");
2183

    
2184
    if (any_gr_able)
2185
    {
2186
        /* Continues from gr_aware */
2187
        cli_msg(-1006, "        Restart time: %u", caps->gr_time);
2188
        if (caps->gr_flags & BGP_GRF_RESTART)
2189
            cli_msg(-1006, "        Restart recovery");
2190

    
2191
        afn1 = afn2 = 0;
2192
        WALK_AF_CAPS(caps, ac)
2193
        {
2194
            if (ac->gr_able)
2195
                afl1[afn1++] = ac->afi;
2196

    
2197
            if (ac->gr_af_flags & BGP_GRF_FORWARDING)
2198
                afl2[afn2++] = ac->afi;
2199
        }
2200

    
2201
        bgp_show_afis(-1006, "        AF supported:", afl1, afn1);
2202
        bgp_show_afis(-1006, "        AF preserved:", afl2, afn2);
2203
    }
2204

    
2205
    if (caps->as4_support)
2206
        cli_msg(-1006, "      4-octet AS numbers");
2207

    
2208
    if (any_add_path)
2209
    {
2210
        cli_msg(-1006, "      ADD-PATH");
2211

    
2212
        afn1 = afn2 = 0;
2213
        WALK_AF_CAPS(caps, ac)
2214
        {
2215
            if (ac->add_path & BGP_ADD_PATH_RX)
2216
                afl1[afn1++] = ac->afi;
2217

    
2218
            if (ac->add_path & BGP_ADD_PATH_TX)
2219
                afl2[afn2++] = ac->afi;
2220
        }
2221

    
2222
        bgp_show_afis(-1006, "        RX:", afl1, afn1);
2223
        bgp_show_afis(-1006, "        TX:", afl2, afn2);
2224
    }
2225

    
2226
    if (caps->enhanced_refresh)
2227
        cli_msg(-1006, "      Enhanced refresh");
2228
}
2229

    
2230
static void
2231
bgp_show_proto_info(struct proto *P)
2232
{
2233
    struct bgp_proto *p = (struct bgp_proto *) P;
2234

    
2235
    cli_msg(-1006, "  BGP state:          %s", bgp_state_dsc(p));
2236
    cli_msg(-1006, "    Neighbor address: %I%J", p->cf->remote_ip, p->cf->iface);
2237
    cli_msg(-1006, "    Neighbor AS:      %u", p->remote_as);
2238

    
2239
    if (p->gr_active_num)
2240
        cli_msg(-1006, "    Neighbor graceful restart active");
2241

    
2242
    if (P->proto_state == PS_START)
2243
    {
2244
        struct bgp_conn *oc = &p->outgoing_conn;
2245

    
2246
        if ((p->start_state < BSS_CONNECT) &&
2247
            (tm_active(p->startup_timer)))
2248
            cli_msg(-1006, "    Error wait:       %t/%u",
2249
                    tm_remains(p->startup_timer), p->startup_delay);
2250

    
2251
        if ((oc->state == BS_ACTIVE) &&
2252
            (tm_active(oc->connect_timer)))
2253
            cli_msg(-1006, "    Connect delay:    %t/%u",
2254
                    tm_remains(oc->connect_timer), p->cf->connect_delay_time);
2255

    
2256
        if (p->gr_active_num && tm_active(p->gr_timer))
2257
            cli_msg(-1006, "    Restart timer:    %t/-",
2258
                    tm_remains(p->gr_timer));
2259
    }
2260
    else if (P->proto_state == PS_UP)
2261
    {
2262
        cli_msg(-1006, "    Neighbor ID:      %R", p->remote_id);
2263
        cli_msg(-1006, "    Local capabilities");
2264
        bgp_show_capabilities(p, p->conn->local_caps);
2265
        cli_msg(-1006, "    Neighbor capabilities");
2266
        bgp_show_capabilities(p, p->conn->remote_caps);
2267
        cli_msg(-1006, "    Session:          %s%s%s%s%s",
2268
                p->is_internal ? "internal" : "external",
2269
                p->cf->multihop ? " multihop" : "",
2270
                p->rr_client ? " route-reflector" : "",
2271
                p->rs_client ? " route-server" : "",
2272
                p->as4_session ? " AS4" : "");
2273
        cli_msg(-1006, "    Source address:   %I", p->source_addr);
2274
        cli_msg(-1006, "    Hold timer:       %t/%u",
2275
                tm_remains(p->conn->hold_timer), p->conn->hold_time);
2276
        cli_msg(-1006, "    Keepalive timer:  %t/%u",
2277
                tm_remains(p->conn->keepalive_timer), p->conn->keepalive_time);
2278
    }
2279

    
2280
    if ((p->last_error_class != BE_NONE) &&
2281
        (p->last_error_class != BE_MAN_DOWN))
2282
    {
2283
        const char *err1 = bgp_err_classes[p->last_error_class];
2284
        const char *err2 = bgp_last_errmsg(p);
2285
        cli_msg(-1006, "    Last error:       %s%s", err1, err2);
2286
    }
2287

    
2288
    {
2289
        struct bgp_channel *c;
2290
        WALK_LIST(c, p->p.channels)
2291
        {
2292
            channel_show_info(&c->c);
2293

    
2294
            if (c->c.channel_state == CS_UP)
2295
            {
2296
                if (ipa_zero(c->link_addr))
2297
                    cli_msg(-1006, "    BGP Next hop:   %I", c->next_hop_addr);
2298
                else
2299
                    cli_msg(-1006, "    BGP Next hop:   %I %I", c->next_hop_addr, c->link_addr);
2300
            }
2301

    
2302
            if (c->igp_table_ip4)
2303
                cli_msg(-1006, "    IGP IPv4 table: %s", c->igp_table_ip4->name);
2304

    
2305
            if (c->igp_table_ip6)
2306
                cli_msg(-1006, "    IGP IPv6 table: %s", c->igp_table_ip6->name);
2307
        }
2308
    }
2309
}
2310

    
2311
// Next three function could be usefull in some situations
2312
/*void
2313
channel_show_info_mine(struct channel *c)
2314
{
2315
    log(L_INFO "  Channel %s", c->name);
2316
    //log(L_INFO "    State:          %s", c_states[c->channel_state]);
2317
    log(L_INFO "    Table:          %s", c->table->name);
2318
    log(L_INFO "    Preference:     %d", c->preference);
2319
    log(L_INFO "    Input filter:   %s", filter_name(c->in_filter));
2320
    log(L_INFO "    Output filter:  %s", filter_name(c->out_filter));
2321

2322
    ///*if (graceful_restart_state == GRS_ACTIVE)
2323
        log(L_INFO "    GR recovery:   %s%s",
2324
                c->gr_lock ? " pending" : "",
2325
                c->gr_wait ? " waiting" : "");//
2326

2327
    //channel_show_limit(&c->rx_limit, "Receive limit:");
2328
    //channel_show_limit(&c->in_limit, "Import limit:");
2329
    //channel_show_limit(&c->out_limit, "Export limit:");
2330

2331
    //if (c->channel_state != CS_DOWN)
2332
    //    channel_show_stats(c);
2333
}*/
2334

    
2335
/*static void
2336
bgp_show_capabilities_mine(struct bgp_proto *p UNUSED, struct bgp_caps *caps)
2337
{
2338
    struct bgp_af_caps *ac;
2339
    uint any_mp_bgp = 0;
2340
    uint any_gr_able = 0;
2341
    uint any_add_path = 0;
2342
    uint any_ext_next_hop = 0;
2343
    u32 *afl1 = alloca(caps->af_count * sizeof(u32));
2344
    u32 *afl2 = alloca(caps->af_count * sizeof(u32));
2345
    uint afn1, afn2;
2346

2347
    WALK_AF_CAPS(caps, ac)
2348
    {
2349
        any_mp_bgp |= ac->ready;
2350
        any_gr_able |= ac->gr_able;
2351
        any_add_path |= ac->add_path;
2352
        any_ext_next_hop |= ac->ext_next_hop;
2353
    }
2354

2355
    if (any_mp_bgp)
2356
    {
2357
        log(L_INFO "      Multiprotocol");
2358

2359
        afn1 = 0;
2360
        WALK_AF_CAPS(caps, ac)
2361
            if (ac->ready)
2362
                afl1[afn1++] = ac->afi;
2363

2364
        //bgp_show_afis(-1006, "        AF announced:", afl1, afn1);
2365
    }
2366

2367
    if (caps->route_refresh)
2368
        log(L_INFO "      Route refresh");
2369

2370
    if (any_ext_next_hop)
2371
    {
2372
        log(L_INFO "      Extended next hop");
2373

2374
        afn1 = 0;
2375
        WALK_AF_CAPS(caps, ac)
2376
            if (ac->ext_next_hop)
2377
                afl1[afn1++] = ac->afi;
2378

2379
        //bgp_show_afis(-1006, "        IPv6 nexthop:", afl1, afn1);
2380
    }
2381

2382
    if (caps->ext_messages)
2383
        log(L_INFO "      Extended message");
2384

2385
    if (caps->gr_aware)
2386
        log(L_INFO "      Graceful restart");
2387

2388
    if (any_gr_able)
2389
    {
2390
        // Continues from gr_aware
2391
        log(L_INFO "        Restart time: %u", caps->gr_time);
2392
        if (caps->gr_flags & BGP_GRF_RESTART)
2393
            log(L_INFO "        Restart recovery");
2394

2395
        afn1 = afn2 = 0;
2396
        WALK_AF_CAPS(caps, ac)
2397
        {
2398
            if (ac->gr_able)
2399
                afl1[afn1++] = ac->afi;
2400

2401
            if (ac->gr_af_flags & BGP_GRF_FORWARDING)
2402
                afl2[afn2++] = ac->afi;
2403
        }
2404

2405
        //bgp_show_afis(-1006, "        AF supported:", afl1, afn1);
2406
        //bgp_show_afis(-1006, "        AF preserved:", afl2, afn2);
2407
    }
2408

2409
    if (caps->as4_support)
2410
        log(L_INFO "      4-octet AS numbers");
2411

2412
    if (any_add_path)
2413
    {
2414
        log(L_INFO "      ADD-PATH");
2415

2416
        afn1 = afn2 = 0;
2417
        WALK_AF_CAPS(caps, ac)
2418
        {
2419
            if (ac->add_path & BGP_ADD_PATH_RX)
2420
                afl1[afn1++] = ac->afi;
2421

2422
            if (ac->add_path & BGP_ADD_PATH_TX)
2423
                afl2[afn2++] = ac->afi;
2424
        }
2425

2426
        //bgp_show_afis(-1006, "        RX:", afl1, afn1);
2427
        //bgp_show_afis(-1006, "        TX:", afl2, afn2);
2428
    }
2429

2430
    if (caps->enhanced_refresh)
2431
        log(L_INFO "      Enhanced refresh");
2432
}
2433
*/
2434

    
2435
/*void
2436
bgp_show_proto_info_mine(struct bgp_proto *P)
2437
{
2438
    struct bgp_proto *p = P;
2439

2440
    log(L_INFO "  BGP state:          %s", bgp_state_dsc(p));
2441
    log(L_INFO "    Neighbor address: %I%J", p->cf->remote_ip, p->cf->iface);
2442
    log(L_INFO "    Neighbor AS:      %u", p->remote_as);
2443

2444
    if (p->gr_active_num)
2445
        log(L_INFO "    Neighbor graceful restart active");
2446

2447
    if (P->p.proto_state == PS_START)
2448
    {
2449
        struct bgp_conn *oc = &p->outgoing_conn;
2450

2451
        if ((p->start_state < BSS_CONNECT) &&
2452
            (tm_active(p->startup_timer)))
2453
            log(L_INFO "    Error wait:       %t/%u",
2454
                    tm_remains(p->startup_timer), p->startup_delay);
2455

2456
        if ((oc->state == BS_ACTIVE) &&
2457
            (tm_active(oc->connect_timer)))
2458
            log(L_INFO "    Connect delay:    %t/%u",
2459
                    tm_remains(oc->connect_timer), p->cf->connect_delay_time);
2460

2461
        if (p->gr_active_num && tm_active(p->gr_timer))
2462
            log(L_INFO "    Restart timer:    %t/-",
2463
                    tm_remains(p->gr_timer));
2464
    }
2465
    else if (P->p.proto_state == PS_UP)
2466
    {
2467
        log(L_INFO "    Neighbor ID:      %R", p->remote_id);
2468
        log(L_INFO "    Local capabilities");
2469
        bgp_show_capabilities_mine(p, p->conn->local_caps);
2470
        log(L_INFO "    Neighbor capabilities");
2471
        bgp_show_capabilities_mine(p, p->conn->remote_caps);
2472
        log(L_INFO "    Session:          %s%s%s%s%s",
2473
                p->is_internal ? "internal" : "external",
2474
                p->cf->multihop ? " multihop" : "",
2475
                p->rr_client ? " route-reflector" : "",
2476
                p->rs_client ? " route-server" : "",
2477
                p->as4_session ? " AS4" : "");
2478
        log(L_INFO "    Source address:   %I", p->source_addr);
2479
        log(L_INFO "    Hold timer:       %t/%u",
2480
                tm_remains(p->conn->hold_timer), p->conn->hold_time);
2481
        log(L_INFO "    Keepalive timer:  %t/%u",
2482
                tm_remains(p->conn->keepalive_timer), p->conn->keepalive_time);
2483
    }
2484

2485
    if ((p->last_error_class != BE_NONE) &&
2486
        (p->last_error_class != BE_MAN_DOWN))
2487
    {
2488
        const char *err1 = bgp_err_classes[p->last_error_class];
2489
        const char *err2 = bgp_last_errmsg(p);
2490
        log(L_INFO "    Last error:       %s%s", err1, err2);
2491
    }
2492

2493
    {
2494
        struct bgp_channel *c;
2495
        WALK_LIST(c, p->p.channels)
2496
        {
2497
            channel_show_info_mine(&c->c);
2498

2499
            if (c->c.channel_state == CS_UP)
2500
            {
2501
                if (ipa_zero(c->link_addr))
2502
                    log(L_INFO "    BGP Next hop:   %I", c->next_hop_addr);
2503
                else
2504
                    log(L_INFO "    BGP Next hop:   %I %I", c->next_hop_addr, c->link_addr);
2505
            }
2506

2507
            if (c->igp_table_ip4)
2508
                log(L_INFO "    IGP IPv4 table: %s", c->igp_table_ip4->name);
2509

2510
            if (c->igp_table_ip6)
2511
                log(L_INFO "    IGP IPv6 table: %s", c->igp_table_ip6->name);
2512
        }
2513
    }
2514
}*/
2515

    
2516
struct channel_class channel_bgp = {
2517
        .channel_size =        sizeof(struct bgp_channel),
2518
        .config_size =        sizeof(struct bgp_channel_config),
2519
        .init =                bgp_channel_init,
2520
        .start =                bgp_channel_start,
2521
        .shutdown =                bgp_channel_shutdown,
2522
        .cleanup =                bgp_channel_cleanup,
2523
        .reconfigure =        bgp_channel_reconfigure,
2524
};
2525

    
2526
struct protocol proto_bgp = {
2527
        .name =                 "BGP",
2528
        .template =                 "bgp%d",
2529
        .attr_class =         EAP_BGP,
2530
        .preference =         DEF_PREF_BGP,
2531
        .channel_mask =        NB_IP | NB_VPN | NB_FLOW,
2532
        .proto_size =                sizeof(struct bgp_proto),
2533
        .config_size =        sizeof(struct bgp_config),
2534
        .postconfig =                bgp_postconfig,
2535
        .init =                 bgp_init,
2536
        .start =                 bgp_start,
2537
        .shutdown =                 bgp_shutdown,
2538
        .reconfigure =         bgp_reconfigure,
2539
        .copy_config =         bgp_copy_config,
2540
        .get_status =         bgp_get_status,
2541
        .get_attr =                 bgp_get_attr,
2542
        .get_route_info =         bgp_get_route_info,
2543
        .show_proto_info =         bgp_show_proto_info
2544
};