From e7461eb684f76698fab53cc58ee7966d7a3c4d79 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Thu, 30 Oct 2008 19:47:00 +0000 Subject: [PATCH] (libT) fix a tr_buildPath() bug reported by pea_ --- libtransmission/utils-test.c | 19 +++++++++++++++++++ libtransmission/utils.c | 11 +++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/libtransmission/utils-test.c b/libtransmission/utils-test.c index 42d6c92a4..2dd8ee424 100644 --- a/libtransmission/utils-test.c +++ b/libtransmission/utils-test.c @@ -1,6 +1,7 @@ #include /* fprintf */ #include /* strcmp */ #include "transmission.h" +#include "platform.h" #include "utils.h" #include "crypto.h" @@ -118,6 +119,22 @@ test_strstrip( void ) return 0; } +static int +test_buildpath( void ) +{ + char * out; + + out = tr_buildPath( "foo", "bar", NULL ); + check( !strcmp( out, "foo" TR_PATH_DELIMITER_STR "bar" ) ); + tr_free( out ); + + out = tr_buildPath( "", "foo", "bar", NULL ); + check( !strcmp( out, TR_PATH_DELIMITER_STR "foo" TR_PATH_DELIMITER_STR "bar" ) ); + tr_free( out ); + + return 0; +} + int main( void ) { @@ -141,6 +158,8 @@ main( void ) if( ( i = test_strstrip( ) ) ) return i; + if( ( i = test_buildpath( ) ) ) + return i; /* test that tr_cryptoRandInt() stays in-bounds */ for( i = 0; i < 100000; ++i ) diff --git a/libtransmission/utils.c b/libtransmission/utils.c index d2cd4c93f..27b82687f 100644 --- a/libtransmission/utils.c +++ b/libtransmission/utils.c @@ -615,7 +615,7 @@ tr_buildPath( const char *first_element, ... ) bufLen += strlen( element ) + 1; element = (const char*) va_arg( vl, const char* ); } - pch = buf = tr_new0( char, bufLen ); + pch = buf = tr_new( char, bufLen ); va_end( vl ); /* pass 2: build the string piece by piece */ @@ -623,16 +623,19 @@ tr_buildPath( const char *first_element, ... ) element = first_element; while( element ) { const size_t elementLen = strlen( element ); - if( pch != buf ) - *pch++ = TR_PATH_DELIMITER; memcpy( pch, element, elementLen ); pch += elementLen; + *pch++ = TR_PATH_DELIMITER; element = (const char*) va_arg( vl, const char* ); } va_end( vl ); - /* sanity checks & return */ + /* terminate the string. if nonempty, eat the unwanted trailing slash */ + if( pch != buf ) + --pch; *pch++ = '\0'; + + /* sanity checks & return */ assert( pch - buf == (off_t)bufLen ); return buf; }