#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;

	uid=getuid();

	/* 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);
		}
	}
	execl(SHELL, SHELL_SHORT, NULL);
	return(4);
}
