0c212bef44796071c7c490f9d8fb09197d39687d
[util-vserver.git] / util-vserver / lib / getvservername.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 "vserver.h"
24 #include "pathconfig.h"
25
26 #include <string.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <libgen.h>
30
31 static char *
32 getRecentName(char *start, char *end)
33 {
34   char          *res = 0;
35   int           fd;
36   
37   strcpy(end, "/name");
38   fd = open(start, O_RDONLY);
39   if (fd!=-1) {
40     off_t       len;
41
42     if ((len=lseek(fd, 0, SEEK_END))!=-1 &&
43         (len<VC_LIMIT_VSERVER_NAME_LEN) &&
44         (lseek(fd, 0, SEEK_SET)!=-1)) {
45       char      buf[len+1];
46
47       if (TEMP_FAILURE_RETRY(read(fd, buf, len+1))==len) {
48         while (len>0 && buf[len-1]=='\n') --len;
49         buf[len] = '\0';
50         if (len>0) res = buf;
51       }
52
53       close(fd);
54       return strdup(res);
55     }
56
57     close(fd);
58   }
59
60   if (res==0) {
61     *end = '\0';
62     res  = basename(start);
63   }
64
65   return strdup(res);
66 }
67
68 char *
69 vc_getVserverName(char const *id, vcCfgStyle style)
70 {
71   size_t                l1  = strlen(id);
72
73   if (style==vcCFG_NONE || style==vcCFG_AUTO)
74     style = vc_getVserverCfgStyle(id);
75
76   switch (style) {
77     case vcCFG_NONE             :  return 0;
78     case vcCFG_LEGACY           :  return strdup(id);
79     case vcCFG_RECENT_SHORT     :
80     {
81       char              buf[sizeof(CONFDIR "/") + l1 + sizeof("/name") - 1];
82
83       strcpy(buf,                         CONFDIR "/");
84       strcpy(buf+sizeof(CONFDIR "/") - 1, id);
85       
86       return getRecentName(buf, buf+sizeof(CONFDIR "/")+l1 - 1);
87     }
88     case vcCFG_RECENT_FULL      :
89     {
90       char              buf[l1 + sizeof("/name")];
91       strcpy(buf, id);
92
93       return getRecentName(buf, buf+l1);
94     }
95     default                     :  return 0;
96   }
97 }