#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>

int main(void) {
	struct passwd *pwinfo=NULL;
	char *home=NULL, *home_tmp=NULL;
	uid_t uid;
	gid_t gid;

	uid=getuid();
	gid=getgid();

	/* Don't chroot for uid==0 */
	if (uid!=0) {
		pwinfo=getpwuid(uid);
		if (pwinfo==NULL) return(1);
		home_tmp=getenv("HOME");
		if (home_tmp) home=strdup(home_tmp);
		if (home!=NULL && pwinfo->pw_dir!=NULL) {
			if (strcmp(pwinfo->pw_dir, home)!=0) {
				/* Passwd entry for home dir and $HOME don't match */
				return(2);
			}
		}
		if (home==NULL && pwinfo->pw_dir!=NULL) {
			home=pwinfo->pw_dir;
		}
		if (chroot(home)!=0) {
			return(3);
		}
	}

	/* Set our GID and UID, GID first. */
	if (setgid(gid)<0) return(5);
	if (setuid(uid)<0) return(6);

	/* Execute our shell. */
	execl(SHELL, SHELL_SHORT, NULL);
	return(4);
}
