chiark / gitweb /
cgi-fcgi-interp: Send our own stage2 messages to syslog
[chiark-utils.git] / cprogs / cgi-fcgi-interp.c
index 89b3f5deceef6d67a30ad599092eeb168539724d..1612e4fe70f9dcb141a9742240cfff4525a1cd63 100644 (file)
 #include <time.h>
 #include <signal.h>
 #include <sys/wait.h>
+#include <syslog.h>
        
 #include <nettle/sha.h>
 
@@ -159,13 +160,31 @@ static int check_interval=300;
 
 static struct sha256_ctx identsc;
 
-const char *stage2;
+static bool logging;
+static const char *stage2;
 
 static void vmsgcore(int estatus, int errnoval, const char *fmt, va_list al) {
-  fputs("cgi-fcgi-interp: ",stderr);
-  vfprintf(stderr,fmt,al);
-  if (errnoval!=-1) fprintf(stderr,": %s",strerror(errnoval));
-  fputc('\n',stderr);
+  int r;
+
+  if (logging) {
+    const char *fmt_use = fmt;
+    char *fmt_free = 0;
+    if (errnoval) {
+      r = asprintf(&fmt_free, "%s: %%m", fmt);
+      if (r) {
+       fmt_free = 0;
+      } else {
+       fmt_use = fmt_free;
+      }
+    }
+    vsyslog(LOG_ERR, fmt_use, al);
+    free(fmt_free);
+  } else {
+    fputs("cgi-fcgi-interp: ",stderr);
+    vfprintf(stderr,fmt,al);
+    if (errnoval!=-1) fprintf(stderr,": %s",strerror(errnoval));
+    fputc('\n',stderr);
+  }
   if (estatus) exit(estatus);
 }
 
@@ -525,6 +544,7 @@ static void become_pgrp(void);
 static void setup_handlers(void);
 static void spawn_script(void);
 static void queue_alarm(void);
+static void start_logging(void);
 static void await_something(void);
 
 int main(int argc, const char *const *argv) {
@@ -543,6 +563,9 @@ int main(int argc, const char *const *argv) {
     if (r<0) diee("open /dev/null as stdout");
     if (r>=3) close(r);
     else if (r!=1) die("open /dev/null for stdout gave bad fd %d",r);
+
+    r = close(stderrfd);
+    if (r) diee("close saved stderr fd");
   }
 
   sha256_init(&identsc);
@@ -614,6 +637,7 @@ int main(int argc, const char *const *argv) {
 
     record_baseline_time();
     become_pgrp();
+    start_logging();
     setup_handlers();
     spawn_script();
     queue_alarm();
@@ -732,6 +756,15 @@ static void queue_alarm(void) {
   alarm(check_interval);
 }
 
+static void start_logging(void) {
+  int r;
+
+  openlog(script, LOG_NOWAIT|LOG_PID, LOG_USER);
+  logging = 1;
+  r = dup2(1,2);
+  if (r!=2) diee("dup2 stdout to stderr");
+}
+
 static void await_something(void) {
   int r;
   sigset_t mask;