- Timestamp:
- 2008-06-10T03:09:49Z (17 years ago)
- Branches:
- master
- Children:
- fde7b91
- Parents:
- 55eda08
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
lib/misc.c
r55eda08 r7f49a86 392 392 } 393 393 394 /* A pretty reliable random number generator. Tries to use the /dev/random 395 devices first, and falls back to the random number generator from libc 396 when it fails. Opens randomizer devices with O_NONBLOCK to make sure a 397 lack of entropy won't halt BitlBee. */ 398 void random_bytes( unsigned char *buf, int count ) 399 { 400 #ifndef _WIN32 401 static int use_dev = -1; 402 403 /* Actually this probing code isn't really necessary, is it? */ 404 if( use_dev == -1 ) 405 { 406 if( access( "/dev/random", R_OK ) == 0 || access( "/dev/urandom", R_OK ) == 0 ) 407 use_dev = 1; 408 else 409 { 410 use_dev = 0; 411 srand( ( getpid() << 16 ) ^ time( NULL ) ); 412 } 413 } 414 415 if( use_dev ) 416 { 417 int fd; 418 419 /* At least on Linux, /dev/random can block if there's not 420 enough entropy. We really don't want that, so if it can't 421 give anything, use /dev/urandom instead. */ 422 if( ( fd = open( "/dev/random", O_RDONLY | O_NONBLOCK ) ) >= 0 ) 423 if( read( fd, buf, count ) == count ) 424 { 425 close( fd ); 426 return; 427 } 428 close( fd ); 429 430 /* urandom isn't supposed to block at all, but just to be 431 sure. If it blocks, we'll disable use_dev and use the libc 432 randomizer instead. */ 433 if( ( fd = open( "/dev/urandom", O_RDONLY | O_NONBLOCK ) ) >= 0 ) 434 if( read( fd, buf, count ) == count ) 435 { 436 close( fd ); 437 return; 438 } 439 close( fd ); 440 441 /* If /dev/random blocks once, we'll still try to use it 442 again next time. If /dev/urandom also fails for some 443 reason, stick with libc during this session. */ 444 445 use_dev = 0; 446 srand( ( getpid() << 16 ) ^ time( NULL ) ); 447 } 448 449 if( !use_dev ) 450 #endif 451 { 452 int i; 453 454 /* Possibly the LSB of rand() isn't very random on some 455 platforms. Seems okay on at least Linux and OSX though. */ 456 for( i = 0; i < count; i ++ ) 457 buf[i] = rand() & 0xff; 458 } 459 } 460 394 461 int is_bool( char *value ) 395 462 {
Note: See TracChangeset
for help on using the changeset viewer.