summaryrefslogtreecommitdiff
path: root/src/main/java/com/lumaserv/bgp/BGPSession.java
blob: bd40c13af04bbde9f1f6de3f504cf3555b7d3790 (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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package com.lumaserv.bgp;

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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;

public class BGPSession implements Runnable {

    @Getter
    final BGPServer server;
    @Getter
    final BGPSessionConfiguration configuration;
    final String host;
    final int port;
    Socket socket;
    InputStream inputStream;
    OutputStream outputStream;
    @Getter
    boolean closed;
    boolean outgoing;
    @Getter
    BGPFsm fsm;
    Thread thread;
    boolean isAdvAS4Capability;
    @Getter
    boolean isAS4Capability;
    @Getter
    byte[] remoteIdentifier;

    public BGPSession(BGPServer server, Socket socket, BGPSessionConfiguration configuration) throws IOException {
        this.server = server;
        this.configuration = configuration;
        this.socket = socket;
        this.inputStream = socket.getInputStream();
        this.outputStream = socket.getOutputStream();
        this.fsm = new BGPFsm(this);
        this.host = null;
        this.port = -1;
    }

    public BGPSession(BGPServer server, BGPSessionConfiguration configuration, String host, int port) {
        this.server = server;
        this.configuration = configuration;
        this.fsm = new BGPFsm(this);
        this.host = host;
        this.port = port;
    }

    public InetAddress getInetAddress() {
        return socket.getInetAddress();
    }

    public InetAddress getLocalAddress() {
        return socket.getLocalAddress();
    }

    protected void finalize() throws Throwable {
        System.out.println("Finalize BGPSession");
        super.finalize();
    }

    public void cleanup() {
        fsm.cleanup();
    }

    public void automaticStop() {
        fsm.getCurrentState().automaticStop();
    }

    public void keepAlive() {
        try {
            outputStream.write(new BGPPacket().setType(BGPPacket.Type.KEEPALIVE).setMessage(new byte[0]).build());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handle(BGPPacket packet) {
        switch (packet.getType()) {
            case NOTIFICATION:
                BGPNotification notif = new BGPNotification(packet.getMessage());
                if (notif.getMajorErrorCode() == BGPNotification.Error.MESSAGE_HEADER_ERROR.getCode() &&
                    notif.getMinorErrorCode() == BGPNotification.OpenMessageError.UNSUPPORTED_VERSION_NUMBER.getCode())
                    fsm.getCurrentState().notifMsgVerErr(notif);
                else
                    fsm.getCurrentState().notifMsg(notif);
                break;
            case KEEPALIVE:
                fsm.getCurrentState().keepAliveMsg();
                //keepAlive();
                break;
            case OPEN:
                BGPOpen open = new BGPOpen(packet.getMessage());
                if (server.hasCollided(this, open)) {
                    BGPNotification notification = new BGPNotification()
                        .setMajorErrorCode(BGPNotification.Error.CEASE.getCode());
                    try {
                        sendNotification(notification);
                    } catch(IOException ex) {
                    }
                    dropConnection();
                    cleanup();
                } else {
                    isAS4Capability = isAdvAS4Capability && open.getAS4Capability().isPresent();
                    remoteIdentifier = open.getIdentifier();
                    fsm.getCurrentState().openMsg(open);
                }
                break;
            case UPDATE: {
                BGPUpdate update = new BGPUpdate(this, packet.getMessage());
                fsm.getCurrentState().updateMsg(update);
                configuration.getListener().onUpdate(this, update);
                break;
            }
        }
    }

    public void startIncoming() {
        outgoing = false;
        thread = new Thread(this);
        thread.start();
    }

    public void startOutgoing() {
        outgoing = true;
        thread = new Thread(this);
        thread.start();
    }

    void sendNotification(BGPNotification notification) throws IOException {
        outputStream.write(new BGPPacket().setType(BGPPacket.Type.NOTIFICATION).setMessage(notification.build()).build());
    }

    void sendOpen(BGPOpen request) throws IOException {
        isAdvAS4Capability = request.getAS4Capability().isPresent();
        outputStream.write(new BGPPacket().setType(BGPPacket.Type.OPEN).setMessage(request.build()).build());
System.out.println("Sent open");
    }

    void sendOpen() throws IOException {
        BGPOpen.Capabilities caps = new BGPOpen.Capabilities();
        caps.getCapabilities().add(new BGPOpen.MultiprotocolExtensionCapability(AFI.IPV4.getValue(), SAFI.UNICAST.getValue()));
        caps.getCapabilities().add(new BGPOpen.MultiprotocolExtensionCapability(AFI.IPV6.getValue(), SAFI.UNICAST.getValue()));
        caps.getCapabilities().add(new BGPOpen.AS4Capability(configuration.getLocalAs()));

        BGPOpen request = new BGPOpen()
            .setHoldTime(BGPFsm.CONFIG_HOLD_TIME)
            .setVersion(BGPFsm.CONFIG_VERSION)
            .setIdentifier(configuration.getLocalIdentifier());
        if ((configuration.getLocalAs() & 0xFFFFFFFFL) < 0xFFFF)
            request.setAsn(configuration.getLocalAs());
        request.getOptionalParameters().add(caps);

        sendOpen(request);
    }

    public void sendUpdate(BGPUpdate request) throws IOException {
        if (fsm.getCurrentState() != fsm.ESTABLISHED) {
            throw new RuntimeException("Can't send UPDATE in state " + fsm.getCurrentState());
        }
        outputStream.write(new BGPPacket().setType(BGPPacket.Type.UPDATE).setMessage(request.build()).build());
        fsm.setKeepAliveTimer();
    }

    public void retryConnection() {
        if (!socket.isConnected()) {
            try {
                socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
        }
    }

    public void dropConnection() {
        closed = true;
        try {
            if (outputStream != null)
                outputStream.close();
            if (inputStream != null)
                inputStream.close();
            socket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    public void run() {
        try {
            if (socket == null) {
                while (true) {
                    try {
                        System.out.println("Outgoing: " + host + ":" + port);
                        socket = configuration.getSocketFactory().createSocket(host, port);
                        break;
                    } catch(IOException ex) {
                        System.out.println("Exception: " + ex);
                        if (closed) {
                            throw new IOException("Closed", ex);
                        }
                    }
                }
                System.out.println("Outgoing accepted: " + socket.isConnected());
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
                fsm.getCurrentState().tcpCRAcked();
            } else {
                System.out.println("Incoming");
                fsm.getCurrentState().tcpConnectionConfirmed();
            }
            while (!closed) {
                handle(BGPPacket.read(inputStream));
            }
            System.out.println("Closed!");
        } catch (IOException ex) {
            if (!closed) {
                fsm.getCurrentState().tcpConnectionFails();
            }
            closed = true;
            configuration.getListener().onClose(this);
        }
    }
}