chiark / gitweb /
www-cgi/: Allow customization of the environment filters.
[userv-utils.git] / www-cgi / ucgicommon.c
index 168641b9d724811087e00da2d50a6eacc42c0e79..db8c75d65858932034adae2f5d6ccb0d1f55b8cd 100644 (file)
@@ -18,6 +18,8 @@
  * $Id$
  */
 
+#include <ctype.h>
+#include <stdarg.h>
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
@@ -69,6 +71,59 @@ void xsetenv(const char *en, const char *ev, int overwrite) {
   if (setenv(en,ev,overwrite)) syserror("setenv");
 }
 
+const char **load_filters(unsigned flags, const char *first, ...)
+{
+  va_list ap;
+  const char *name, *p, *q, **v;
+  char *pp;
+  size_t l, n, sz;
+  FILE *fp;
+  char buf[MAX_ENVVAR_NAME];
+
+  D( if (debugmode) printf(";; load_filters...\n"); )
+  va_start(ap, first);
+  for (name= first; name; name= va_arg(ap, const char *)) {
+    fp= fopen(name, "r"); if (fp) goto opened;
+    D( if (debugmode)
+        printf(";;   file `%s': %s\n", name, strerror(errno)); )
+    if (errno != ENOENT) syserror("failed to open environment filters");
+  }
+  va_end(ap);
+  if (flags & LOADF_MUST) syserror("failed to open environment filters");
+  D( if (debugmode) printf(";;   using default filters\n"); )
+  return 0;
+
+opened:
+  va_end(ap);
+  D( if (debugmode) printf(";;   file `%s': OK\n", name); )
+
+  n= 0; sz= 128; v= xmalloc(sz * sizeof(*v));
+  for (;;) {
+    if (!fgets(buf, sizeof(buf), fp)) break;
+    l= strlen(buf);
+    if (buf[l - 1] == '\n') buf[--l]= 0;
+    if (l + 1 == sizeof(buf))
+      error("line too long in environment filter file");
+    p= buf; q= p + l;
+    while (isspace((unsigned char)*p)) p++;
+    while (q > p && isspace((unsigned char)q[-1])) q--;
+    if (*p == '#' || p == q) continue;
+    l= q - p;
+    pp= xmalloc(l + 1);
+    memcpy(pp, p, l);
+    pp[l]= 0;
+    v[n++]= pp;
+    D( if (debugmode) printf(";;   filter: `%s'\n", pp); )
+    if (n >= sz) {
+      sz *= 2;
+      v= xrealloc(v, sz * sizeof(*v));
+    }
+  }
+  if (ferror(fp)) syserror("failed to read environment filters");
+  fclose(fp);
+  return v;
+}
+
 void filter_environment(unsigned flags, const char *prefix_in,
                        const char *const *patv,
                        void (*foundone)(const char *fulln,