Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (74.4 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
                if (keyValue == conn->bgp->remote_as) {
458
                    log(L_INFO "REMOVE LOADIN 2 %d %d", keyValue, conn->bgp->remote_as);
459
                    map_remove(RTmap_element->loadin, keyLoadInmap_RTmap);
460
                    iterLoadInmap_RTmap = map_iter(RTmap_element->loadin);
461
                }
462
            }
463
            //map_deinit(&RTmap_element->loadin);
464

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

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

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

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

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

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

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

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

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

    
535
    p->last_proto_error = current_time();
536

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
637
    conn->state = new_state;
638
}
639

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

    
647
static const struct bgp_af_caps dummy_af_caps = { };
648

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
819
    p->gr_active_num = 0;
820

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
907

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

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

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

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

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

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

    
951

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

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

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

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

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

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

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

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

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

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

    
1016
    bgp_conn_enter_idle_state(conn);
1017
}
1018

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1175
    return NULL;
1176
}
1177

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1288
    bgp_initiate(p);
1289
}
1290

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1431

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

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

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

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

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

    
1464
    p->neigh = n;
1465

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

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

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

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

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

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

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

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

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

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

    
1527
    return PS_START;
1528
}
1529

    
1530
extern int proto_restart;
1531

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1642
    return P;
1643
}
1644

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1761
    return NULL;
1762
}
1763

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

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

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

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

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

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

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

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

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

    
1804

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

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

    
1813

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

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

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

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

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

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

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

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

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

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

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

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

    
1851

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1950

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

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

    
1958
    return same;
1959
}
1960

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

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

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

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

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

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

    
1991

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

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

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

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

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

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

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

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

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

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

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

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

    
2090
    return bgp_state_names[state];
2091
}
2092

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

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

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

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

    
2113
    buffer_puts(&b, s);
2114

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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