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