From 2741b3739d9e3b797fb1b66e3ca10c42606728d7 Mon Sep 17 00:00:00 2001
From: Joe Groff <arcata@gmail.com>
Date: Wed, 29 Apr 2009 08:22:35 -0500
Subject: [PATCH] plug some holes in wav parser

---
 extra/audio/wav/wav.factor | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)

diff --git a/extra/audio/wav/wav.factor b/extra/audio/wav/wav.factor
index 6f8ee49395..3f40516abf 100644
--- a/extra/audio/wav/wav.factor
+++ b/extra/audio/wav/wav.factor
@@ -1,6 +1,6 @@
 USING: alien.c-types alien.syntax audio combinators
 combinators.short-circuit io io.binary io.encodings.binary
-io.files io.streams.memory kernel locals sequences ;
+io.files io.streams.byte-array kernel locals sequences ;
 IN: audio.wav
 
 CONSTANT: RIFF-MAGIC "RIFF"
@@ -16,7 +16,6 @@ C-STRUCT: riff-chunk-header
 C-STRUCT: riff-chunk
     { "riff-chunk-header" "header" }
     { "char[4]" "format" }
-    { "uchar[0]" "body" }
     ;
 
 C-STRUCT: wav-fmt-chunk
@@ -34,8 +33,17 @@ C-STRUCT: wav-data-chunk
     { "uchar[0]" "body" }
     ;
 
+ERROR: invalid-wav-file ;
+
+: ensured-read ( count -- output/f )
+    [ read ] keep over length = [ drop f ] unless ;
+: ensured-read* ( count -- output )
+    ensured-read [ invalid-wav-file ] unless* ;
+
 : read-chunk ( -- byte-array/f )
-    4 read [ 4 read le> [ <uint> ] [ read ] bi 3append ] [ f ] if* ;
+    4 ensured-read [ 4 ensured-read* dup le> ensured-read* 3append ] [ f ] if* ;
+: read-riff-chunk ( -- byte-array/f )
+    "riff-chunk" heap-size ensured-read* ;
 
 : id= ( chunk id -- ? )
     [ 4 memory>byte-array ] dip sequence= ;
@@ -49,8 +57,6 @@ C-STRUCT: wav-data-chunk
     } cond ] while drop
     fmt data ;
 
-ERROR: invalid-wav-file ;
-
 : verify-wav ( chunk -- )
     { [ RIFF-MAGIC id= ] [ riff-chunk-format WAVE-MAGIC id= ] } 1&&
     [ invalid-wav-file ] unless ;
@@ -68,7 +74,5 @@ ERROR: invalid-wav-file ;
 
 : read-wav ( filename -- audio )
     binary [
-        read-chunk
-        [ verify-wav ]
-        [ riff-chunk-body <memory-stream> [ (read-wav) ] with-input-stream* ] bi
+        read-riff-chunk verify-wav (read-wav)
     ] with-file-reader ;