1
2 /*****************************************************************************
3 * rand : write a randomization of files or stdin or parms to stdout
4 * Usage:
5 * blah | rand [-lw] [-o output file]
6 * rand [-lw] -f <file> [-o output file]
7 *
8 * Copyright (C) 1998-2012 Erik Greenwald <erik@brlcad.org>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 *
24 ******************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <time.h>
35
36 #include "seed.h"
37
38 #if HAVE_GETEUID
39 # define GETUID geteuid()
40 #elif HAVE_GETUID
41 # define GETUID getuid()
42 #else
43 # define GETUID 0
44 #endif
45
46 /*
47 * Write out the random seed. This is done on each pass per euid, so if an
48 * effective user wants to recover the last random seed, there is a place to
49 * extract it from.
50 * @param void No parameters accepted.
51 * @return Void. Nothing returned.
52 */
53 void
seed_rand()54 seed_rand ()
55 {
56 unsigned int seed;
57 FILE *f;
58 char s[1024];
59
60 /*
61 * seed the entropy pool from here, so we can override it
62 *
63 * thanks to Martin Hinsch for the +time(0)
64 */
65 seed = ((unsigned int)(getpid () * time (NULL)));
66 #ifdef HAVE_DRAND48
67 srand48 (seed);
68 #else
69 srand (seed);
70 #endif
71 sprintf (s, "/var/tmp/rand.%d", GETUID);
72 if((f = fopen (s, "w")) == NULL)
73 return;
74 fprintf (f, "%u\n", seed);
75 fclose (f);
76 return;
77 }
78
79 /**
80 * I have no clue why this is here.
81 */
82 void
old_seed()83 old_seed ()
84 {
85 unsigned int seed;
86 FILE *f;
87 char s[1024];
88
89 sprintf (s, "/var/tmp/rand.%d", GETUID);
90 if( (f = fopen (s, "r")) == NULL)
91 return;
92 if(fscanf (f, "%u\n", &seed) != 1) {
93 fprintf(stderr, "Error reading old random seed\n");
94 return;
95 }
96 fclose (f);
97 #ifdef HAVE_DRAND48
98 srand48 (seed);
99 #else
100 srand (seed);
101 #endif
102 return;
103 }
104
105 /**
106 * Seed a random number.
107 * @param arg eh?
108 * @return Void... Nothing returned.
109 */
110 void
seed(char * arg)111 seed (char *arg)
112 {
113 if (arg == NULL)
114 seed_rand ();
115 else if (arg[0] == '.')
116 old_seed ();
117 else
118 srand (atoi (arg));
119 return;
120 }
121