rewrote some parts to cope better with '-o' options (required for -bme
[util-vserver.git] / util-vserver / src / vserver-info.c
index b7ccbdb..0231ac8 100644 (file)
@@ -20,6 +20,7 @@
 #  include <config.h>
 #endif
 
+#include "lib/utils-legacy.h"
 #include "pathconfig.h"
 #include "util.h"
 
 #include <fcntl.h>
 #include <errno.h>
 #include <sys/utsname.h>
+#include <dirent.h>
 
 #define ENSC_WRAPPERS_FCNTL    1
 #define ENSC_WRAPPERS_IO       1
 #define ENSC_WRAPPERS_UNISTD   1
+#define ENSC_WRAPPERS_VSERVER  1
 #include <wrappers.h>
 
 typedef enum { tgNONE,tgCONTEXT, tgRUNNING,
@@ -177,7 +180,7 @@ getXid(char *buf, char const *vserver)
 }
 
 static char *
-getInitPid(char *buf, xid_t xid)
+getInitPid_native(char *buf, xid_t xid)
 {
   struct vc_vx_info            info;
   
@@ -190,6 +193,71 @@ getInitPid(char *buf, xid_t xid)
   return 0;
 }
 
+#if defined(VC_ENABLE_API_COMPAT) || defined(VC_ENABLE_API_V11)
+static int
+selectPid(struct dirent const *ent)
+{
+  return atoi(ent->d_name)!=0;
+}
+
+static bool
+getInitPid_internal(pid_t pid, xid_t xid, pid_t *res)
+{
+  *res = -1;
+  
+  for (;*res==-1;) {
+    size_t                     bufsize = utilvserver_getProcEntryBufsize();
+    char                       buf[bufsize+1];
+    char                       *pos = 0;
+
+    pos = utilvserver_getProcEntry(pid, "\ns_context: ", buf, bufsize);
+    if (pos==0 && errno==EAGAIN) continue;
+
+    if (pos==0 || (xid_t)atoi(pos)!=xid) return false;
+
+    buf[bufsize] = '\0';
+    pos          = strstr(buf, "\ninitpid: ");
+    
+    if (pos!=0) {
+      pos         += sizeof("\ninitpid: ")-1;
+      if (strncmp(pos, "none", 4)==0) *res = -1;
+      else                            *res = atoi(pos);
+    }
+  }
+
+  return true;
+}
+
+static char *
+getInitPid_emulated(char *buf, xid_t xid)
+{
+  struct dirent **namelist;
+  int          n;
+  
+  vc_new_s_context(1,0,0);     // ignore errors silently...
+  n = scandir("/proc", &namelist, selectPid, alphasort);
+  if (n<0) perror("scandir()");
+  else while (n--) {
+    pid_t      pid;
+    if (!getInitPid_internal(atoi(namelist[n]->d_name), xid, &pid)) continue;
+
+    utilvserver_fmt_long(buf, pid);
+    return buf;
+  }
+
+  return 0;
+}
+#endif // VC_ENABLE_API_COMPAT
+
+static char *
+getInitPid(char *buf, xid_t xid)
+{
+  if (vc_isSupported(vcFEATURE_VINFO))
+    return getInitPid_native(buf, xid);
+  else
+    return getInitPid_emulated(buf, xid);
+}
+
 static char *
 getInitPidPid(char *buf, char const *vserver)
 {
@@ -310,7 +378,7 @@ execQuery(char const *vserver, VserverTag tag, int argc, char *argv[])
 {
   char const *         res = 0;
   char                         buf[sizeof(xid_t)*4 + 1024];
-  xid_t                        xid = *vserver!='\0' ? (xid_t)(atoi(vserver)) : VC_SAMECTX;
+  xid_t                        xid = *vserver!='\0' ? vc_xidopt2xid(vserver,true,0) : VC_SAMECTX;
 
   memset(buf, 0, sizeof buf);
   switch (tag) {