chiark / gitweb /
Pull fetching random bytes into the system-specific code.
[yaid] / linux.c
diff --git a/linux.c b/linux.c
index 413fcdc2c3f3d9c8d622fb8acfbc114f7b3308d2..ecd43a1530800ffd5d6d70dc7216f764f71c7c0a 100644 (file)
--- a/linux.c
+++ b/linux.c
 /*----- Static variables --------------------------------------------------*/
 
 static FILE *natfp;                    /* File handle for NAT table */
+static int randfd;                     /* File descriptor for random data */
+
+/*----- Miscellaneous system services -------------------------------------*/
+
+/* Fill the buffer at P with SZ random bytes.  The buffer will be moderately
+ * large: this is intended to be a low-level interface, not a general-purpose
+ * utility.
+ */
+void fill_random(void *p, size_t sz)
+{
+  ssize_t n;
+
+  n = read(randfd, p, sz);
+  if (n < 0) die(1, "error reading `/dev/urandom': %s", strerror(errno));
+  else if (n < sz) die(1, "unexpected short read from `/dev/urandom'");
+}
 
 /*----- Address-type operations -------------------------------------------*/
 
@@ -463,6 +479,12 @@ void init_sys(void)
     die(1, "failed to open `/proc/net/nf_conntrack' for reading: %s",
        strerror(errno));
   }
+
+  /* Open the random data source. */
+  if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
+    die(1, "failed to open `/dev/urandom' for reading: %s",
+       strerror(errno));
+  }
 }
 
 /*----- That's all, folks -------------------------------------------------*/