2975b6f50397 default tip

Try to detect truncated data
[view raw] [browse files]
author Steve Losh <steve@stevelosh.com>
date Sun, 24 Jul 2016 17:27:46 +0000
parents 5d747e72d1f2
children (none)
branches/tags default tip
files autoload/bencode.vim

Changes

--- 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) " {{{