# HG changeset patch # User Steve Losh # Date 1469381266 0 # Node ID 2975b6f50397cc4912f04e3986906eca8fa441e7 # Parent 5d747e72d1f2e9bdd1d3f3a1375faabf5fe00313 Try to detect truncated data diff -r 5d747e72d1f2 -r 2975b6f50397 autoload/bencode.vim --- a/autoload/bencode.vim Wed Dec 09 12:12:55 2015 +0000 +++ b/autoload/bencode.vim Sun Jul 24 17:27:46 2016 +0000 @@ -54,6 +54,11 @@ function! s:ActuallyBdecode(bstring) " {{{ let bs = substitute(a:bstring, '\v^\s*', '', '') + + if bs == '' + throw "bencode: received truncated data" + endif + if bs[0] == 'i' return s:BdecodeInteger(bs) elseif bs[0] =~ '[0-9]' @@ -67,21 +72,37 @@ endif endfunction " }}} -function! s:BdecodeInteger(bstring) " {{{ +function! s:FindDelimiter(bstring, delimiter) "{{{ let i = 1 - while a:bstring[i] != 'e' + let len = len(a:bstring) + + while a:bstring[i] != a:delimiter + if i >= len + throw "bencode: received truncated data" + endif + let i += 1 endwhile + + return i +endfunction " }}} + +function! s:BdecodeInteger(bstring) " {{{ + let i = s:FindDelimiter(a:bstring, 'e') return [0 + a:bstring[1:i - 1], a:bstring[i+1:]] endfunction " }}} function! s:BdecodeString(bstring) " {{{ - let i = 0 - while a:bstring[i] != ':' - let i += 1 - endwhile + let i = s:FindDelimiter(a:bstring, ':') + let slen = 0 + a:bstring[0:i-1] - return [a:bstring[i+1:i+slen], a:bstring[i+slen+1:]] + let strcontents = a:bstring[i+1:i+slen] + + if len(strcontents) < slen + throw "bencode: received truncated data" + endif + + return [strcontents, a:bstring[i+slen+1:]] endfunction " }}} function! s:BdecodeList(bstring) " {{{