LRN: Fix automake deps to allow -j* builds again
[oweals/gnunet.git] / src / util / os_priority.c
index e9ca9deea3060205ff2a102887ecc7478394fb94..f2e3f3c382fa54a89c418bd1267a04f3b1856289 100644 (file)
@@ -1,6 +1,6 @@
 /*
      This file is part of GNUnet
-     (C) 2002, 2003, 2004, 2005, 2006 Christian Grothoff (and other contributing authors)
+     (C) 2002, 2003, 2004, 2005, 2006, 2011 Christian Grothoff (and other contributing authors)
 
      GNUnet is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -47,68 +47,95 @@ static struct GNUNET_OS_Process current_process;
 
 /**
  * This handler is called when there are control data to be read on the pipe
+ *
+ * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
+ * @param tc scheduler context
  */
-void
-GNUNET_OS_parent_control_handler (void *cls,
-                                  const struct
-                                  GNUNET_SCHEDULER_TaskContext * tc)
+static void
+parent_control_handler (void *cls,
+                       const struct
+                       GNUNET_SCHEDULER_TaskContext * tc)
 {
   struct GNUNET_DISK_FileHandle *control_pipe = (struct GNUNET_DISK_FileHandle *) cls;
   int sig;
 
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__, tc->reason);
-
+#if DEBUG_OS
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
+             "`%s' invoked because of %d\n",
+             __FUNCTION__,
+             tc->reason);
+#endif
   if (tc->reason & (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT | GNUNET_SCHEDULER_REASON_PREREQ_DONE))
-  {
-    GNUNET_DISK_npipe_close (control_pipe);
-  }
-  else
-  {
-    if (GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)) != sizeof (sig))
     {
-      GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
       GNUNET_DISK_npipe_close (control_pipe);
     }
-    else
+  else
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n", sig);
-      raise (sig);
-      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Re-scheduling the parent control handler pipe\n");
-      GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe, GNUNET_OS_parent_control_handler, control_pipe);
+      if (GNUNET_DISK_file_read (control_pipe, 
+                                &sig, 
+                                sizeof (sig)) != sizeof (sig))
+       {
+         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
+                              "GNUNET_DISK_file_read");
+         GNUNET_DISK_npipe_close (control_pipe);
+       }
+      else
+       {
+#if DEBUG_OS
+         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
+                     "Got control code %d from parent\n", sig);
+#endif
+         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 
+                                         control_pipe, 
+                                         &parent_control_handler, control_pipe);
+         raise (sig);
+       }
     }
-  }
 }
 
+
 /**
- * Connects this process to its parent via pipe
+ * Task that connects this process to its parent via pipe
  */
 void
 GNUNET_OS_install_parent_control_handler (void *cls,
                                           const struct
                                           GNUNET_SCHEDULER_TaskContext * tc)
 {
-  char *env_buf;
-  struct GNUNET_DISK_FileHandle *control_pipe = NULL;
+  const char *env_buf;
+  struct GNUNET_DISK_FileHandle *control_pipe;
 
   env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
-  if (env_buf == NULL || strlen (env_buf) <= 0)
-  {
-    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not installing a handler because %s=%s\n", GNUNET_OS_CONTROL_PIPE, env_buf);
-    return;
-  }
-
-  control_pipe = GNUNET_DISK_npipe_open (env_buf, GNUNET_DISK_OPEN_READ,
-        GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
+  if ( (env_buf == NULL) || (strlen (env_buf) <= 0) )
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
+                 _("Not installing a handler because $%s=%s\n"), 
+                 GNUNET_OS_CONTROL_PIPE, 
+                 env_buf);
+      return;
+    }
+  control_pipe = GNUNET_DISK_npipe_open (env_buf,
+                                        GNUNET_DISK_OPEN_READ,
+                                        GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
   if (control_pipe == NULL)
-  {
-    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to open the pipe `%s'\n", env_buf);
-    return;
-  }
-
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
-  GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe, GNUNET_OS_parent_control_handler, control_pipe);
+    {
+      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
+                               "open",
+                               env_buf);
+      return;
+    }
+#if DEBUG_OS
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+             "Adding parent control handler pipe `%s' to the scheduler\n", 
+             env_buf);
+#endif
+  GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 
+                                 control_pipe, 
+                                 &parent_control_handler, 
+                                 control_pipe);
 }
 
+
 /**
  * Get process structure for current process
  *
@@ -129,28 +156,55 @@ GNUNET_OS_process_current ()
   return &current_process;
 }
 
+
 int
 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
 {
 #if ENABLE_WINDOWS_WORKAROUNDS
-  int res;
-  int ret;
+  int res = 0;
+  int ret = 0;
 
   ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof(sig));
   if (ret != sizeof(sig))
   {
     if (errno == ECOMM)
+    {
       /* Child process is not controllable via pipe */
+#if DEBUG_OS
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
           "Child process is not controllable, will kill it directly\n");
+#endif
+    }
+    else if (errno == EPIPE)
+    {
+#if DEBUG_OS
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+          "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
+#endif
+    }
     else
-      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
           "Failed to write into control pipe , errno is %d\n", errno);
-    res = PLIBC_KILL (proc->pid, sig);
+#if WINDOWS && !defined(__CYGWIN__)
+    TerminateProcess (proc->handle, 0);
+#else
+    PLIBC_KILL (proc->pid, sig);
+#endif
   }
   else
   {
-       struct GNUNET_NETWORK_FDSet *rfds;
+#if DEBUG_OS
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+        "Wrote control code into control pipe, now waiting\n");
+#endif
+
+#if WINDOWS
+    /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
+    if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
+      TerminateProcess (proc->handle, 0);
+    res = 0;
+#else
+    struct GNUNET_NETWORK_FDSet *rfds;
     struct GNUNET_NETWORK_FDSet *efds;
 
     rfds = GNUNET_NETWORK_fdset_create ();
@@ -159,33 +213,43 @@ GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
     GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
     GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
 
- read_next:
-        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-            "Wrote control code into control pipe, now waiting\n");
-
-        ret = GNUNET_NETWORK_socket_select (rfds, NULL, efds,
-            GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_unit (),
-                5000));
-
-        if (ret < 1 || GNUNET_NETWORK_fdset_handle_isset (efds,
-            proc->control_pipe))
-          {
-            /* Just to be sure */
-            PLIBC_KILL (proc->pid, sig);
-            res = 0;
-          }
-        else
-          {
-            if (GNUNET_DISK_file_read (proc->control_pipe, &ret,
-                sizeof(ret)) != GNUNET_OK)
-              res = PLIBC_KILL (proc->pid, sig);
-
-            /* Child signaled shutdown is in progress */
-            goto read_next;
-          }
-      }
+    /* Ndurner thought this up, and i have no idea what it does.
+     * There's have never been any code to answer the shutdown call
+     * (write a single int into the pipe, so that this function can read it).
+     * On *nix select() will probably tell that pipe is ready
+     * for reading, once the other process shuts down,
+     * but the read () call will fail, triggering a kill ()
+     * on the pid that is already dead. This will probably result in non-0
+     * return from kill(), and therefore from this function.
+     */
+    while (1)
+    {
+      ret = GNUNET_NETWORK_socket_select (rfds, NULL, efds,
+          GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_unit (),
+              5000));
 
-    return res;
+      if (ret < 1 || GNUNET_NETWORK_fdset_handle_isset (efds,
+          proc->control_pipe))
+        {
+          /* Just to be sure */
+          PLIBC_KILL (proc->pid, sig);
+          res = 0;
+          break;
+        }
+      else
+        {
+          if (GNUNET_DISK_file_read (proc->control_pipe, &ret,
+              sizeof(ret)) != GNUNET_OK)
+            res = PLIBC_KILL (proc->pid, sig);
+
+          /* Child signaled shutdown is in progress */
+          continue;
+        }
+     }
+#endif
+  }
+
+  return res;
 #else
   return kill (proc->pid, sig);
 #endif
@@ -204,6 +268,7 @@ GNUNET_OS_process_get_pid (struct GNUNET_OS_Process *proc)
   return proc->pid;
 }
 
+
 void
 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
 {
@@ -348,8 +413,10 @@ GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
         }
     }
 #else
+#if DEBUG_OS
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
              "Priority management not availabe for this platform\n");
+#endif
 #endif
   return GNUNET_OK;
 }
@@ -372,7 +439,7 @@ CreateCustomEnvTable (char **vars)
     return NULL;
   for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++);
   n_var = c;
-  index = GNUNET_malloc (n_var);
+  index = GNUNET_malloc (sizeof (char *) * n_var);
   for (c = 0; c < n_var; c++)
     index[c] = 0;
   for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
@@ -453,19 +520,21 @@ CreateCustomEnvTable (char **vars)
 }
 #endif
 
+
 /**
  * Start a process.
  *
  * @param pipe_stdin pipe to use to send input to child process (or NULL)
  * @param pipe_stdout pipe to use to get output from child process (or NULL)
  * @param filename name of the binary
- * @param ... NULL-terminated list of arguments to the process
+ * @param va NULL-terminated list of arguments to the process
  * @return pointer to process structure of the new process, NULL on error
  */
 struct GNUNET_OS_Process *
-GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin, 
-                        struct GNUNET_DISK_PipeHandle *pipe_stdout,
-                        const char *filename, ...)
+GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin, 
+                           struct GNUNET_DISK_PipeHandle *pipe_stdout,
+                           const char *filename, 
+                           va_list va)
 {
   va_list ap;
 #if ENABLE_WINDOWS_WORKAROUNDS
@@ -492,13 +561,13 @@ GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
 #endif
 
   argc = 0;
-  va_start (ap, filename);
+  va_copy (ap, va);
   while (NULL != va_arg (ap, char *))
       argc++;
   va_end (ap);
   argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
   argc = 0;
-  va_start (ap, filename);
+  va_copy (ap, va);
   while (NULL != (argv[argc] = va_arg (ap, char *)))
     argc++;
   va_end (ap);
@@ -647,18 +716,18 @@ GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
   GNUNET_free (non_const_filename);
  
   cmdlen = 0;
-  va_start (ap, filename);
+  va_copy (ap, va);
   while (NULL != (arg = va_arg (ap, char *)))
-  {
+    {
       if (cmdlen == 0)
         cmdlen = cmdlen + strlen (path) + 3;
       else
         cmdlen = cmdlen + strlen (arg) + 3;
-  }
+    }
   va_end (ap);
 
   cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
-  va_start (ap, filename);
+  va_copy (ap, va);
   while (NULL != (arg = va_arg (ap, char *)))
   {
       if (idx == cmd)
@@ -696,7 +765,11 @@ GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
     return NULL;
   }
 
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n", childpipename);
+#if DEBUG_OS
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
+             "Opened the parent end of the pipe `%s'\n", 
+             childpipename);
+#endif
 
   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
   GNUNET_asprintf (&our_env[1], "%s", childpipename);
@@ -732,10 +805,37 @@ GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
 
   return gnunet_proc;
 #endif
-
 }
 
 
+/**
+ * Start a process.
+ *
+ * @param pipe_stdin pipe to use to send input to child process (or NULL)
+ * @param pipe_stdout pipe to use to get output from child process (or NULL)
+ * @param filename name of the binary
+ * @param ... NULL-terminated list of arguments to the process
+ *
+ * @return pointer to process structure of the new process, NULL on error
+ *
+ */
+struct GNUNET_OS_Process *
+GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin, 
+                        struct GNUNET_DISK_PipeHandle *pipe_stdout,
+                        const char *filename, ...)
+{
+  struct GNUNET_OS_Process *ret;
+  va_list ap;
+
+  va_start (ap, filename);
+  ret = GNUNET_OS_start_process_va (pipe_stdin,
+                                   pipe_stdout,
+                                   filename,
+                                   ap);
+  va_end (ap);
+  return ret;
+}
+
 
 /**
  * Start a process.
@@ -1007,7 +1107,9 @@ GNUNET_OS_start_process_v (const int *lsocks,
     return NULL;
   }
 
+#if DEBUG_OS
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n", childpipename);
+#endif
 
   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
   GNUNET_asprintf (&our_env[1], "%s", childpipename);
@@ -1044,6 +1146,7 @@ GNUNET_OS_start_process_v (const int *lsocks,
 #endif
 }
 
+
 /**
  * Retrieve the status of a process
  * @param proc process ID
@@ -1141,6 +1244,7 @@ GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
   return GNUNET_OK;
 }
 
+
 /**
  * Wait for a process
  * @param proc pointer to process structure
@@ -1184,4 +1288,198 @@ GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
 }
 
 
+/**
+ * Handle to a command.
+ */
+struct GNUNET_OS_CommandHandle
+{
+
+  /**
+   * Process handle.
+   */
+  struct GNUNET_OS_Process *eip;
+
+  /**
+   * Handle to the output pipe.
+   */
+  struct GNUNET_DISK_PipeHandle *opipe;
+  
+  /**
+   * Read-end of output pipe.
+   */
+  const struct GNUNET_DISK_FileHandle *r;
+
+  /**
+   * Function to call on each line of output.
+   */
+  GNUNET_OS_LineProcessor proc;
+
+  /**
+   * Closure for 'proc'.
+   */
+  void *proc_cls;
+                      
+  /**
+   * Buffer for the output.
+   */
+  char buf[1024];
+  
+  /**
+   * Task reading from pipe.
+   */
+  GNUNET_SCHEDULER_TaskIdentifier rtask;
+
+  /**
+   * When to time out.
+   */
+  struct GNUNET_TIME_Absolute timeout;
+
+  /**
+   * Current read offset in buf.
+   */
+  size_t off;
+};
+
+
+/**
+ * Stop/kill a command.  Must ONLY be called either from
+ * the callback after 'NULL' was passed for 'line' *OR*
+ * from an independent task (not within the line processor).
+ *
+ * @param cmd handle to the process
+ */
+void
+GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
+{
+
+  if (cmd->proc != NULL)
+    {
+      GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
+      GNUNET_SCHEDULER_cancel (cmd->rtask);
+    }
+  (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
+  GNUNET_break (GNUNET_OK ==
+               GNUNET_OS_process_wait (cmd->eip));
+  GNUNET_OS_process_close (cmd->eip);
+  GNUNET_DISK_pipe_close (cmd->opipe);
+  GNUNET_free (cmd);
+}
+
+
+/**
+ * Read from the process and call the line processor.
+ *
+ * @param cls the 'struct GNUNET_OS_CommandHandle'
+ * @param tc scheduler context
+ */
+static void
+cmd_read (void *cls,
+         const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct GNUNET_OS_CommandHandle *cmd = cls;
+  GNUNET_OS_LineProcessor proc;
+  char *end;
+  ssize_t ret;
+
+  cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
+  if (GNUNET_YES !=
+      GNUNET_NETWORK_fdset_handle_isset (tc->read_ready,
+                                        cmd->r))
+    {
+      /* timeout, shutdown, etc. */
+      proc = cmd->proc;
+      cmd->proc = NULL;
+      proc (cmd->proc_cls, NULL);
+      return;
+    }                                   
+  ret = GNUNET_DISK_file_read (cmd->r,
+                              &cmd->buf[cmd->off], 
+                              sizeof (cmd->buf)-cmd->off);
+  if (ret <= 0)
+    {
+      if ( (cmd->off > 0) && (cmd->off < sizeof (cmd->buf)) )
+       {
+         cmd->buf[cmd->off] = '\0';
+         cmd->proc (cmd->proc_cls, cmd->buf);
+       }
+      proc = cmd->proc;
+      cmd->proc = NULL;
+      proc (cmd->proc_cls, NULL);
+      return;
+    }    
+  end = memchr (&cmd->buf[cmd->off], '\n', ret);
+  cmd->off += ret;
+  while (end != NULL)
+    {
+      *end = '\0';
+      cmd->proc (cmd->proc_cls, cmd->buf);
+      memmove (cmd->buf, 
+              end + 1, 
+              cmd->off - (end + 1 - cmd->buf));
+      cmd->off -= (end + 1 - cmd->buf);
+      end = memchr (cmd->buf, '\n', cmd->off);
+    }    
+  cmd->rtask = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining (cmd->timeout),
+                                              cmd->r,
+                                              &cmd_read,
+                                              cmd);
+}
+
+
+/**
+ * Run the given command line and call the given function
+ * for each line of the output.
+ *
+ * @param proc function to call for each line of the output
+ * @param proc_cls closure for proc
+ * @param timeout when to time out
+ * @param binary command to run
+ * @param ... arguments to command
+ * @return NULL on error
+ */
+struct GNUNET_OS_CommandHandle *
+GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc,
+                      void *proc_cls,
+                      struct GNUNET_TIME_Relative timeout,
+                      const char *binary,
+                      ...)
+{
+  struct GNUNET_OS_CommandHandle *cmd;
+  struct GNUNET_OS_Process *eip;
+  struct GNUNET_DISK_PipeHandle *opipe;
+  va_list ap;
+
+  opipe = GNUNET_DISK_pipe (GNUNET_YES,
+                           GNUNET_NO,
+                           GNUNET_YES);
+  if (NULL == opipe)
+    return NULL;
+  va_start (ap, binary);
+  eip = GNUNET_OS_start_process_va (NULL, opipe,
+                                   binary, ap);
+  va_end (ap);
+  if (NULL == eip)
+    {
+      GNUNET_DISK_pipe_close (opipe);
+      return NULL;
+    }
+  GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
+  cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
+  cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
+  cmd->eip = eip;
+  cmd->opipe = opipe;
+  cmd->proc = proc;
+  cmd->proc_cls = proc_cls;
+  cmd->r = GNUNET_DISK_pipe_handle (opipe,
+                                    GNUNET_DISK_PIPE_END_READ);
+  cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout,
+                                              cmd->r,
+                                              &cmd_read,
+                                              cmd);
+  return cmd;
+}
+
+
+
+
 /* end of os_priority.c */