#
#define ENOENT		2
#define E2BIG		7
#define ENOMEM		12
#define EACCES		13
#define ENOTDIR		20

/* chroot rootdir cmd args */
char	*args[100];
char	string[10000];
main(argc,argv)
int	argc;
char	*argv[];
{
        int i;

        register char **argp, *strp, *p;



        if(argc < 3) {

                printf("useage:  chroot rootdir cmd arg arg ...\n");

                exit(1);

        }

        argc--;

        argv++;

        if (chroot(argv[0]) == -1) {

                perror(argv[0]);

                exit(1);

        }

        if (chdir("/") == -1) {

                printf("Can't chdir to new root\n");

                exit(1);

        }

        argc--;

        argv++;

        argp = args;

        strp = string;

        for(i=0; i<argc; i++) {

                *argp++ = strp;

                p = *argv++;

                while(*strp++ = *p++);

        }

        *argp = 0;

        switch(i = exprog(args))  {

                case ENOENT:

                case ENOTDIR:

                        printf("%s: not found\n", args[0]);

                        break;

                case E2BIG:

                        printf("Arg list too long\n");

                        break;

                case ENOMEM:

                        printf("Not enough core\n");

                        break;

                case EACCES:

                        printf("Permission denied\n");

                        break;

                case -1:

                        printf("No Shell!\n");

                        break;

                default:

                        printf("Unknown error.  errno: %d\n", i);

			break;
	}
}
#define ENOEXEC	8

exprog(as)
char	*as[];
{
	char	cmd[101];
	register i,j;
	extern errno;
	char	*sargs[101];

	j = 0;
	for(i=0;i<10;i++)
		cmd[i] = "/usr//bin/"[i];
	while(i<100 && as[0][j])
		cmd[i++] = as[0][j++];
	cmd[i++] = 0;
	for(j=10;j>=0; j =- 5){
		execv(&cmd[j],as);
		if(errno == ENOEXEC)
			goto runcom;
		if(errno != ENOENT)
			return(errno);
	}
	return(errno);
runcom:
	sargs[1] = &cmd[j];
	sargs[0] = "sh";
	i = 1;
	while(as[i] != 0) {
		if(i>99)
			return(E2BIG);
		sargs[i+1] = as[i];
		i++;
	}
	sargs[i+1] = 0;
	execv("/bin/sh",sargs);
	return(-1);
}
