Browse code

improve cli_rndnum() and cli_gentempfd()

git-svn: trunk@3490

Tomasz Kojm authored on 2008/01/10 04:43:08
Showing 3 changed files
... ...
@@ -1,3 +1,7 @@
1
+Wed Jan  9 20:13:52 CET 2008 (tk)
2
+---------------------------------
3
+  * libclamav/others.c: improve cli_rndnum() and cli_gentempfd()
4
+
1 5
 Wed Jan  9 14:19:15 CET 2008 (tk)
2 6
 ---------------------------------
3 7
   * freshclam/manager.c: under some conditions old db files were not being
... ...
@@ -437,7 +437,7 @@ int scanstream(int odesc, unsigned long int *scanned, const struct cl_engine *en
437 437
     while(!bound && --portscan) {
438 438
 	if(rnd_port_first) {
439 439
 	    /* try a random port first */
440
-	    port = min_port + cli_rndnum(max_port - min_port + 1);
440
+	    port = min_port + cli_rndnum(max_port - min_port);
441 441
 	    rnd_port_first = 0;
442 442
 	} else {
443 443
 	    /* try the neighbor ports */
... ...
@@ -404,12 +404,13 @@ char *cli_strdup(const char *s)
404 404
 
405 405
 unsigned int cli_rndnum(unsigned int max)
406 406
 {
407
-    struct timeval tv;
408
-
409
-  gettimeofday(&tv, (struct timezone *) 0);
410
-  srand(tv.tv_usec+clock());
407
+    if(name_salt[0] == 16) { /* minimizes re-seeding after the first call to cli_gentemp() */
408
+	    struct timeval tv;
409
+	gettimeofday(&tv, (struct timezone *) 0);
410
+	srand(tv.tv_usec+clock());
411
+    }
411 412
 
412
-  return rand() % max;
413
+    return 1 + (unsigned int) (max * (rand() / (1.0 + RAND_MAX)));
413 414
 }
414 415
 
415 416
 void cl_settempdir(const char *dir, short leavetemps)
... ...
@@ -460,7 +461,7 @@ char *cli_gentemp(const char *dir)
460 460
     memcpy(salt, name_salt, 16);
461 461
 
462 462
     for(i = 16; i < 48; i++)
463
-	salt[i] = cli_rndnum(256);
463
+	salt[i] = cli_rndnum(255);
464 464
 
465 465
     tmp = cli_md5buff(salt, 48, name_salt);
466 466
 
... ...
@@ -492,8 +493,12 @@ int cli_gentempfd(const char *dir, char **name, int *fd)
492 492
     if(!*name)
493 493
 	return CL_EMEM;
494 494
 
495
-    *fd = open(*name, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU);
496
-    if(*fd == -1) {
495
+    *fd = open(*name, O_RDWR|O_CREAT|O_TRUNC|O_BINARY|O_EXCL, S_IRWXU);
496
+    /*
497
+     * EEXIST is almost impossible to occur, so we just treat it as other
498
+     * errors
499
+     */
500
+   if(*fd == -1) {
497 501
 	cli_errmsg("cli_gentempfd: Can't create temporary file %s: %s\n", *name, strerror(errno));
498 502
 	free(*name);
499 503
 	return CL_EIO;