From 0bf7a215f0623f0a4d5920ffde71ff5d788fe9cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20B=C3=BChler?= Date: Fri, 21 Jun 2013 15:17:10 +0200 Subject: [PATCH] check key order in dictionaries --- lib/bencode.js | 21 +++++++++++++++++---- lib/test.js | 3 +++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/bencode.js b/lib/bencode.js index db566d3..6b316c1 100644 --- a/lib/bencode.js +++ b/lib/bencode.js @@ -78,9 +78,6 @@ function findchar(str, pos, c) { function copy(str, start, len) { return str.slice(start, start+len); -// var buf = new Buffer(len); -// str.copy(buf, 0, start, start+len); -// return buf; } // parse a bencoded string @@ -120,9 +117,18 @@ function bparseList(str, pos) { 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 = {}; + 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"); @@ -132,6 +138,13 @@ function bparseDict(str, pos) { 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]; } diff --git a/lib/test.js b/lib/test.js index 7854bf6..0ec0267 100644 --- a/lib/test.js +++ b/lib/test.js @@ -38,3 +38,6 @@ checkDecodeThrows("d3:key5:value", Error, "unexpected end of data"); checkDecodeThrows("l", Error, "unexpected end of data"); checkDecodeThrows("l7:element", Error, "unexpected end of data"); + +checkDecodeThrows("d3:kez0:3:key0:e", Error, "wrong key order in dictionary"); +checkDecodeThrows("d3:key0:3:key0:e", Error, "duplicate key in dictionary");