From c2be26a9bdb2ec7ae7c817fd84885fa2a85521fb Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Sun, 18 Mar 2012 00:34:31 +0100 Subject: [PATCH] q3map2: add safe string copy functions * Q_strncpyz() * Q_strncat() * Q_strcat() Guard against buffer overruns, always zero terminate the result. --- tools/quake3/q3map2/main.c | 32 ++++++++++++++++++++++++++++++++ tools/quake3/q3map2/q3map2.h | 5 +++++ 2 files changed, 37 insertions(+) diff --git a/tools/quake3/q3map2/main.c b/tools/quake3/q3map2/main.c index 2ea7c92..e74a89c 100644 --- a/tools/quake3/q3map2/main.c +++ b/tools/quake3/q3map2/main.c @@ -46,6 +46,38 @@ vec_t Random( void ){ } +char *Q_strncpyz( char *dst, const char *src, size_t len ) { + if ( len == 0 ) { + abort(); + } + + strncpy( dst, src, len ); + dst[ len - 1 ] = '\0'; + return dst; +} + + +char *Q_strcat( char *dst, size_t dlen, const char *src ) { + size_t n = strlen( dst ); + + if ( n > dlen ) { + abort(); /* buffer overflow */ + } + + return Q_strncpyz( dst + n, src, dlen - n ); +} + + +char *Q_strncat( char *dst, size_t dlen, const char *src, size_t slen ) { + size_t n = strlen( dst ); + + if ( n > dlen ) { + abort(); /* buffer overflow */ + } + + return Q_strncpyz( dst + n, src, MIN( slen, dlen - n ) ); +} + /* ExitQ3Map() diff --git a/tools/quake3/q3map2/q3map2.h b/tools/quake3/q3map2/q3map2.h index bb75691..245e34c 100644 --- a/tools/quake3/q3map2/q3map2.h +++ b/tools/quake3/q3map2/q3map2.h @@ -83,6 +83,8 @@ #include +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) /* ------------------------------------------------------------------------------- @@ -1446,6 +1448,9 @@ surfaceInfo_t; /* main.c */ vec_t Random( void ); +char *Q_strncpyz( char *dst, const char *src, size_t len ); +char *Q_strcat( char *dst, size_t dlen, const char *src ); +char *Q_strncat( char *dst, size_t dlen, const char *src, size_t slen ); int BSPInfo( int count, char **fileNames ); int ScaleBSPMain( int argc, char **argv ); int ConvertMain( int argc, char **argv );