chiark / gitweb /
Properly log fatal errors encountered after program startup.
[yaid] / linux.c
diff --git a/linux.c b/linux.c
index 25fcb6c12794fbb7da600df17e6ef667d5183999..571b179b2bf09559b15139a24635e197eadc2c87 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) fatal("error reading `/dev/urandom': %s", strerror(errno));
+  else if (n < sz) fatal("unexpected short read from `/dev/urandom'");
+}
 
 /*----- Address-type operations -------------------------------------------*/
 
@@ -102,7 +118,7 @@ static int get_default_gw(int af, union addr *a)
 
   /* Open a netlink socket for interrogating the kernel. */
   if ((fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
-    die(1, "failed to create netlink socket: %s", strerror(errno));
+    fatal("failed to create netlink socket: %s", strerror(errno));
 
   /* We want to read the routing table.  There doesn't seem to be a good way
    * to do this without just crawling through the whole thing.
@@ -119,14 +135,14 @@ static int get_default_gw(int af, union addr *a)
   rtgen->rtgen_family = af;
 
   if (write(fd, nlmsg, nlmsg->nlmsg_len) < 0)
-    die(1, "failed to send RTM_GETROUTE request: %s", strerror(errno));
+    fatal("failed to send RTM_GETROUTE request: %s", strerror(errno));
 
   /* Now we try to parse the answer. */
   for (;;) {
 
     /* Not finished yet, so read another chunk of answer. */
     if ((n = read(fd, buf, sizeof(buf))) < 0)
-      die(1, "failed to read RTM_GETROUTE response: %s", strerror(errno));
+      fatal("failed to read RTM_GETROUTE response: %s", strerror(errno));
 
     /* Start at the beginning of the response. */
     nlmsg = (struct nlmsghdr *)buf;
@@ -457,11 +473,18 @@ done:
 /* Initialize the system-specific code. */
 void init_sys(void)
 {
+  /* Open the NAT connection map. */
   if ((natfp = fopen("/proc/net/nf_conntrack", "r")) == 0 &&
       errno != ENOENT) {
     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 -------------------------------------------------*/