zsh-workers
 help / color / mirror / code / Atom feed
a2914a8375e05d8b12e517eb1eb6fe24c8a2ed8c blob 8043 bytes (raw)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
 
/*
 * random.c - module to access kernel random sources.
 *
 * This file is part of zsh, the Z shell.
 *
 * Copyright (c) 2022 Clinton Bunch
 * All rights reserved.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and to distribute modified versions of this software for any
 * purpose, provided that the above copyright notice and the following
 * two paragraphs appear in all copies of this software.
 *
 * In no event shall Clinton Bunch or the Zsh Development Group be liable
 * to any party for direct, indirect, special, incidental, or consequential
 * damages arising out of the use of this software and its documentation,
 * even if Clinton Bunch and the Zsh Development Group have been advised of
 * the possibility of such damage.
 *
 * Clinton Bunch and the Zsh Development Group specifically disclaim any
 * warranties, including, but not limited to, the implied warranties of
 * merchantability and fitness for a particular purpose.  The software
 * provided hereunder is on an "as is" basis, and Clinton Bunch and the
 * Zsh Development Group have no obligation to provide maintenance,
 * support, updates, enhancements, or modifications.
 *
 */

#include "random.mdh"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

#include <stdbool.h>
#include <stdint.h>

#ifdef HAVE_SYS_RANDOM_H
#include <sys/random.h>
#endif

/* Simplify select URANDOM specific code */
#if !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_GETRANDOM)
#define USE_URANDOM
#endif

/* buffer to pre-load integers for SRANDOM to lessen the context switches */
uint32_t rand_buff[8];
static int buf_cnt = -1;

#ifdef USE_URANDOM
/* File descriptor for /dev/urandom */
int randfd = -1;
#endif /* USE_URANDOM */

static zlong get_srandom(UNUSED(Param p));
/*
 *  Function takes an input buffer and converts the characters to hex and
 *  places them in an outbut buffer twice the size. Returns -1 if it can't.
 *  Returns the size of the output otherwise.
 */

/**/
static int
ztr_to_hex(char *out, size_t outlen, uint8_t *input, size_t inlen)
{
    int i = 0, j = 0;

    if (outlen < (inlen * 2 + 1))
	return -1;

    for(i = 0, j = 0; i < inlen; i++, j+=2) {
	if (j < outlen) {
	    sprintf((char *)(out + j),"%02X",input[i]);
	} else {
	    return -1;
	}
    }
    out[j]='\0';
    return j;
}

/**/
ssize_t
getrandom_buffer(void *buf, size_t len)
{
    ssize_t ret;
    size_t  val     = 0;
    uint8_t *bufptr = buf;

    do {
	errno = 0;
#ifdef HAVE_ARC4RANDOM_BUF
	arc4random_buf(buf,len);
	ret = len;
#elif defined(HAVE_GETRANDOM)
	ret=getrandom(bufptr,(len - val),0);
#else
	ret=read(randfd,bufptr,(len - val));
#endif
	if (ret < 0) {
	    if (errno != EINTR || errflag || retflag || breaks || contflag) {
		zwarn("Unable to get random data: %e.", errno);
		return -1;
	    }
	}
	bufptr += ret;
	val    += ret;
    } while (ret < len);
    return ret;
}

/*
 * Generate count number of random 32-bit integers between 0 and max-1 
 * Got this algorithm from
 * https://lemire.me/blog/2016/06/30/fast-random-shuffling/
 * adapting the public domain code.
 *
 */

/**/
void
get_bound_random_buffer(uint32_t *buffer, size_t count, uint32_t max)
{
    uint64_t multi_result;
    uint32_t threshold= -max % max;
    uint32_t leftover;

    size_t i; /* loop counter */

    getrandom_buffer((void*) buffer, count*sizeof(uint32_t));
    if (max == UINT32_MAX) 
	return;

    for(i=0;i<count;i++) {
	multi_result = ((uint64_t) buffer[i]) * max;
	leftover = (uint32_t) multi_result;

	/*
	 * The following if statement should (according to Google's Gemini)
	 * only be executed with a probability of 1/2**32 or 2.33e-10
	 */
	if(leftover < max) {
	    while (leftover < threshold) {
		uint64_t j=get_srandom(NULL);
		multi_result=j*max;
		leftover= (uint32_t) multi_result;
	    }
	}
	buffer[i]=multi_result >> 32;
    }
}

/*
 * Provides for the SRANDOM parameter and returns an unsigned 32-bit random
 * integer.
 */

/**/
static zlong
get_srandom(UNUSED(Param pm)) {

    if(buf_cnt <= 0) {
	getrandom_buffer((void*) rand_buff,sizeof(rand_buff));
	buf_cnt=sizeof(rand_buff)/sizeof(rand_buff[0]);
    }
    return rand_buff[--buf_cnt];
}

/*
 * Implements math function zrand_int takes 0 to 3 arguments an upper bound,
 * a lower bound and a flag as to whether the range is inclusive or not.  The
 * default is exclusive.  If neither upper or lower is specified this is no
 * different than SRANDOM.
 */

/**/
static mnumber
math_zrand_int(UNUSED(char *name), int argc, mnumber *argv, UNUSED(int id))
{
    mnumber ret;
    uint32_t i;
    zlong lower=0, upper=UINT32_MAX,incl=0, diff;

    ret.type = MN_INTEGER;

    switch (argc) {
	case 0: ret.u.l=get_srandom(NULL);
		return ret;
		break;
	case 3: incl = (argv[2].u.l != 0)?1:0;
	case 2: lower = argv[1].u.l;
	case 1: upper = argv[0].u.l;
	default: diff = upper-lower+incl;
    }

    if (lower < 0 || lower >= UINT32_MAX) {
	zwarn("Lower bound (%z) out of range: 0-4294967295",lower);
    } else if (upper < lower) {
	zwarn("Upper bound (%z) must be greater than Lower Bound (%z)",upper,lower);
    } else if (upper < 0 || upper >= UINT32_MAX) {
	zwarn("Upper bound (%z) out of range: 0-4294967295",upper);
    }

    if ( diff == 0 ) {
	ret.u.l=upper; /* still not convinced this shouldn't be an error. */
    } else {
	get_bound_random_buffer(&i,1,(uint32_t) diff);
	ret.u.l=i+lower;
    }
    return ret;
}

/*
 * Implements the mathfunc zrandom and returns a random floating-point
 * number between 0 and 1.  
 *
 */

/**/
static mnumber
math_zrand_float(UNUSED(char *name), UNUSED(int argc), UNUSED(mnumber *argv),
	     UNUSED(int id))
{
    mnumber ret;
    double r;

    r = random_real();
    if (r < 0) {
	zwarnnam(name, "Failed to get sufficient random data.");
    }
    ret.type = MN_FLOAT;
    ret.u.d = r;

    return ret;
}

static const struct gsu_integer srandom_gsu =
{ get_srandom, nullintsetfn, stdunsetfn };

static struct paramdef patab[] = {
    {"SRANDOM", PM_INTEGER | PM_READONLY_SPECIAL | PM_HIDEVAL, NULL,
	    &srandom_gsu, NULL, NULL, NULL},
};

static struct mathfunc mftab[] = {
    NUMMATHFUNC("zrand_float", math_zrand_float, 0, 0, 0),
    NUMMATHFUNC("zrand_int", math_zrand_int, 0, 3, 0),
};

static struct features module_features = {
    NULL, 0,
    NULL, 0,
    mftab, sizeof(mftab)/sizeof(*mftab),
    patab, sizeof(patab)/sizeof(*patab),
    0
};

/**/
int
setup_(UNUSED(Module m))
{
#ifdef USE_URANDOM
    /* Check for the existence of /dev/urandom */

    struct stat st;

    errno=0;
    if (stat("/dev/urandom",&st) < 0) {
	zwarn("Error getting kernel random pool: %e.", errno);
	return 1;
    }

    errno=0;
    if (!(S_ISCHR(st.st_mode)) ) {
	zwarn("Error getting kernel random pool: %e.", errno);
	return 1;
    }
#endif /* USE_URANDOM */
    return 0;
}

/**/
int
features_(Module m, char ***features)
{
    *features = featuresarray(m, &module_features);
    return 0;
}

/**/
int
enables_(Module m, int **enables)
{
    return handlefeatures(m, &module_features, enables);
}

/**/
int
boot_(Module m)
{
#ifdef USE_URANDOM
    /*
     * Open /dev/urandom.  Here because of a weird issue on HP-UX 11.31
     * When opening in setup_ open returned 0.  In boot_, it returns
     * an unused file descriptor. Decided against ifdef HPUX as it works
     * here just as well for other platforms.
     *
     */

    int tmpfd=-1;

    errno=0;
    if ((tmpfd = open("/dev/urandom", O_RDONLY)) < 0) {
	zwarn("Could not access kernel random pool: %e.",errno);
	return 1;
    }
    randfd = movefd(tmpfd);
    addmodulefd(randfd,FDT_MODULE);
    if (randfd < 0) {
	zwarn("Could not access kernel random pool.");
	return 1;
    }
#endif /* USE_URANDOM */
    return 0;
}

/**/
int
cleanup_(Module m)
{
    return setfeatureenables(m, &module_features, NULL);
}

/**/
int
finish_(UNUSED(Module m))
{
#ifdef USE_URANDOM
    if (randfd >= 0)
	zclose(randfd);
#endif /* USE_URANDOM */
    return 0;
}

debug log:

solving a2914a837 ...
found a2914a837 in https://inbox.vuxu.org/zsh-workers/fa3e4452-16d3-43d7-8b62-b112069c1357@zentaur.org/

applying [1/1] https://inbox.vuxu.org/zsh-workers/fa3e4452-16d3-43d7-8b62-b112069c1357@zentaur.org/
diff --git a/Src/Modules/random.c b/Src/Modules/random.c
new file mode 100644
index 000000000..a2914a837

1:123: trailing whitespace.
 * Generate count number of random 32-bit integers between 0 and max-1 
1:141: trailing whitespace.
    if (max == UINT32_MAX) 
1:225: trailing whitespace.
 * number between 0 and 1.  
Checking patch Src/Modules/random.c...
1:354: new blank line at EOF.
+
Applied patch Src/Modules/random.c cleanly.
warning: 4 lines add whitespace errors.

index at:
100644 a2914a8375e05d8b12e517eb1eb6fe24c8a2ed8c	Src/Modules/random.c

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).