-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBencoder2.java
More file actions
executable file
·432 lines (405 loc) · 16.2 KB
/
Copy pathBencoder2.java
File metadata and controls
executable file
·432 lines (405 loc) · 16.2 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
* RUBTClient is a BitTorrent client written at Rutgers University for
* instructional use.
* Copyright (C) 2008-2009 Robert Moore II
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.rutgers.cs.cs352.bt.util;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
import edu.rutgers.cs.cs352.bt.exceptions.BencodingException;
/**
* Parses a Bencoded byte array and returns a combination of {@code Map},
* {@code List}, {@code ByteBuffer}, and {@code Integer} objects.
*
* @author Robert Moore II
*
*/
public final class Bencoder2
{
/**
* Indicates an invalid object type or bencoded object.
*/
private static final int INVALID = -1;
/**
* Indicates that an object is a dictionary.
*/
private static final int DICTIONARY = 0;
/**
* Indicates that an object is an integer.
*/
private static final int INTEGER = 1;
/**
* Indicates an object is a byte string.
*/
private static final int STRING = 2;
/**
* Indicates an object is a list.
*/
private static final int LIST = 3;
/*
********************************************
************ CONVENIENCE METHODS ***********
********************************************
*/
/**
* Extracts the bencoded 'info' dictionary from a metainfo torrent file.
* @param torrent_file_bytes the bencoded metainfo dictionary.
* @return a {@code ByteBuffer} containing the bencoded 'info' dictionary from the metainfo file.
* @throws BencodingException if the 'info' key is not contained in the decoded dictionary.
*/
public static final ByteBuffer getInfoBytes(byte[] torrent_file_bytes) throws BencodingException
{
Object[] vals = decodeDictionary(torrent_file_bytes,0);
if(vals.length != 3 || vals[2] == null)
throw new BencodingException("Exception: No info bytes found!");
return (ByteBuffer)vals[2];
}
/*
********************************************
************ BDECODING METHODS *************
********************************************
*/
/**
* Decodes a bencoded object represented by the byte array.
* @param bencoded_bytes the bencoded data to decode.
* @return either a {@code Map}, {@code List}, {@code ByteBuffer}, or {@code Integer}.
* @throws BencodingException if the bencoded data was improperly formatted.
*/
public static final Object decode(byte[] bencoded_bytes) throws BencodingException
{
return decode(bencoded_bytes, 0)[1];
}
/**
* Decodes a bencoded object represented by the byte array, starting at the specified offset.
* @param bencoded_bytes the bencoded data to decode.
* @param offset the offset into {@code bencoded_bytes} at which to start decoding.
* @return a {@code Map}, {@code List}, {@code ByteBuffer}, or {@code Integer}.
* @throws BencodingException if the bencoded object in {@code bencoded_bytes} at offset {@code offset} is incorrectly encoded.
*/
private static final Object[] decode(byte[] bencoded_bytes, int offset) throws BencodingException
{
switch(nextObject(bencoded_bytes, offset))
{
case DICTIONARY:
return decodeDictionary(bencoded_bytes, offset);
case LIST:
return decodeList(bencoded_bytes, offset);
case INTEGER:
return decodeInteger(bencoded_bytes, offset);
case STRING:
return decodeString(bencoded_bytes, offset);
default:
return null;
}
}
/**
* Decodes an integer from the byte array.
* @param bencoded_bytes the byte array of the bencoded integer.
* @param offset the position of the 'i' indicating the start of the
* bencoded integer to be bdecoded.
* @return an <code>Object[]</code> containing an <code>Integer</code> offset and the decoded
* <code>Integer</code>, in positions 0 and 1, respectively
* @throws BencodingException if the bencoded integer in {@code bencoded_bytes} at offset {@code offset} is incorrectly encoded.
*/
private static final Object[] decodeInteger(byte[] bencoded_bytes, int offset) throws BencodingException
{
StringBuffer int_chars = new StringBuffer();
offset++;
for(; bencoded_bytes[offset] != (byte)'e' && bencoded_bytes.length > (offset); offset++)
{
if((bencoded_bytes[offset] < 48 || bencoded_bytes[offset] > 57) && bencoded_bytes[offset] != 45)
throw new BencodingException("Expected an ASCII integer character, found " + (int)bencoded_bytes[offset]);
int_chars.append((char)bencoded_bytes[offset]);
}
try
{
offset++; // Skip the 'e'
return new Object[] {new Integer(offset),new Integer(Integer.parseInt(int_chars.toString()))};
}
catch(NumberFormatException nfe)
{
throw new BencodingException("Could not parse integer at position" + offset + ".\nInvalid character at position " + offset + ".");
}
}
/**
* Decodes a byte string from the byte array
* @param bencoded_bytes the bencoded form of the byte string.
* @param offset the offset into {@code bencoded_bytes} where the byte string begins.
* @return an <code>Object[]</code> containing an <code>Integer</code> offset and the decoded
* byte string (as a {@code ByteBuffer}), in positions 0 and 1, respectively
* @throws BencodingException if the bencoded object is incorrectly encoded.
*/
private static final Object[] decodeString(byte[] bencoded_bytes, int offset) throws BencodingException
{
StringBuffer digits = new StringBuffer();
while(bencoded_bytes[offset] > '/' && bencoded_bytes[offset] < ':')
{
digits.append((char)bencoded_bytes[offset++]);
}
if(bencoded_bytes[offset] != ':')
{
throw new BencodingException("Error: Invalid character at position " + offset + ".\nExpecting ':' but found '" + (char)bencoded_bytes[offset] + "'.");
}
offset++;
int length = Integer.parseInt(digits.toString());
byte[] byte_string = new byte[length];
System.arraycopy(bencoded_bytes, offset, byte_string, 0, byte_string.length);
return new Object[] {new Integer(offset+length), ByteBuffer.wrap(byte_string)};
}
/**
* Decodes a list from the bencoded byte array.
* @param bencoded_bytes the bencoded form of the list.
* @param offset the offset into {@code bencoded_bytes} where the list begins.
* @return an <code>Object[]</code> containing an <code>Integer</code> offset and the decoded
* list (as a {@code List}), in positions 0 and 1, respectively
* @throws BencodingException if the bencoded object is incorrectly encoded.
*/
@SuppressWarnings("unchecked")
private static final Object[] decodeList(byte[] bencoded_bytes, int offset) throws BencodingException
{
ArrayList list = new ArrayList();
offset++;
Object[] vals;
while(bencoded_bytes[offset] != (byte)'e')
{
vals = decode(bencoded_bytes,offset);
offset = ((Integer)vals[0]).intValue();
list.add(vals[1]);
}
offset++;
return new Object[] {new Integer(offset), list};
}
/**
* Decodes a dictionary from the bencoded byte array.
* @param bencoded_bytes the bencoded form of the dictionary.
* @param offset the offset into {@code bencoded_bytes} where the dictionary begins.
* @return an <code>Object[]</code> containing an <code>Integer</code> offset and the decoded
* dictionary (as a {@code Map}, in positions 0 and 1, respectively
* @throws BencodingException if the bencoded object is incorrectly encoded.
*/
@SuppressWarnings("unchecked")
private static final Object[] decodeDictionary(byte[] bencoded_bytes, int offset) throws BencodingException
{
HashMap map = new HashMap();
++offset;
ByteBuffer info_hash_bytes = null;
while(bencoded_bytes[offset] != (byte)'e')
{
// Decode the key, which must be a byte string
Object[] vals = decodeString(bencoded_bytes, offset);
ByteBuffer key = (ByteBuffer)vals[1];
offset = ((Integer)vals[0]).intValue();
boolean match = true;
for(int i = 0; i < key.array().length && i < 4; i++)
{
if(!key.equals(ByteBuffer.wrap(new byte[]{'i', 'n','f','o'})))
{
match = false;
break;
}
}
int info_offset = -1;
if(match)
info_offset = offset;
vals = decode(bencoded_bytes, offset);
offset = ((Integer)vals[0]).intValue();
if(match)
{
info_hash_bytes = ByteBuffer.wrap(new byte[offset - info_offset]);
info_hash_bytes.put(bencoded_bytes,info_offset, info_hash_bytes.array().length);
}
else if(vals[1] instanceof HashMap)
{
info_hash_bytes = (ByteBuffer)vals[2];
}
if(vals[1] != null)
map.put(key,vals[1]);
}
return new Object[] {new Integer(++offset), map, info_hash_bytes};
}
/**
* Determines the bencoded data type at {@code bencoded_bytes[offset]}.
* @param bencoded_bytes the bencoded data.
* @param offset the offset into {@code bencoded_bytes} that contains a bencoded object.
* @return the type of the bencoded object.
* @see #DICTIONARY
* @see #LIST
* @see #INTEGER
* @see #STRING
* @see #INVALID
*/
private static final int nextObject(byte[] bencoded_bytes, int offset)
{
switch(bencoded_bytes[offset])
{
case (byte)'d':
return DICTIONARY;
case (byte)'i':
return INTEGER;
case (byte)'l':
return LIST;
case (byte)'0':
case (byte)'1':
case (byte)'2':
case (byte)'3':
case (byte)'4':
case (byte)'5':
case (byte)'6':
case (byte)'7':
case (byte)'8':
case (byte)'9':
return STRING;
default:
return INVALID;
}
}
/*
********************************************
************ BENCODING METHODS *************
********************************************
*/
/**
* Bencodes the specified object as a {@code byte[]}.
* @param o the object to bencode.
* @return the bencoded form of the object.
* @throws BencodingException if {@code o} is not of type {@code HashMap}, {@code ArrayList},
* {@code Integer}, or {@code ByteBuffer}.
*/
@SuppressWarnings("unchecked")
public static final byte[] encode(Object o) throws BencodingException
{
if(o instanceof HashMap)
return encodeDictionary((HashMap)o);
else if(o instanceof ArrayList)
return encodeList((ArrayList)o);
else if(o instanceof Integer)
return encodeInteger((Integer)o);
else if(o instanceof ByteBuffer)
return encodeString((ByteBuffer)o);
else
throw new BencodingException("Error: Object not of valid type for Bencoding.");
}
/**
* Bencodes the specified byte string.
* @param string the byte string to bencode.
* @return a {@code byte[]} containing the bencoded form of the byte string.
*/
private static final byte[] encodeString(ByteBuffer string)
{
int length = string.array().length;
int num_digits = 1;
while((length /= 10) > 0)
{
num_digits++;
}
byte[] bencoded_string = new byte[length+num_digits+1];
bencoded_string[num_digits] = (byte)':';
System.arraycopy(string.array(), 0, bencoded_string, num_digits+1, length);
for(int i = num_digits-1; i >= 0; i--)
{
bencoded_string[i] = (byte)((length % 10)+48);
length /= 10;
}
return bencoded_string;
}
/**
* Bencodes the specified Integer.
* @param integer the Integer to bencode.
* @return a {@code byte[]} containing the bencoded form of the Integer.
*/
private static final byte[] encodeInteger(Integer integer)
{
int num_digits = 1;
int int_val = integer.intValue();
while((int_val /= 10) > 0)
++num_digits;
int_val = integer.intValue();
byte[] bencoded_integer = new byte[num_digits+2];
bencoded_integer[0] = (byte)'i';
bencoded_integer[bencoded_integer.length - 1] = (byte)'e';
for(int i = num_digits; i > 0; i--)
{
bencoded_integer[i] = (byte)((int_val % 10)+48);
int_val /= 10;
}
return bencoded_integer;
}
/**
* Bencodes the specified {@code ArrayList}.
* @param list the {@code ArrayList} to bencode.
* @return a {@code byte[]} containing the bencoded form of the {@code ArrayList}.
* @throws BencodingException if any of the objects in the list is not bencodable.
*/
@SuppressWarnings("unchecked")
private static final byte[] encodeList(ArrayList list) throws BencodingException
{
byte[][] list_segments = new byte[list.size()][];
for(int i = 0; i < list_segments.length;i++)
{
list_segments[i] = encode(list.get(i));
}
int total_length = 2;
for(int i = 0 ; i < list_segments.length; i++)
total_length += list_segments[i].length;
byte[] bencoded_list = new byte[total_length];
bencoded_list[0] = 'l';
bencoded_list[bencoded_list.length-1] = 'e';
int offset = 1;
for(int i = 0; i < list_segments.length; i++)
{
System.arraycopy(list_segments[i],0,bencoded_list,offset,list_segments[i].length);
offset += list_segments[i].length;
}
return bencoded_list;
}
/**
* Bencodes the specified {@code HashMap}.
* @param dictionary the {@code HashMap} to bencode.
* @return a {@code byte[]} containing the bnecoded form of the {@code HashMap}.
* @throws BencodingException if any of the objecdts in the map is not bencodable.
*/
private static final byte[] encodeDictionary(HashMap<ByteBuffer, Object> dictionary) throws BencodingException
{
TreeMap<ByteBuffer, Object> sorted_dictionary = new TreeMap<ByteBuffer, Object>();
sorted_dictionary.putAll(dictionary);
byte[][] dictionary_parts = new byte[sorted_dictionary.keySet().size()*2][];
int k = 0;
for(Iterator<ByteBuffer> i = sorted_dictionary.keySet().iterator(); i.hasNext();)
{
ByteBuffer key = i.next();
dictionary_parts[k++] = encodeString(key);
dictionary_parts[k++] = encode(sorted_dictionary.get(key));
}
int total_length = 2;
for(int i = 0; i < dictionary_parts.length; i++)
{
total_length += dictionary_parts[i].length;
}
byte[] bencoded_dictionary = new byte[total_length];
bencoded_dictionary[0] = 'd';
bencoded_dictionary[bencoded_dictionary.length-1] = 'e';
int offset = 1;
for(int i = 0; i < dictionary_parts.length; i++)
{
System.arraycopy(dictionary_parts[i],0,bencoded_dictionary,offset,dictionary_parts[i].length);
offset += dictionary_parts[i].length;
}
return bencoded_dictionary;
}
}