minor optimizations
[util-vserver.git] / util-vserver / src / vserver-info.c
1 // $Id$    --*- c -*--
2
3 // Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 //  
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; version 2 of the License.
8 //  
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //  
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18
19 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include "lib/utils-legacy.h"
24 #include "pathconfig.h"
25 #include "util.h"
26
27 #include "internal.h"
28 #include "vserver.h"
29
30 #include <stdlib.h>
31 #include <getopt.h>
32 #include <assert.h>
33 #include <stdbool.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #include <sys/utsname.h>
37 #include <dirent.h>
38 #include <strings.h>
39
40 #define ENSC_WRAPPERS_FCNTL     1
41 #define ENSC_WRAPPERS_IO        1
42 #define ENSC_WRAPPERS_UNISTD    1
43 #define ENSC_WRAPPERS_VSERVER   1
44 #include <wrappers.h>
45
46 typedef enum { tgNONE,tgCONTEXT, tgID, tgRUNNING,
47                tgVDIR, tgNAME, tgCFGDIR, tgAPPDIR,
48                tgAPIVER, tgPXID,
49                tgINITPID, tgINITPID_PID,
50                tgXID, tgUTS, tgSYSINFO,
51                tgFEATURE, tgCANONIFY,
52 }       VserverTag;
53
54 static struct {
55     char const * const  tag;
56     VserverTag const    val;
57     char const * const  descr;
58 }  const TAGS[] = {
59   { "CONTEXT", tgCONTEXT, ("the current and/or assigned context; when an optinal argument "
60                            "evaluates to false,only the current context will be printed") },
61   { "ID",      tgID,      "gives out the vserver-id for the context-xid" },
62   { "RUNNING", tgRUNNING, "gives out '1' when vserver is running; else, it fails without output" },
63   { "VDIR",    tgVDIR,    "gives out the root-directory of the vserver" },
64   { "NAME",    tgNAME,    "gives out the name of the vserver" },
65   { "CFGDIR",  tgCFGDIR,  "gives out the configuration directory of the vserver" },
66   { "APPDIR",  tgAPPDIR,  "gives out the name of the toplevel application cfgdir" },
67   { "INITPID",     tgINITPID,     "gives out the initpid of the given context" },
68   { "INITPID_PID", tgINITPID_PID, "gives out the initpid of the given pid" },
69   { "XID",         tgXID,         "gives out the context-id of the given pid" },
70   { "APIVER",      tgAPIVER,      "gives out the version of the kernel API" },
71   { "UTS",         tgUTS,         ("gives out an uts-entry; possible entries are "
72                                    "context, sysname, nodename, release, version, "
73                                    "machine and domainname") },
74   { "SYSINFO",     tgSYSINFO,     "gives out information about the systen" },
75   { "FEATURE",     tgFEATURE,     "returns 0 iff the queried feature is supported" },
76   { "PXID",        tgPXID,        "returns the xid of the parent context" },
77   { "CANONIFY",    tgCANONIFY,    "canonifies the vserver-name and removes dangerous characters" },
78 };
79
80 int wrapper_exit_code = 1;
81
82 static struct option const
83 CMDLINE_OPTIONS[] = {
84   { "help",     no_argument,  0, 'h' },
85   { "version",  no_argument,  0, 'v' },
86   { 0,0,0,0 }
87 };
88
89
90 static void
91 showHelp(int fd, char const *cmd, int res)
92 {
93   WRITE_MSG(fd, "Usage:  ");
94   WRITE_STR(fd, cmd);
95   WRITE_MSG(fd,
96             " [-ql] <vserver>|<pid>|<context> <tag>\n"
97             "Please report bugs to " PACKAGE_BUGREPORT "\n");
98   exit(res);
99 }
100
101 static void
102 showVersion()
103 {
104   WRITE_MSG(1,
105             "vserver-info " VERSION " -- returns information about vservers\n"
106             "This program is part of " PACKAGE_STRING "\n\n"
107             "Copyright (C) 2003 Enrico Scholz\n"
108             VERSION_COPYRIGHT_DISCLAIMER);
109   exit(0);
110 }
111
112 static void
113 showTags()
114 {
115   char const *          delim = "";
116   size_t        i;
117
118   WRITE_MSG(1, "Valid tags are: ");
119   for (i=0; i<DIM_OF(TAGS); ++i) {
120     WRITE_STR(1, delim);
121     WRITE_STR(1, TAGS[i].tag);
122
123     delim = ", ";
124   }
125   WRITE_MSG(1, "\n");
126   exit(0);
127 }
128
129 static VserverTag
130 stringToTag(char const *str)
131 {
132   size_t        i;
133   for (i=0; i<DIM_OF(TAGS); ++i)
134     if (strcmp(TAGS[i].tag, str)==0) return TAGS[i].val;
135
136   return tgNONE;
137 }
138
139 static vc_uts_type
140 utsText2Tag(char const *str)
141 {
142   if      (strcmp(str, "context")   ==0) return vcVHI_CONTEXT;
143   else if (strcmp(str, "sysname")   ==0) return vcVHI_SYSNAME;
144   else if (strcmp(str, "nodename")  ==0) return vcVHI_NODENAME;
145   else if (strcmp(str, "release")   ==0) return vcVHI_RELEASE;
146   else if (strcmp(str, "version")   ==0) return vcVHI_VERSION;
147   else if (strcmp(str, "machine")   ==0) return vcVHI_MACHINE;
148   else if (strcmp(str, "domainname")==0) return vcVHI_DOMAINNAME;
149   else {
150     WRITE_MSG(2, "Unknown UTS tag\n");
151     exit(1);
152   }
153 }
154
155 static char *
156 getAPIVer(char *buf)
157 {
158   int           v = vc_get_version();
159   size_t        l;
160   
161   if (v==-1) return 0;
162
163   
164   l = utilvserver_fmt_xulong(0, (unsigned int)v);
165   memcpy(buf, "0x00000000", 10);
166   utilvserver_fmt_xulong(buf+2+8-l, (unsigned int)v);
167
168   return buf;
169 }
170
171 static char *
172 getXid(char *buf, char const *vserver)
173 {
174   pid_t         pid = atoi(vserver);
175   xid_t         xid = vc_get_task_xid(pid);
176
177   if (xid==VC_NOCTX) perror("vc_get_task_xid()");
178   else {
179     utilvserver_fmt_long(buf, xid);
180     return buf;
181   }
182
183   return 0;
184 }
185
186 static char *
187 getPXid(char UNUSED *buf, char const UNUSED *vserver)
188 {
189   // TODO: implement me when available
190   return 0;
191 }
192
193 static char *
194 getInitPid_native(char *buf, xid_t xid)
195 {
196   struct vc_vx_info             info;
197   
198   if (vc_get_vx_info(xid, &info)==-1) perror("vc_get_vx_info()");
199   else {
200     utilvserver_fmt_long(buf, info.initpid);
201     return buf;
202   }
203
204   return 0;
205 }
206
207 #if defined(VC_ENABLE_API_COMPAT) || defined(VC_ENABLE_API_V11)
208 static int
209 selectPid(struct dirent const *ent)
210 {
211   return atoi(ent->d_name)!=0;
212 }
213
214 static bool
215 getInitPid_internal(pid_t pid, xid_t xid, pid_t *res)
216 {
217   *res = -1;
218   
219   for (;*res==-1;) {
220     size_t                      bufsize = utilvserver_getProcEntryBufsize();
221     char                        buf[bufsize+1];
222     char                        *pos = 0;
223
224     pos = utilvserver_getProcEntry(pid, "\ns_context: ", buf, bufsize);
225     if (pos==0 && errno==EAGAIN) continue;
226
227     if (pos==0 || (xid_t)atoi(pos)!=xid) return false;
228
229     buf[bufsize] = '\0';
230     pos          = strstr(buf, "\ninitpid: ");
231     
232     if (pos!=0) {
233       pos       += sizeof("\ninitpid: ")-1;
234       if (strncmp(pos, "none", 4)==0) *res = -1;
235       else                            *res = atoi(pos);
236     }
237   }
238
239   return true;
240 }
241
242 static char *
243 getInitPid_emulated(char *buf, xid_t xid)
244 {
245   struct dirent **namelist;
246   int           n;
247
248   switchToWatchXid(0);  // ignore errors silently...
249   n = scandir("/proc", &namelist, selectPid, alphasort);
250   if (n<0) perror("scandir()");
251   else while (n--) {
252     pid_t       pid;
253     if (!getInitPid_internal(atoi(namelist[n]->d_name), xid, &pid)) continue;
254
255     utilvserver_fmt_long(buf, pid);
256     return buf;
257   }
258
259   return 0;
260 }
261 #endif // VC_ENABLE_API_COMPAT
262
263 static char *
264 getInitPid(char *buf, xid_t xid)
265 {
266   if (vc_isSupported(vcFEATURE_VINFO))
267     return getInitPid_native(buf, xid);
268   else
269     return getInitPid_emulated(buf, xid);
270 }
271
272 static char *
273 getInitPidPid(char *buf, char const *vserver)
274 {
275   struct vc_vx_info     info;
276   pid_t                 pid = atoi(vserver);
277   xid_t                 xid = vc_get_task_xid(pid);
278
279   if (xid==VC_NOCTX) perror("vc_get_task_xid()");
280   else if (vc_get_vx_info(xid, &info)==-1) perror("vc_get_vx_info()");
281   else {
282     utilvserver_fmt_long(buf, info.initpid);
283     return buf;
284   }
285
286   return 0;
287 }
288
289 static char *
290 getUTS(char *buf, xid_t xid, size_t argc, char * argv[])
291 {
292   if (argc>0) {
293     vc_uts_type type = utsText2Tag(argv[0]);
294     if (vc_get_vhi_name(xid, type, buf, sizeof(buf)-1)==-1)
295       perror("vc_get_vhi_name()");
296     else
297       return buf;
298   }
299   else {
300     bool                is_passed = false;
301     char                tmp[128];
302 #define APPEND_UTS(TYPE)                                                \
303     (((vc_get_vhi_name(xid, TYPE, tmp, sizeof(tmp)-1)!=-1) && (strcat(buf, tmp), strcat(buf, " "), is_passed=true)) || \
304      (strcat(buf, "??? ")))
305
306     if (APPEND_UTS(vcVHI_CONTEXT) &&
307         APPEND_UTS(vcVHI_SYSNAME) &&
308         APPEND_UTS(vcVHI_NODENAME) &&
309         APPEND_UTS(vcVHI_RELEASE) &&
310         APPEND_UTS(vcVHI_VERSION) &&
311         APPEND_UTS(vcVHI_MACHINE) &&
312         APPEND_UTS(vcVHI_DOMAINNAME) &&
313         is_passed)
314       return buf;
315
316     perror("vc_get_vhi_name()");
317 #undef APPEND_UTS
318   }
319
320   return 0;
321 }
322
323 static int
324 printSysInfo(char *buf)
325 {
326   int                   fd = open(PKGLIBDIR "/FEATURES.txt", O_RDONLY);
327   struct utsname        uts;
328
329   if (uname(&uts)==-1)
330     perror("uname()");
331   else {
332     WRITE_MSG(1,
333               "Versions:\n"
334               "                   Kernel: ");
335     WRITE_STR(1, uts.release);
336     WRITE_MSG(1, "\n"
337               "                   VS-API: ");
338
339     memset(buf, 0, 128);
340     if (getAPIVer(buf)) WRITE_STR(1, buf);
341     else                WRITE_MSG(1, "???");
342     
343     WRITE_MSG(1, "\n"
344               "             util-vserver: " PACKAGE_VERSION "; " __DATE__ ", " __TIME__"\n"
345               "\n");
346   }
347
348   if (fd==-1)
349     WRITE_MSG(1, "FEATURES.txt not found\n");
350   else {
351     off_t               l  = Elseek(fd, 0, SEEK_END);
352     Elseek(fd, 0, SEEK_SET);
353     {
354       char              buf[l];
355       EreadAll(fd, buf, l);
356       EwriteAll(1, buf, l);
357     }
358     Eclose(fd);
359   }
360
361   return EXIT_SUCCESS;
362 }
363
364 static char *
365 getContext(char *buf, char const *vserver, bool allow_only_static)
366 {
367   xid_t         xid = vc_getVserverCtx(vserver, vcCFG_AUTO,
368                                        allow_only_static, 0);
369   if (xid==VC_NOCTX) return 0;
370   
371   utilvserver_fmt_long(buf, xid);
372   return buf;
373 }
374
375 static int
376 testFeature(int argc, char *argv[])
377 {
378   return (argc>0 && vc_isSupportedString(argv[0])) ? EXIT_SUCCESS : EXIT_FAILURE;
379 }
380
381 static bool
382 str2bool(char const *str)
383 {
384   return atoi(str)!=0 || strchr("yYtY", str[0])!=0 || strcasecmp("true", str)==0;
385 }
386
387 static int
388 execQuery(char const *vserver, VserverTag tag, int argc, char *argv[])
389 {
390   char const *          res = 0;
391   char                  buf[sizeof(xid_t)*4 + 1024 + strlen(vserver)];
392
393   memset(buf, 0, sizeof buf);
394   switch (tag) {
395     case tgNAME         :  res = vc_getVserverName(vserver, vcCFG_AUTO); break;
396     case tgVDIR         :
397       res = vc_getVserverVdir(vserver, vcCFG_AUTO, argc>0 && atoi(argv[0]));
398       break;
399     case tgCFGDIR       :  res = vc_getVserverCfgDir(vserver, vcCFG_AUTO);     break;
400     case tgAPPDIR       :
401       res = vc_getVserverAppDir(vserver, vcCFG_AUTO, argc==0 ? "" : argv[0]);
402       break;
403       
404     case tgRUNNING      :
405       res = (vc_getVserverCtx(vserver, vcCFG_AUTO, false, 0)==VC_NOCTX) ? 0 : "1";
406       break;
407
408     case tgCANONIFY     :
409       strcpy(buf, vserver);
410       if (canonifyVserverName(buf)>0) res = buf;
411       break;
412       
413     case tgCONTEXT      :  res = getContext(buf, vserver,
414                                             argc==0 || str2bool(argv[0])); break;
415     case tgINITPID_PID  :  res = getInitPidPid(buf, vserver);  break;
416     case tgAPIVER       :  res = getAPIVer(buf);               break;
417     case tgXID          :  res = getXid(buf, vserver);         break;
418     case tgPXID         :  res = getPXid(buf, vserver);        break;
419     case tgSYSINFO      :  return printSysInfo(buf);           break;
420     case tgFEATURE      :  return testFeature(argc,argv);      break;
421
422
423     default             : {
424       xid_t             xid = *vserver!='\0' ? vc_xidopt2xid(vserver,true,0) : VC_SAMECTX;
425
426       switch (tag) {
427         case tgID       :  res = vc_getVserverByCtx(xid,0,0);  break;
428         case tgINITPID  :  res = getInitPid(buf, xid);         break;
429         case tgUTS      :  res = getUTS(buf, xid, argc, argv); break;
430     
431         default         :  assert(false); abort();  // TODO
432       }
433     }
434   }
435
436   if (res==0) return EXIT_FAILURE;
437   WRITE_STR(1, res);
438   WRITE_MSG(1, "\n");
439   return EXIT_SUCCESS;
440 }
441
442 int main(int argc, char *argv[])
443 {
444   bool          quiet = false;
445   char const *  vserver;
446   VserverTag    tag;
447   
448   while (1) {
449     int         c = getopt_long(argc, argv, "ql", CMDLINE_OPTIONS, 0);
450     if (c==-1) break;
451
452     switch (c) {
453       case 'h'          :  showHelp(1, argv[0], 0);
454       case 'v'          :  showVersion();
455       case 'l'          :  showTags();
456       case 'q'          :  quiet = true; break;
457       default           :
458         WRITE_MSG(2, "Try '");
459         WRITE_STR(2, argv[0]);
460         WRITE_MSG(2, " --help\" for more information.\n");
461         exit(1);
462         break;
463     }
464   }
465
466   if (optind+2>argc) {
467     execQuery("-", tgSYSINFO, 0, 0);
468     WRITE_MSG(2, "\nAssumed 'SYSINFO' as no other option given; try '--help' for more information.\n");
469     exit(0);
470   }
471
472   vserver = argv[optind];
473   tag     = stringToTag(argv[optind+1]);
474
475   if (tag==tgNONE) {
476     WRITE_MSG(2, "Unknown tag; use '-l' to get list of valid tags\n");
477     exit(1);
478   }
479
480   if (quiet) {
481     int         fd = Eopen("/dev/null", O_WRONLY, 0644);
482     Edup2(fd, 1);
483     Eclose(fd);
484   }
485
486   return execQuery(vserver, tag, argc-(optind+2), argv+optind+2);
487 }