/*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
 *
 * n4: A fast userspace NFSv4 server.
 * $Id: random.c,v 1.1 2001/05/30 06:04:59 mbp Exp $
 * 
 * Copyright (C) 2001 by Martin Pool <mbp@samba.org>
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <includes.h>

/*
 * Taken from the libuuid library, which is licensed under the GNU
 * GPL.
 *
 * Copyright (C) 1996, 1997 Theodore Ts'o.
 */

/*
 * Generate a series of random bytes.  Use /dev/urandom if possible,
 * and if not, use srandom/random.
 */
MKPROTO void n4_get_random_bytes(void *buf, int nbytes)
{
    static int fd = -2;
    int i;
    char *cp = (char *) buf;

    if (fd == -2) {
        fd = open("/dev/urandom", O_RDONLY);
        srand((getpid() << 16) ^ getuid() ^ time(0));
    }
    if (fd >= 0) {
        while (nbytes > 0) {
            i = read(fd, cp, nbytes);
            if (i < 0) {
                if ((errno == EINTR) || (errno == EAGAIN))
                    continue;
                break;
            }
            nbytes -= i;
            cp += i;
        }
    }
    if (nbytes == 0)
        return;

    /* XXX put something better here if no /dev/random! */
    for (i=0; i < nbytes; i++)
        *cp++ = rand() & 0xFF;
    return;
	
}
