54181e9834bc77d6e4dfd192fa6ac1b9952f4536
[nestedvm.git] / src / org / ibex / nestedvm / support_aux.c
1 #include <string.h>
2 #include <sys/stat.h>
3 #include <sys/dirent.h>
4 #include <sys/types.h>
5 #include <utime.h>
6 #include <errno.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <signal.h>
12 #include <sys/sysctl.h>
13 #include <sys/utsname.h>
14 #include <paths.h>
15 #include <ctype.h>
16 #include <pwd.h>
17 #include <grp.h>
18 #include <stdarg.h>
19
20 #include <nestedvm/socket.h>
21
22 int _syscall_set_errno(struct _reent *ptr, int err) {
23     ptr->_errno = -err;
24     return -1;
25 }
26
27 #define REENT_WRAPPER0R(f,rt) \
28     extern rt _##f##_r(struct _reent *ptr); \
29     rt f() { return _##f##_r(_REENT); }
30 #define REENT_WRAPPER0(f) REENT_WRAPPER0R(f,int)
31
32 #define REENT_WRAPPER1R(f,rt,t1) \
33     extern rt _##f##_r(struct _reent *ptr, t1 a); \
34     rt f(t1 a) { return _##f##_r(_REENT,a); }
35 #define REENT_WRAPPER1(f,t1) REENT_WRAPPER1R(f,int,t1)
36
37 #define REENT_WRAPPER2R(f,rt,t1,t2) \
38     extern rt _##f##_r(struct _reent *ptr, t1 a, t2 b); \
39     rt f(t1 a, t2 b) { return _##f##_r(_REENT,a,b); }
40 #define REENT_WRAPPER2(f,t1,t2) REENT_WRAPPER2R(f,int,t1,t2)
41
42 #define REENT_WRAPPER3R(f,rt,t1,t2,t3) \
43     extern rt _##f##_r(struct _reent *ptr, t1 a, t2 b, t3 c); \
44     rt f(t1 a, t2 b, t3 c) { return _##f##_r(_REENT,a,b,c); }
45 #define REENT_WRAPPER3(f,t1,t2,t3) REENT_WRAPPER3R(f,int,t1,t2,t3)
46
47 #define REENT_WRAPPER4R(f,rt,t1,t2,t3,t4) \
48 extern rt _##f##_r(struct _reent *ptr, t1 a, t2 b, t3 c, t4 d); \
49 rt f(t1 a, t2 b, t3 c, t4 d) { return _##f##_r(_REENT,a,b,c,d); }
50 #define REENT_WRAPPER4(f,t1,t2,t3,t4) REENT_WRAPPER4R(f,int,t1,t2,t3,t4)
51
52 #define REENT_WRAPPER5R(f,rt,t1,t2,t3,t4,t5) \
53 extern rt _##f##_r(struct _reent *ptr, t1 a, t2 b, t3 c, t4 d, t5 e); \
54 rt f(t1 a, t2 b, t3 c, t4 d, t5 e) { return _##f##_r(_REENT,a,b,c,d,e); }
55 #define REENT_WRAPPER5(f,t1,t2,t3,t4,t5) REENT_WRAPPER5R(f,int,t1,t2,t3,t4,t5)
56
57 #define REENT_WRAPPER6R(f,rt,t1,t2,t3,t4,t5,t6) \
58 extern rt _##f##_r(struct _reent *ptr, t1 a, t2 b, t3 c, t4 d, t5 e, t6 f); \
59 rt f(t1 a, t2 b, t3 c, t4 d, t5 e, t6 f) { return _##f##_r(_REENT,a,b,c,d,e,f); }
60 #define REENT_WRAPPER6(f,t1,t2,t3,t4,t5,t6) REENT_WRAPPER6R(f,int,t1,t2,t3,t4,t5,t6)
61
62 REENT_WRAPPER2(mkdir,const char *,mode_t)
63 REENT_WRAPPER2(access,const char *,int)
64 REENT_WRAPPER1(rmdir,const char *)
65 REENT_WRAPPER1R(sysconf,long,int)
66 REENT_WRAPPER1(chdir,const char*)
67 REENT_WRAPPER2(utime,const char *,const struct utimbuf *)
68 REENT_WRAPPER1(pipe,int *)
69 REENT_WRAPPER2(dup2,int,int)
70 REENT_WRAPPER3(waitpid,pid_t,int *,int)
71 REENT_WRAPPER2R(getcwd,char *,char *,size_t)
72 REENT_WRAPPER2R(_getcwd,char *,char *,size_t)
73 REENT_WRAPPER2(symlink,const char *,const char *)
74 REENT_WRAPPER3(readlink,const char *, char *,int)
75 REENT_WRAPPER3(chown,const char *,uid_t,gid_t)
76 REENT_WRAPPER3(fchown,int,uid_t,gid_t)
77 REENT_WRAPPER3(lchown,const char *,uid_t,gid_t)
78 REENT_WRAPPER2(chmod,const char *,mode_t)
79 REENT_WRAPPER2(fchmod,int,mode_t)
80 REENT_WRAPPER2(lstat,const char *,struct stat *)
81 REENT_WRAPPER4(getdents,int, char *, size_t,long *)
82 REENT_WRAPPER1(dup,int)
83 REENT_WRAPPER2R(pathconf,long,const char *,int)
84 REENT_WRAPPER0(vfork)
85 REENT_WRAPPER1(chroot,const char *)
86 REENT_WRAPPER3(mknod,const char *,mode_t,dev_t)
87 REENT_WRAPPER2(ftruncate,int,off_t)
88 REENT_WRAPPER1(usleep,unsigned int)
89 REENT_WRAPPER2(mkfifo,const char *, mode_t)
90 REENT_WRAPPER3(klogctl,int,char*,int)
91 REENT_WRAPPER2R(realpath,char *,const char *,char *)
92 REENT_WRAPPER6(_sysctl,int *,int, void *, size_t*, void *, size_t)
93 REENT_WRAPPER6(sysctl,int *, int, void *, size_t*, void *, size_t)
94 REENT_WRAPPER2(getpriority,int,int)
95 REENT_WRAPPER3(setpriority,int,int,int)
96 REENT_WRAPPER3(connect,int,const struct sockaddr *,socklen_t)
97 REENT_WRAPPER3(socket,int,int,int)
98 REENT_WRAPPER3(_resolve_hostname,const char *,char*,size_t*)
99 REENT_WRAPPER3(_resolve_ip,int,char*,size_t)
100 REENT_WRAPPER3(accept,int,struct sockaddr *,socklen_t*)
101 REENT_WRAPPER5(getsockopt,int,int,int,void*,socklen_t*)
102 REENT_WRAPPER5(setsockopt,int,int,int,const void*,socklen_t)
103 REENT_WRAPPER3(bind,int,const struct sockaddr *,socklen_t)
104 REENT_WRAPPER2(listen,int,int)
105 REENT_WRAPPER2(shutdown,int,int)
106 REENT_WRAPPER6(sendto,int,const void*,size_t,int,const struct sockaddr*,socklen_t)
107 REENT_WRAPPER6(recvfrom,int,void*,size_t,int,struct sockaddr*,socklen_t*)
108 REENT_WRAPPER5(select,int,fd_set*,fd_set*,fd_set*,struct timeval*)
109 REENT_WRAPPER4(send,int,const void*,size_t,int)
110 REENT_WRAPPER4(recv,int,void*,size_t,int)
111 REENT_WRAPPER2(getgroups,int,gid_t*)
112 REENT_WRAPPER3(getsockname,int,struct sockaddr*,int*)
113 REENT_WRAPPER3(getpeername,int,struct sockaddr*,int*)
114 REENT_WRAPPER1(setuid,uid_t)
115 REENT_WRAPPER1(seteuid,uid_t)
116 REENT_WRAPPER1(setgid,gid_t)
117 REENT_WRAPPER1(setegid,gid_t)
118 REENT_WRAPPER2(setgroups,int,const gid_t *)
119 REENT_WRAPPER0R(setsid,pid_t)
120 REENT_WRAPPER1(fsync,int)
121
122 extern int __execve_r(struct _reent *ptr, const char *path, char *const argv[], char *const envp[]);
123 int _execve(const char *path, char *const argv[], char *const envp[]) {
124     return __execve_r(_REENT,path,argv,envp);
125 }
126
127 char *_getcwd_r(struct _reent *ptr, char *buf, size_t size) {
128     if(buf != NULL) {
129         buf = __getcwd_r(ptr,buf,size);
130         return (long)buf == -1 ? NULL : buf;
131     }
132     
133     size = 256;
134     for(;;) {
135         buf = malloc(size);
136         char *ret = __getcwd_r(ptr,buf,size);
137         if((long)ret != -1) return ret;
138         free(buf);
139         size *= 2;
140         if(ptr->_errno != ERANGE) return NULL;
141     }
142 }
143
144 pid_t _wait_r(struct _reent *ptr, int *status) {
145     return _waitpid_r(ptr,-1,status,0);
146 }
147
148 long _pathconf_r(struct _reent *ptr,const char *path, int name) {
149     switch(name) {
150         default:
151             fprintf(stderr,"WARNING: pathconf: Unknown \"name\": %d\n",name);
152             ptr->_errno = EINVAL;
153             return -1;
154     }
155 }
156
157 int _sysctl_r(struct _reent *ptr, int *name, int namelen, void *oldp, size_t *oldlen, void *newp, size_t newlen) {
158     if(name[0] != CTL_USER) return _sysctl(name,namelen,oldp,oldlen,newp,newlen);
159     if(newp != NULL) { ptr->_errno = EPERM; return -1; }
160     if(namelen != 2) { ptr->_errno = EINVAL; return -1; }
161     
162     switch(name[1]) {
163         default:
164             fprintf(stderr,"WARNING: sysctl: Unknown name: %d\n",name[1]);
165             ptr->_errno = EINVAL;
166             return -1;
167     }
168 }
169
170 void sync() {
171     /* do nothing*/
172 }
173
174 char *ttyname(int fd) {
175     return isatty(fd) ? "/dev/console" : NULL;
176 }
177
178 int sigaction(int sig, const struct sigaction *act, struct sigaction *oact) {
179     _sig_func_ptr old;
180     _sig_func_ptr new;
181     if(act) {
182         if(act->sa_flags || act->sa_mask != ~((sigset_t)0)) { errno = EINVAL; return -1; }
183         old = signal(sig,act->sa_handler);
184     } else if(oact) {
185         old = signal(sig,SIG_DFL);
186         signal(sig,old);
187     }
188     if(oact) {
189         oact->sa_handler = old;
190         oact->sa_mask = 0;
191         oact->sa_mask = ~((sigset_t)0);
192     }
193     return 0;
194 }
195
196 DIR *opendir(const char *path) {
197     struct stat sb;
198     int fd;
199     DIR *dir;
200     
201     fd = open(path,O_RDONLY);
202     if(fd < 0) return NULL;
203     
204     if(fstat(fd,&sb) < 0 || !S_ISDIR(sb.st_mode)) {
205         close(fd);
206         errno = ENOTDIR;
207         return NULL;
208     }
209     
210     dir = malloc(sizeof(*dir));
211     if(dir == NULL) {
212         close(fd);
213         errno = ENOMEM;
214         return NULL;
215     }
216     dir->dd_fd = fd;
217     dir->dd_buf = malloc(sizeof(struct dirent));
218     dir->dd_size = sizeof(struct dirent);
219     if(dir->dd_buf == NULL) {
220         close(fd);
221         free(dir);
222         return NULL;
223     }
224     dir->dd_loc = 0;
225     dir->dd_len = 0;
226     return dir;
227 }
228
229 struct dirent *readdir(DIR *dir) {
230     struct dirent *dp;
231     errno = 0;
232     if(dir->dd_loc == 0 || dir->dd_loc == dir->dd_len) {
233         dir->dd_len = getdents(dir->dd_fd,dir->dd_buf,dir->dd_size,NULL);
234         dir->dd_loc = 0;
235         if(dir->dd_len <= 0) { dir->dd_len = 0; return NULL; }
236     }
237     dp = (struct dirent*) (dir->dd_buf + dir->dd_loc);
238     if(dp->d_reclen == 0 || dp->d_reclen > dir->dd_len - dir->dd_loc) return NULL;
239     dir->dd_loc += dp->d_reclen;
240     return dp;
241 }
242
243 int closedir(DIR *dir) {
244     int fd = dir->dd_fd;
245     free(dir->dd_buf);
246     free(dir);
247     return close(fd);
248 }
249
250 /*
251  * Networking/Socket stuff
252  */
253
254 /* This should really be part of the newlib _reent structure */
255 int h_errno;
256
257 char *inet_ntoa(struct in_addr in) {
258     static char buf[18];
259     const unsigned char *p = (void*) &in;
260     snprintf(buf,sizeof(buf),"%u.%u.%u.%u",p[0],p[1],p[2],p[3]);
261     return buf;
262 }
263
264 struct servent *getservbyname(const char *name,const char *proto) {
265     return NULL;
266 }
267
268 static const char *h_errlist[] = { "No Error","Unknown host", "Host name lookup failure","Unknown server error","No address associated with name" };
269
270 const char *hstrerror(int err) {
271     if(err < 0 || err > 4) return "Unknown Error";
272     return h_errlist[err];
273 }
274
275 void herror(const char *string) {
276     fprintf(stderr,"%s: %s\n",string,hstrerror(h_errno));
277 }
278
279 extern int _resolve_ip(int addr, char *buf, size_t size);
280
281 struct hostent *gethostbyaddr(const char *addr, int len, int type) {
282     static struct hostent hostent;
283     static char name[128];
284     static char *aliases[1];
285     static char *addr_list[1];
286     static char addr_list_buf[4];
287     int err,i;
288     
289     if(type != AF_INET || len != 4) return NULL;
290     memcpy(&i,addr,4);
291     memcpy(addr_list_buf,addr,4);
292     err = _resolve_ip(i,name,sizeof(name));
293     if(err != 0) { h_errno = err; return NULL; }
294     
295     hostent.h_name = name;
296     hostent.h_aliases = aliases;
297     aliases[0] = NULL;
298     hostent.h_addrtype = AF_INET;
299     hostent.h_length = sizeof(struct in_addr);
300     hostent.h_addr_list = addr_list;
301     addr_list[0] = addr_list_buf;
302     
303     return &hostent;
304 }
305
306 extern int _resolve_hostname(const char *, char *buf, size_t *size);
307
308 struct hostent *gethostbyname(const char *hostname) {
309 #define MAX_ADDRS 256
310     static struct hostent hostent;
311     static char saved_hostname[128];
312     static char *addr_list[MAX_ADDRS+1];
313     static char addr_list_buf[MAX_ADDRS*sizeof(struct in_addr)];
314     static char *aliases[1];
315     
316     unsigned char buf[MAX_ADDRS*sizeof(struct in_addr)];
317     size_t size = sizeof(buf);
318     int err,i,n=0;
319     
320     err = _resolve_hostname(hostname,buf,&size);
321     if(err != 0) { h_errno = err; return NULL; }
322     
323     memcpy(addr_list_buf,buf,size);
324     for(i=0;i<size;i += sizeof(struct in_addr)) addr_list[n++] = &addr_list_buf[i];
325     addr_list[n] = NULL;
326     strncpy(saved_hostname,hostname,sizeof(saved_hostname));
327     aliases[0] = NULL;
328     
329     hostent.h_name = saved_hostname;
330     hostent.h_aliases = aliases;
331     hostent.h_addrtype = AF_INET;
332     hostent.h_length = sizeof(struct in_addr);
333     hostent.h_addr_list = addr_list;
334     
335     return &hostent;
336 }
337
338 static struct passwd pw_passwd;
339 static struct group gr_group;
340 static FILE *passwd_fp;
341 static FILE *group_fp;
342 static char pw_name[1024];
343 static char pw_password[1024];
344 static char pw_gecos[1024];
345 static char pw_dir[1024];
346 static char pw_shell[1024];
347 static char gr_name[1024];
348 static char gr_passwd[1024];
349 static char *gr_mem[1];
350
351 static int gr_parse_body(const char *buf) {
352     if(sscanf(buf,"%[^:]:%[^:]:%hu",gr_name,gr_passwd,&gr_group.gr_gid) < 3) return -1;
353     gr_group.gr_name = gr_name;
354     gr_group.gr_passwd = gr_passwd;
355     gr_group.gr_mem = gr_mem;
356     gr_mem[0] = NULL;
357     return 0;
358 }
359
360 static int pw_parse_body(const char *buf) {
361     int pos;
362     if(sscanf(buf,"%[^:]:%[^:]:%d:%d:%[^:]:%[^:]:%s\n",pw_name,pw_password,&pw_passwd.pw_uid,&pw_passwd.pw_gid,pw_gecos,pw_dir,pw_shell) < 7) return -1;
363     pw_passwd.pw_name = pw_name;
364     pw_passwd.pw_passwd = pw_password;
365     pw_passwd.pw_gecos = pw_gecos;
366     pw_passwd.pw_dir = pw_dir;
367     pw_passwd.pw_shell = pw_shell;
368     pw_passwd.pw_comment = "";
369     return 0;
370 }
371
372 struct group *getgrnam(const char *name) {
373     FILE *fp;
374     char buf[1024];
375     
376     if((fp=fopen("/etc/group","r"))==NULL) return NULL;
377     while(fgets(buf,sizeof(buf),fp)) {
378         if(buf[0] == '#') continue;
379         if(gr_parse_body(buf) < 0) {
380             fclose(fp);
381             return NULL;
382         }
383         if(strcmp(name,gr_name)==0) {
384             fclose(fp);
385             return &gr_group;
386         }
387     }
388     fclose(fp);
389     return NULL;
390 }
391
392 struct group *getgrgid(gid_t gid) {
393     FILE *fp;
394     char buf[1024];
395     
396     if((fp=fopen("/etc/group","r"))==NULL) return NULL;
397     while(fgets(buf,sizeof(buf),fp)) {
398         if(buf[0] == '#') continue;
399         if(gr_parse_body(buf) < 0) {
400             fclose(fp);
401             return NULL;
402         }
403         if(gid == gr_group.gr_gid) {
404             fclose(fp);
405             return &gr_group;
406         }
407     }
408     fclose(fp);
409     return NULL;
410 }
411     
412 struct group *getgrent() {
413     char buf[1024];
414     if(group_fp == NULL) return NULL;
415     if(fgets(buf,sizeof(buf),group_fp) == NULL) return NULL;
416     if(buf[0] == '#') return getgrent();
417     if(gr_parse_body(buf) < 0) return NULL;
418     return &gr_group;
419 }
420
421 void setgrent() { 
422     if(group_fp != NULL) fclose(group_fp);
423     group_fp = fopen("/etc/group","r");
424 }
425
426 void endgrent() {
427     if(group_fp != NULL) fclose(group_fp);
428     group_fp = NULL;
429 }
430
431 struct passwd *getpwnam(const char *name) {
432     FILE *fp;
433     char buf[1024];
434     
435     if((fp=fopen("/etc/passwd","r"))==NULL) return NULL;
436     while(fgets(buf,sizeof(buf),fp)) {
437         if(buf[0] == '#') continue;
438         if(pw_parse_body(buf) < 0) {
439             fclose(fp);
440             return NULL;
441         }
442         if(strcmp(name,pw_name)==0) {
443             fclose(fp);
444             return &pw_passwd;
445         }
446     }
447     fclose(fp);
448     return NULL;
449 }
450
451 struct passwd *getpwuid(uid_t uid) {
452     FILE *fp;
453     char buf[1024];
454     
455     if((fp=fopen("/etc/passwd","r"))==NULL) return NULL;
456     while(fgets(buf,sizeof(buf),fp)) {
457         if(buf[0] == '#') continue;
458         if(pw_parse_body(buf) < 0) {
459             fclose(fp);
460             return NULL;
461         }
462         if(uid == pw_passwd.pw_uid) {
463             fclose(fp);
464             return &pw_passwd;
465         }
466     }
467     fclose(fp);
468     return NULL;
469 }
470
471 struct passwd *getpwent() {
472     char buf[1024];
473     if(passwd_fp == NULL) return NULL;
474     if(fgets(buf,sizeof(buf),passwd_fp) == NULL) return NULL;
475     if(buf[0] == '#') return getpwent();
476     if(pw_parse_body(buf) < 0) return NULL;
477     return &pw_passwd;
478 }
479
480 void setpwent() { 
481     if(passwd_fp != NULL) fclose(passwd_fp);
482     passwd_fp = fopen("/etc/group","r");
483 }
484
485 void endpwent() {
486     if(passwd_fp != NULL) fclose(passwd_fp);
487     passwd_fp = NULL;
488 }
489
490 char *getpass(const char *prompt) {
491     static char buf[1024];
492     int len = 0;
493     fputs(prompt,stderr);
494     fflush(stdout);
495     if(fgets(buf,sizeof(buf),stdin)!=NULL) {
496         len = strlen(buf);
497         if(buf[len-1] == '\n') len--;
498     }
499     fputc('\n',stderr);
500     buf[len] = '\0';
501     return buf;
502 }
503
504 /* Argh... newlib's asprintf is totally broken... */
505 int vasprintf(char **ret, const char *fmt, va_list ap) {
506     int n;
507     char *p;
508     *ret = malloc(128); /* just guess for now */
509     if(!*ret) return -1;
510     n = vsnprintf(*ret,128,fmt,ap);
511     if(n < 128) {
512         return n;
513     } else {
514         p = realloc(*ret,n+1);
515         if(!p) { free(*ret); return -1; }
516         return vsprintf(*ret = p,fmt,ap);
517     }
518 }
519
520 // FIXME: This needs to be in a header
521 char *getlogin() {
522     return getenv("USER");
523 }
524
525
526 /*
527  * Other People's Code 
528  */
529
530 /* FreeBSD's dirname/basename */
531
532 /* FIXME: Put these in a header */
533
534 /*
535  * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
536  * All rights reserved.
537  *
538  * Redistribution and use in source and binary forms, with or without
539  * modification, are permitted provided that the following conditions
540  * are met:
541  * 1. Redistributions of source code must retain the above copyright
542  *    notice, this list of conditions and the following disclaimer.
543  * 2. Redistributions in binary form must reproduce the above copyright
544  *    notice, this list of conditions and the following disclaimer in the
545  *    documentation and/or other materials provided with the distribution.
546  * 3. The name of the author may not be used to endorse or promote products
547  *    derived from this software without specific prior written permission.
548  *
549  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
550  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
551  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
552  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
553  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
554  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
555  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
556  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
557  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
558  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
559  */
560
561 char *
562 dirname(path)
563 const char *path;
564 {
565     static char bname[MAXPATHLEN];
566     register const char *endp;
567     
568     /* Empty or NULL string gets treated as "." */
569     if (path == NULL || *path == '\0') {
570         (void)strcpy(bname, ".");
571         return(bname);
572     }
573     
574     /* Strip trailing slashes */
575     endp = path + strlen(path) - 1;
576     while (endp > path && *endp == '/')
577         endp--;
578     
579     /* Find the start of the dir */
580     while (endp > path && *endp != '/')
581         endp--;
582     
583     /* Either the dir is "/" or there are no slashes */
584     if (endp == path) {
585         (void)strcpy(bname, *endp == '/' ? "/" : ".");
586         return(bname);
587     } else {
588         do {
589             endp--;
590         } while (endp > path && *endp == '/');
591     }
592     
593     if (endp - path + 2 > sizeof(bname)) {
594         errno = ENAMETOOLONG;
595         return(NULL);
596     }
597     (void)strncpy(bname, path, endp - path + 1);
598     bname[endp - path + 1] = '\0';
599     return(bname);
600 }
601
602 char *
603 basename(path)
604 const char *path;
605 {
606     static char bname[MAXPATHLEN];
607     register const char *endp, *startp;
608     
609     /* Empty or NULL string gets treated as "." */
610     if (path == NULL || *path == '\0') {
611         (void)strcpy(bname, ".");
612         return(bname);
613     }
614     
615     /* Strip trailing slashes */
616     endp = path + strlen(path) - 1;
617     while (endp > path && *endp == '/')
618         endp--;
619     
620     /* All slashes becomes "/" */
621     if (endp == path && *endp == '/') {
622         (void)strcpy(bname, "/");
623         return(bname);
624     }
625     
626     /* Find the start of the base */
627     startp = endp;
628     while (startp > path && *(startp - 1) != '/')
629         startp--;
630     
631     if (endp - startp + 2 > sizeof(bname)) {
632         errno = ENAMETOOLONG;
633         return(NULL);
634     }
635     (void)strncpy(bname, startp, endp - startp + 1);
636     bname[endp - startp + 1] = '\0';
637     return(bname);
638 }
639
640 /* FreeBSD's uname */
641 int
642 uname(name)
643 struct utsname *name;
644 {
645         int mib[2], rval;
646         size_t len;
647         char *p;
648         int oerrno;
649     
650         rval = 0;
651     
652         mib[0] = CTL_KERN;
653         mib[1] = KERN_OSTYPE;
654         len = sizeof(name->sysname);
655         oerrno = errno;
656         if (sysctl(mib, 2, &name->sysname, &len, NULL, 0) == -1) {
657                 if(errno == ENOMEM)
658                         errno = oerrno;
659                 else
660                         rval = -1;
661         }
662         name->sysname[sizeof(name->sysname) - 1] = '\0';
663     
664         mib[0] = CTL_KERN;
665         mib[1] = KERN_HOSTNAME;
666         len = sizeof(name->nodename);
667         oerrno = errno;
668         if (sysctl(mib, 2, &name->nodename, &len, NULL, 0) == -1) {
669                 if(errno == ENOMEM)
670                         errno = oerrno;
671                 else
672                         rval = -1;
673         }
674         name->nodename[sizeof(name->nodename) - 1] = '\0';
675     
676         mib[0] = CTL_KERN;
677         mib[1] = KERN_OSRELEASE;
678         len = sizeof(name->release);
679         oerrno = errno;
680         if (sysctl(mib, 2, &name->release, &len, NULL, 0) == -1) {
681                 if(errno == ENOMEM)
682                         errno = oerrno;
683                 else
684                         rval = -1;
685         }
686         name->release[sizeof(name->release) - 1] = '\0';
687     
688         /* The version may have newlines in it, turn them into spaces. */
689         mib[0] = CTL_KERN;
690         mib[1] = KERN_VERSION;
691         len = sizeof(name->version);
692         oerrno = errno;
693         if (sysctl(mib, 2, &name->version, &len, NULL, 0) == -1) {
694                 if (errno == ENOMEM)
695                         errno = oerrno;
696                 else
697                         rval = -1;
698         }
699         name->version[sizeof(name->version) - 1] = '\0';
700         for (p = name->version; len--; ++p) {
701                 if (*p == '\n' || *p == '\t') {
702                         if (len > 1)
703                                 *p = ' ';
704                         else
705                                 *p = '\0';
706                 }
707         }
708     
709         mib[0] = CTL_HW;
710         mib[1] = HW_MACHINE;
711         len = sizeof(name->machine);
712         oerrno = errno;
713         if (sysctl(mib, 2, &name->machine, &len, NULL, 0) == -1) {
714                 if (errno == ENOMEM)
715                         errno = oerrno;
716                 else
717                         rval = -1;
718         }
719         name->machine[sizeof(name->machine) - 1] = '\0';
720         return (rval);
721 }
722
723 /* FreeBSD's gethostname */
724 int
725 gethostname(name, namelen)
726 char *name;
727 int namelen;
728 {
729     int mib[2];
730     size_t size;
731     
732     mib[0] = CTL_KERN;
733     mib[1] = KERN_HOSTNAME;
734     size = namelen;
735     if (sysctl(mib, 2, name, &size, NULL, 0) == -1)
736         return (-1);
737     return (0);
738 }
739
740 /* FreeBSD's daemon() - modified for nestedvm */
741 int
742 daemon(nochdir, noclose)
743 int nochdir, noclose;
744 {
745         int fd;
746     
747         switch (fork()) {
748         case -1:
749             return (-1);
750         case 0:
751             break;
752         default:
753             _exit(0);
754         }
755     
756         if (setsid() == -1)
757                 return (-1);
758     
759         if (!nochdir)
760                 (void)chdir("/");
761     
762         if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
763                 (void)dup2(fd, STDIN_FILENO);
764                 (void)dup2(fd, STDOUT_FILENO);
765                 (void)dup2(fd, STDERR_FILENO);
766                 if (fd > 2)
767                         (void)close(fd);
768         }
769         return (0);
770 }
771
772 /* FreeBSD's inet_addr/inet_aton */
773
774 /* 
775 * Check whether "cp" is a valid ASCII representation
776  * of an Internet address and convert to a binary address.
777  * Returns 1 if the address is valid, 0 if not.
778  * This replaces inet_addr, the return value from which
779  * cannot distinguish between failure and a local broadcast address.
780  */
781 int
782 inet_aton(cp, addr)
783 register const char *cp;
784 struct in_addr *addr;
785 {
786         u_long parts[4];
787         in_addr_t val;
788         char *c;
789         char *endptr;
790         int gotend, n;
791     
792         c = (char *)cp;
793         n = 0;
794         /*
795          * Run through the string, grabbing numbers until
796          * the end of the string, or some error
797          */
798         gotend = 0;
799         while (!gotend) {
800                 errno = 0;
801                 val = strtoul(c, &endptr, 0);
802         
803                 if (errno == ERANGE)    /* Fail completely if it overflowed. */
804                         return (0);
805                 
806                 /* 
807             * If the whole string is invalid, endptr will equal
808                  * c.. this way we can make sure someone hasn't
809                  * gone '.12' or something which would get past
810                  * the next check.
811                  */
812                 if (endptr == c)
813                         return (0);
814                 parts[n] = val;
815                 c = endptr;
816         
817                 /* Check the next character past the previous number's end */
818                 switch (*c) {
819             case '.' :
820                 /* Make sure we only do 3 dots .. */
821                 if (n == 3)     /* Whoops. Quit. */
822                     return (0);
823                 n++;
824                 c++;
825                 break;
826                 
827             case '\0':
828                 gotend = 1;
829                 break;
830                 
831             default:
832                 if (isspace((unsigned char)*c)) {
833                     gotend = 1;
834                     break;
835                 } else
836                     return (0); /* Invalid character, so fail */
837                 }
838         
839         }
840     
841         /*
842          * Concoct the address according to
843          * the number of parts specified.
844          */
845     
846         switch (n) {
847         case 0:                         /* a -- 32 bits */
848             /*
849              * Nothing is necessary here.  Overflow checking was
850              * already done in strtoul().
851              */
852             break;
853         case 1:                         /* a.b -- 8.24 bits */
854             if (val > 0xffffff || parts[0] > 0xff)
855                 return (0);
856             val |= parts[0] << 24;
857             break;
858             
859         case 2:                         /* a.b.c -- 8.8.16 bits */
860             if (val > 0xffff || parts[0] > 0xff || parts[1] > 0xff)
861                 return (0);
862             val |= (parts[0] << 24) | (parts[1] << 16);
863                 break;
864                 
865             case 3:                             /* a.b.c.d -- 8.8.8.8 bits */
866                 if (val > 0xff || parts[0] > 0xff || parts[1] > 0xff ||
867                     parts[2] > 0xff)
868                     return (0);
869                 val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
870                     break;
871         }
872     
873         if (addr != NULL)
874                 addr->s_addr = htonl(val);
875         return (1);
876 }
877
878 /*
879  * ASCII internet address interpretation routine.
880  * The value returned is in network order.
881  */
882 in_addr_t               /* XXX should be struct in_addr :( */
883 inet_addr(cp)
884 register const char *cp;
885 {
886         struct in_addr val;
887     
888         if (inet_aton(cp, &val))
889                 return (val.s_addr);
890         return (INADDR_NONE);
891 }
892
893 int
894 getgrouplist(uname, agroup, groups, grpcnt)
895 const char *uname;
896 gid_t agroup;
897 register gid_t *groups;
898 int *grpcnt;
899 {
900         register struct group *grp;
901         register int i, ngroups;
902         int ret, maxgroups;
903     
904         ret = 0;
905         ngroups = 0;
906         maxgroups = *grpcnt;
907         /*
908          * When installing primary group, duplicate it;
909          * the first element of groups is the effective gid
910          * and will be overwritten when a setgid file is executed.
911          */
912         groups[ngroups++] = agroup;
913         if (maxgroups > 1)
914                 groups[ngroups++] = agroup;
915         /*
916          * Scan the group file to find additional groups.
917          */
918         setgrent();
919         while ((grp = getgrent())) {
920                 for (i = 0; i < ngroups; i++) {
921                         if (grp->gr_gid == groups[i])
922                                 goto skip;
923                 }
924                 for (i = 0; grp->gr_mem[i]; i++) {
925                         if (!strcmp(grp->gr_mem[i], uname)) {
926                                 if (ngroups >= maxgroups) {
927                                         ret = -1;
928                                         break;
929                                 }
930                                 groups[ngroups++] = grp->gr_gid;
931                                 break;
932                         }
933                 }
934 skip: ;
935         }
936         endgrent();
937         *grpcnt = ngroups;
938         return (ret);
939 }
940
941 int
942 initgroups(uname, agroup)
943 const char *uname;
944 gid_t agroup;
945 {
946     gid_t groups[32], ngroups;
947     
948     ngroups = 32;
949     getgrouplist(uname, agroup, groups, &ngroups);
950     return (setgroups(ngroups, groups));
951 }