-
Notifications
You must be signed in to change notification settings - Fork 4
/
bencode.js
269 lines (230 loc) · 6.8 KB
/
bencode.js
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
/* http://natsuki.weeaboo.se:8080/~valderman/files/bencode.js */
/* Copyright (c) 2009 Anton Ekblad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. */
/* modified by Stefan Buehler to use node.js Buffers (c) 2010 */
function PaddingError(object, message) {
this.object = object;
this.name = "padded bencoeded string";
this.message = message || "bencoded string contained too much data";
}
PaddingError.prototype = new Error();
PaddingError.prototype.constructor = PaddingError;
exports.PaddingError = PaddingError;
if (!Buffer.prototype.charAt) Buffer.prototype.charAt = function charAt(i) {
return String.fromCharCode(this[i]);
};
// bencode an object
function bencode(obj) {
switch(btypeof(obj)) {
case "string": return bstring(obj);
case "number": return bint(obj);
case "list": return blist(obj);
case "dictionary": return bdict(obj);
default: throw new Error('cannot encode element ' + obj);
}
}
exports.bencode = bencode;
// decode a bencoded string into a javascript object
function bdecode(str, allowpadding) {
if (!(str instanceof Buffer)) {
str = new Buffer(str);
}
var dec = bparse(str, 0);
if(dec !== null) {
if (dec[1] === str.length || (allowpadding && dec[1] <= str.length)) return dec[0];
if (!allowpadding && dec[1] <= str.length) throw new PaddingError(dec[0]);
throw new Error("unexpected end of data");
}
throw new Error("couldn't decode data");
}
exports.bdecode = bdecode;
// parse a bencoded string; bdecode is really just a wrapper for this one.
// all bparse* functions return an array in the form
// [parsed object, remaining string to parse]
function bparse(str, pos) {
switch(str.charAt(pos)) {
case "d": return bparseDict(str, pos+1);
case "l": return bparseList(str, pos+1);
case "i": return bparseInt(str, pos+1);
default: return bparseString(str, pos);
}
}
function findchar(str, pos, c) {
while (pos < str.length) {
if (str.charAt(pos) === c) return pos;
++pos;
}
return -1;
}
function copy(str, start, len) {
return str.slice(start, start+len);
}
// parse a bencoded string
function bparseString(str, pos) {
var colon, str2, len;
colon = findchar(str, pos, ':');
if (-1 === colon) throw new Error("couldn't find colon");
str2 = str.toString('ascii', pos, colon);
if(isNum(str2)) {
len = parseInt(str2);
if (colon+1+len > str.length) throw new Error("unexpected end of data");
return [ copy(str, colon+1, len), colon+1+len ];
}
throw new Error("string length is not numeric");
}
// parse a bencoded integer
function bparseInt(str, pos) {
var end = findchar(str, pos, 'e');
if (-1 === end) throw new Error("couldn't find end of int");
var str2 = str.toString('ascii', pos, end);
if(!isNum(str2))
throw new Error("number contains non-digits");
return [Number(str2), end+1];
}
// parse a bencoded list
function bparseList(str, pos) {
var p, list = [];
while (pos < str.length && str.charAt(pos) !== "e") {
p = bparse(str, pos);
if (null === p) throw new Error("unexpected null element");
list.push(p[0]);
pos = p[1];
}
if (pos >= str.length) throw new Error("unexpected end of data");
return [list, pos+1];
}
function compareBuffers(a, b) {
var i, l = Math.min(a.length, b.length);
for (i = 0; i < l; ++i) {
if (a[i] != b[i]) return (a[i] < b[i]) ? -1 : 1;
}
if (a.length === b.length) return 0;
return (a.length < b.length) ? -1 : 1;
}
// parse a bencoded dictionary
function bparseDict(str, pos) {
var key, val, dict = {}, oldkey = false, cmpkey;
while (pos < str.length && str.charAt(pos) !== "e") {
key = bparseString(str, pos);
if (null === key) throw new Error("unexpected null element");
pos = key[1];
if (pos >= str.length) throw new Error("unexpected end of data");
val = bparse(str, pos);
if (null === val) throw new Error("unexpected null element");
if (oldkey !== false) {
cmpkey = compareBuffers(oldkey, key[0]);
if (0 === cmpkey) throw new Error("duplicate key in dictionary");
if (1 === cmpkey) throw new Error("wrong key order in dictionary");
}
oldkey = key[0];
dict[key[0]] = val[0];
pos = val[1];
}
if (pos >= str.length) throw new Error("unexpected end of data");
return [dict, pos+1];
}
// is the given string numeric?
function isNum(str) {
var i, c;
str = str.toString();
if(str.charAt(0) === '-') {
i = 1;
} else {
i = 0;
}
for(; i < str.length; ++i) {
c = str.charCodeAt(i);
if (c < 48 || c > 57) {
return false;
}
}
return true;
}
// returns the bencoding type of the given object
function btypeof(obj) {
var type = typeof obj;
if (null === obj) return "null";
if (type === "object") {
if (obj instanceof Buffer) return "string";
if (obj instanceof Array) return "list";
return "dictionary";
}
return type;
}
// bencode a string
function bstring(str) {
if (str instanceof Buffer) {
var len = str.length;
var slen = len.toString() + ":";
var buf = new Buffer(slen.length + len);
buf.write(slen, 0, 'utf8');
str.copy(buf, slen.length, 0, len);
return buf;
} else {
var len = Buffer.byteLength(str, 'utf8');
var slen = len.toString() + ":";
var buf = new Buffer(slen.length + len);
buf.write(slen, 0, 'utf8');
buf.write(str, slen.length, 'utf8');
return buf;
}
}
// bencode an integer
function bint(num) {
return new Buffer("i" + num + "e", 'utf8');
}
// bencode a list
function blist(list) {
var enclist, i, l, buflen, b, buf, pos;
enclist = [];
buflen = 2;
for (i = 0, l = list.length; i < l; ++i) {
b = bencode(list[i]);
enclist.push(b);
buflen += b.length;
}
buf = new Buffer(buflen);
buf.write('l', 0, 'ascii');
pos = 1;
for (i = 0, l = enclist.length; i < l; ++i) {
b = enclist[i];
b.copy(buf, pos, 0, b.length);
pos += b.length;
}
buf.write('e', pos, 'ascii');
return buf;
}
// bencode a dictionary
function bdict(dict) {
var enclist, i, l, buflen, b, buf, pos, key, keylist;
enclist = [];
buflen = 2;
keylist = Object.keys(dict).sort();
for (i = 0, l = keylist.length; i < l; ++i) {
key = keylist[i];
if (!dict.hasOwnProperty(key)) continue;
b = bstring(key);
enclist.push(b);
buflen += b.length;
b = bencode(dict[key]);
enclist.push(b);
buflen += b.length;
}
buf = new Buffer(buflen);
buf.write('d', 0, 'ascii');
pos = 1;
for (i = 0, l = enclist.length; i < l; ++i) {
b = enclist[i];
b.copy(buf, pos, 0, b.length);
pos += b.length;
}
buf.write('e', pos, 'ascii');
return buf;
}