2 import java.util.Vector;
3 import java.nio.ByteBuffer;
4 import javax.crypto.Mac;
5 import java.util.Arrays;
7 class Slot implements Liveness {
8 static final int SLOT_SIZE=2048;
9 static final int RESERVED_SPACE=64;
10 static final int HMAC_SIZE=32;
13 private byte[] prevhmac;
15 private long machineid;
16 private Vector<Entry> entries;
17 private int livecount;
18 private boolean seqnumlive;
19 private int freespace;
21 Slot(long _seqnum, long _machineid, byte[] _prevhmac, byte[] _hmac) {
26 entries=new Vector<Entry>();
29 freespace = SLOT_SIZE - getBaseSize();
32 Slot(long _seqnum, long _machineid, byte[] _prevhmac) {
33 this(_seqnum, _machineid, _prevhmac, new byte[HMAC_SIZE]);
40 byte[] getPrevHMAC() {
44 void addEntry(Entry e) {
47 freespace -= e.getSize();
50 boolean hasSpace(Entry e) {
51 int newfreespace = freespace - e.getSize();
52 return newfreespace > RESERVED_SPACE;
55 boolean canFit(Entry e) {
56 int newfreespace = freespace - e.getSize();
57 return newfreespace >= 0;
60 Vector<Entry> getEntries() {
64 static Slot decode(byte[] array, Mac mac) {
65 mac.update(array, HMAC_SIZE, array.length-HMAC_SIZE);
66 byte[] realmac=mac.doFinal();
68 ByteBuffer bb=ByteBuffer.wrap(array);
69 byte[] hmac=new byte[HMAC_SIZE];
70 byte[] prevhmac=new byte[HMAC_SIZE];
73 if (!Arrays.equals(realmac, hmac))
74 throw new Error("Server Error: Invalid HMAC! Potential Attack!");
76 long seqnum=bb.getLong();
77 long machineid=bb.getLong();
78 int numentries=bb.getInt();
79 Slot slot=new Slot(seqnum, machineid, prevhmac, hmac);
81 for(int i=0; i<numentries; i++) {
82 slot.addEntry(Entry.decode(slot, bb));
88 byte[] encode(Mac mac) {
89 byte[] array=new byte[SLOT_SIZE];
90 ByteBuffer bb=ByteBuffer.wrap(array);
91 bb.position(HMAC_SIZE); //Leave space for the HMACs
94 bb.putLong(machineid);
95 bb.putInt(entries.size());
96 for(Entry entry:entries) {
100 mac.update(array, HMAC_SIZE, array.length-HMAC_SIZE);
101 byte[] realmac=mac.doFinal();
108 return 2*HMAC_SIZE+2*Long.BYTES+Integer.BYTES;
111 Vector<Entry> getLiveEntries() {
112 Vector<Entry> liveEntries=new Vector<Entry>();
113 for(Entry entry: entries)
115 liveEntries.add(entry);
118 liveEntries.add(new LastMessage(this, machineid, seqnum));
123 long getSequenceNumber() {
127 long getMachineID() {
136 decrementLiveCount();
140 void decrementLiveCount() {
145 return livecount > 0;
148 public String toString() {
149 return "<"+getSequenceNumber()+", "+new String(getBytes())+">";