[vlc-commits] text: fix bias in vlc_mkstemp()

Rémi Denis-Courmont git at videolan.org
Sat Sep 21 11:49:05 CEST 2019


vlc | branch: master | Rémi Denis-Courmont <remi at remlab.net> | Sat Sep 21 11:33:44 2019 +0300| [6e6448aa809713402afa0c7409cdf206431bbaf7] | committer: Rémi Denis-Courmont

text: fix bias in vlc_mkstemp()

Make the cardinal of the random characters set a power of two so that
the random number division does not bias toward certain character.

Also use ARRAY_SIZE and fix misleading "digits" variable name.

> http://git.videolan.org/gitweb.cgi/vlc.git/?a=commit;h=6e6448aa809713402afa0c7409cdf206431bbaf7
---

 src/text/filesystem.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/src/text/filesystem.c b/src/text/filesystem.c
index c0c5218908..989d47cc59 100644
--- a/src/text/filesystem.c
+++ b/src/text/filesystem.c
@@ -204,8 +204,12 @@ int vlc_scandir( const char *dirname, char ***namelist,
 
 int vlc_mkstemp( char *template )
 {
-    static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-    static const int i_digits = sizeof(digits)/sizeof(*digits) - 1;
+    static const char bytes[] =
+        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqstruvwxyz_-";
+    static const size_t nbytes = ARRAY_SIZE(bytes) - 1;
+
+    static_assert(((ARRAY_SIZE(bytes) - 1) & (ARRAY_SIZE(bytes) - 2)) == 0,
+                  "statistical bias");
 
     /* */
     assert( template );
@@ -228,7 +232,7 @@ int vlc_mkstemp( char *template )
 
         vlc_rand_bytes( pi_rand, sizeof(pi_rand) );
         for( int j = 0; j < 6; j++ )
-            psz_rand[j] = digits[pi_rand[j] % i_digits];
+            psz_rand[j] = bytes[pi_rand[j] % nbytes];
 
         /* */
         int fd = vlc_open( template, O_CREAT | O_EXCL | O_RDWR, 0600 );



More information about the vlc-commits mailing list