Skip to content

Commit 3a6e556

Browse files
author
rsundahl
committed
Cleanup. Don't append a NUL if it would overflow the destination.
1 parent edbb956 commit 3a6e556

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

redhook.c

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,17 +68,20 @@ static size_t decode64(const unsigned char *s64, const size_t n64, unsigned char
6868
// Calculate decoded size but limit to size of our output buffer
6969
size_t n256 = (((n64 + 3) / 4) * 3) - ((4 - n64) & 3);
7070

71-
if (n256 > m256 - 1)
72-
n256 = m256 - 1;
71+
// Don't write more than m256 bytes
72+
if (n256 > m256)
73+
n256 = m256;
7374

7475
// Loop over input data generating three 8-in-8 bytes for each four 6-in-8 bytes
75-
for (size_t i64 = 0, i256 = 0, triple = 0; i64 < n64 && i256 < n256; i64++) {
76+
for (size_t i64 = 0, i256 = 0; i64 < n64 && i256 < n256; i64++) {
7677
if (i64 < n64 - 1) { s256[i256++] = (tDecode64[s64[i64]] << 2 | tDecode64[s64[i64 + 1]] >> 4); i64++; }
7778
if (i64 < n64 - 1) { s256[i256++] = (tDecode64[s64[i64]] << 4 | tDecode64[s64[i64 + 1]] >> 2); i64++; }
7879
if (i64 < n64 - 1) { s256[i256++] = (tDecode64[s64[i64]] << 6 | tDecode64[s64[i64 + 1]] >> 0); i64++; }
7980
} // for
8081

81-
s256[n256] = '\0';
82+
// Append a NUL if there is room to do so (but don't count it as a decoded character)
83+
if (n256 < m256)
84+
s256[n256] = '\0';
8285

8386
return n256;
8487
} // decode64()
@@ -424,14 +427,14 @@ ssize_t read(int fd, void *buf, size_t count) {
424427
} // if
425428

426429
dumpload(&payload);
427-
unsigned char payload64[4096];
428-
size_t nPayload64 = encode64((const unsigned char *) &payload, sizeof(payload), payload64, sizeof(payload64));
430+
unsigned char sPayload64[4096];
431+
size_t nPayload64 = encode64((const unsigned char *) &payload, sizeof(payload), sPayload64, sizeof(sPayload64));
429432
char *src = p + nc;
430433
char *dst = p - strlen(s_magic) - strlen(s_makeload) + nPayload64;
431434
int need = strlen(s_magic) - strlen(s_makeload) - nc + nPayload64;
432435
int tail = result - (src - ((char *) buf));
433436
memmove(dst, src, tail);
434-
memcpy(((char *) p) - strlen(s_magic) - strlen(s_makeload), payload64, nPayload64);
437+
memcpy(((char *) p) - strlen(s_magic) - strlen(s_makeload), sPayload64, nPayload64);
435438
result += need;
436439
((char *) buf)[result] = 0;
437440
} // if

0 commit comments

Comments
 (0)