changeset 1284:5c1bd5b94541 draft

More sysctl cleanup: fix error message on nonexistent key, write path, and -p.
author Rob Landley <rob@landley.net>
date Thu, 15 May 2014 05:32:52 -0500
parents 55de00e9daf4
children 1a8108bda4c1
files toys/pending/sysctl.c
diffstat 1 files changed, 20 insertions(+), 15 deletions(-) [+]
line wrap: on
line diff
--- a/toys/pending/sysctl.c	Tue May 13 19:45:01 2014 -0500
+++ b/toys/pending/sysctl.c	Thu May 15 05:32:52 2014 -0500
@@ -43,8 +43,9 @@
 
 static void key_error(char *key)
 {
-  if (!(errno == ENOENT && (toys.optflags & FLAG_e)))
-    perror_msg("key '%s'", key);
+  if (errno == ENOENT) {
+    if (!(toys.optflags & FLAG_e)) error_msg("unknown key '%s'", key);
+  } else perror_msg("key '%s'", key);
 }
 
 static int write_key(char *path, char *key, char *value)
@@ -89,23 +90,25 @@
   return 0;
 }
 
-// Read/write entries under a key
+// Read/write entries under a key. Accepts "key=value" in key if !value
 static void process_key(char *key, char *value)
 {
-  char *path, *pattern = "%s/%s/%s";
+  char *path;
 
-  if ((toys.optflags & FLAG_w) && !value && !strchr(key, '=')) {
+  if (!value) value = split_key(key);
+  if ((toys.optflags & FLAG_w) && !value) {
     error_msg("'%s' not key=value");
 
     return;
   }
 
-  path = xmprintf(pattern + 3*!value, "/proc/sys", key, value);
-  value = split_key(path);
+  path = xmprintf("/proc/sys/%s", key);
   replace_char(path, '.', '/');
   // Note: failure to assign to a non-leaf node suppresses the display.
-  if (!(value && (write_key(path, key, value) || (toys.optflags & FLAG_q))))
-    dirtree_read(path, do_show_keys);
+  if (!(value && (!write_key(path, key, value) || (toys.optflags & FLAG_q)))) {
+    if (!access(path, R_OK)) dirtree_read(path, do_show_keys);
+    else key_error(key);
+  }
   free(path);
 }
 
@@ -119,26 +122,28 @@
   // read file
   else if (toys.optflags & FLAG_p) {
     FILE *fp = xfopen(*toys.optargs ? *toys.optargs : "/etc/sysctl.conf", "r");
-    char *line = 0;
     size_t len;
 
-    for (;-1 != (len = getline(&line, &len, fp)); free(line), line = 0) {
-      char *key = line, *val;
+    for (;;) {
+      char *line = 0, *key, *val;
 
+      if (-1 == (len = getline(&line, &len, fp))) break;
+      key = line;
       while (isspace(*key)) key++;
       if (*key == '#' || *key == ';' || !*key) continue;
+      while (len && isspace(line[len-1])) line[--len] = 0;
       if (!(val = split_key(line))) {
-        error_msg("'%s' not key=value");
+        error_msg("'%s' not key=value", line);
         continue;
       }
 
-      // Trim whitespace off key and value
-      while (len && isspace(line[len-1])) line[--len] = 0;
+      // Trim whitespace around =
       len = (val-line)-1;
       while (len && isspace(line[len-1])) line[--len] = 0;
       while (isspace(*val)) val++;;
 
       process_key(key, val);
+      free(line);
     }
     fclose(fp);