]> git.pond.sub.org Git - empserver/commitdiff
client: Fix integer wrap around in ring_peek()
authorMarkus Armbruster <armbru@pond.sub.org>
Sun, 27 Dec 2015 14:32:00 +0000 (15:32 +0100)
committerMarkus Armbruster <armbru@pond.sub.org>
Sat, 8 Jul 2017 17:17:07 +0000 (19:17 +0200)
Peeking beyond either end of the ring buffer must return EOF.  We
first compute the index, then check whether it's in range.

Unfortunately, the index computation r->prod - -n can wrap around
while r->prod is still <= RING_SIZE.  If it happens, ring_peek()
returns r->buf[(r->prod - -n) % RING_SIZE] instead of EOF.

Currently harmless, because no caller peeks out of range.

Signed-off-by: Markus Armbruster <armbru@pond.sub.org>
src/client/ringbuf.c

index c65ff211827efffc71a6eed935f00c0b10fbd249..1fb6bff6fa0aa984b67ed226afd045d1126c2f03 100644 (file)
@@ -27,7 +27,7 @@
  *  ringbuf.c: Simple ring buffer
  *
  *  Known contributors to this file:
- *     Markus Armbruster, 2007-2009
+ *     Markus Armbruster, 2007-2015
  */
 
 #include <config.h>
@@ -82,9 +82,17 @@ ring_peek(struct ring *r, int n)
 
     assert(-RING_SIZE - 1 <= n && n <= RING_SIZE);
 
-    idx = n >= 0 ? r->cons + n : r->prod - -n;
-    if (idx < r->cons && idx >= r->prod)
-       return EOF;
+    if (n >= 0) {
+       idx = r->cons + n;
+       if (idx >= r->prod)
+           return EOF;
+    } else {
+       /* Beware, r->prod - -n can wrap around, avoid that */
+       if (r->prod < r->cons + -n)
+           return EOF;
+       idx = r->prod - -n;
+    }
+
     return r->buf[idx % RING_SIZE];
 }