package com.lumaserv.bgp.protocol; import com.lumaserv.bgp.protocol.DataBuilder; import com.lumaserv.bgp.protocol.message.BGPOpen; import com.lumaserv.bgp.protocol.message.BGPUpdate; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; @Setter @Getter @NoArgsConstructor public class BGPPacket { Type type; DataBuilder message; public BGPPacket(ByteBuffer packet) { type = Type.fromValue(packet.get()); switch (type) { case OPEN: message = new BGPOpen(packet); break; case UPDATE: message = new BGPUpdate(packet); break; default: System.out.println("type: " + type); break; } } public byte[] build() { ByteBuffer buf = ByteBuffer.allocate(4096).order(ByteOrder.BIG_ENDIAN); // Maximum BGP message size for (int i=0; i<16; i++) buf.put((byte) 0xFF); buf.putShort((short)19); // Length without message payload buf.put(type.getValue()); if (message != null) { message.build(buf); buf.putShort(16, (short)buf.position()); // Set length } byte[] packet = new byte[buf.position()]; buf.position(0); buf.get(packet); // TODO is working? return packet; } public static BGPPacket read(InputStream stream) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4096).order(ByteOrder.BIG_ENDIAN); int value; for(int i=0; i<18; i++) { value = stream.read(); if(value == -1) throw new IOException("Unexpected end of stream"); buf.put((byte) value); } int length = buf.getShort(16); for(int i=18; i