summaryrefslogtreecommitdiff
path: root/src/main/java/com/lumaserv/bgp/BGPServer.java
blob: 53f8af7aabdc572b435d9897b5d10fc430324137 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package com.lumaserv.bgp;

import com.lumaserv.bgp.protocol.BGPPacket;
import com.lumaserv.bgp.protocol.message.BGPNotification;
import com.lumaserv.bgp.protocol.message.BGPOpen;
import lombok.Getter;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class BGPServer implements Runnable {

    final ServerSocket serverSocket;
    @Getter
    final List<BGPSessionConfiguration> sessionConfigurations = new ArrayList<>();
    final List<BGPSession> sessions = new ArrayList<>();

    public BGPServer() throws IOException {
        this(179);
    }

    public BGPServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    private static boolean checkEqual(byte[] a, byte[] b) {
        if(a == b)
            return true;
        if(a == null || b == null)
            return false;
        if(a.length != b.length)
            return false;
        for(int i=0; i<a.length; i++) {
            if(a[i] != b[i])
                return false;
        }
        return true;
    }

    public boolean hasCollided(BGPSession session, BGPOpen msg) {
        for (BGPSession otherSession : sessions) {
            BGPFsm fsm = otherSession.getFsm();
            BGPFsm.State state = fsm.getCurrentState();

            // May examine OPEN_SENT
            if (state == fsm.OPEN_SENT
                && otherSession.getConfiguration() == null)
                continue;

            // Cannot detect collision
            if (state == fsm.IDLE
                || state == fsm.CONNECT
                || state == fsm.ACTIVE)
                continue;

            // Detect collision
            if (session.getInetAddress() != otherSession.getLocalAddress()
                || session.getLocalAddress() != otherSession.getInetAddress())
                continue;

            // Collision!
            if (state == fsm.ESTABLISHED) {
                // Close new connection
                sessions.remove(session);
                return true;
            }

            byte[] remoteIdentifier;
            byte[] localIdentifier = session.getConfiguration()
                .getLocalIdentifier();

            if (state == fsm.OPEN_SENT) {
                remoteIdentifier = otherSession.getConfiguration()
                    .getRemoteIdentifier();
            } else { // state == BGPFsm.OPEN_CONFIRM
                remoteIdentifier = otherSession.getRemoteIdentifier();
            }

            boolean isLocalIdLess = false;

            // Compare integer stored in network byte order
            for (int i=0; i < 4; i++) {
                if (localIdentifier[i] < remoteIdentifier[i]) {
                    isLocalIdLess = true;
                    break;
                }
            }

            if (isLocalIdLess) {
                // Close existing connection
                BGPNotification notification = new BGPNotification()
                    .setMajorErrorCode(BGPNotification.Error.CEASE.getCode());
                try {
                    otherSession.sendNotification(notification);
                } catch(IOException ex) {
                }
                sessions.remove(otherSession);
                otherSession.dropConnection();
                otherSession.cleanup();
                // Accept new connection
                return false;
            } else {
                // Close new connection
                sessions.remove(session);
                return true;
            }
        }

        return false;
    }

    public void run() {
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                System.out.println("Accept");

                BGPSessionConfiguration config = sessionConfigurations.stream()
                        .filter(c -> socket.getInetAddress().equals(c.getRemoteAddr()))
                        .findFirst()
                        .orElse(null);
                System.out.println("Config: " + config);
                if(config == null) {
                    System.out.println("Peer not found:" + socket.getInetAddress());
                    socket.close();
                    continue;
                }

                BGPSession session = new BGPSession(this, socket, config);
                sessions.add(session);
                session.getFsm().getCurrentState().automaticStartPassive();

                // System.out.println("tcpConnectionConfirmed in " + fsm.getCurrentState());
                // fsm.getCurrentState().tcpConnectionConfirmed();
            } catch (IOException ex) {
                if (serverSocket.isClosed())
                    break;
                ex.printStackTrace();
            }
        }
    }

    public boolean connect(BGPSessionConfiguration config, String host) {
        return connect(config, host, 179);
    }

    public boolean connect(BGPSessionConfiguration config, String host, int port) {
        for (BGPSession session : sessions) {
            if (session.getConfiguration().equals(config)) {
                // Already connected
                return false;
            }
        }

        BGPSession session = new BGPSession(this, config, host, port);
        sessions.add(session);
        session.getFsm().getCurrentState().automaticStart();
        return true;
    }

    public void shutdown() {
        for(BGPSession session : sessions) {
            session.automaticStop();
            session.cleanup();
        }
        sessions.clear();
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch(IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}