--- sftp-server.c	Fri Apr 13 08:28:42 2001
+++ sftp-server.c.chroot	Wed May 23 18:16:07 2001
@@ -33,6 +33,8 @@
 #include "sftp.h"
 #include "sftp-common.h"
 
+#define CHROOT
+
 /* helper */
 #define get_int64()			buffer_get_int64(&iqueue);
 #define get_int()			buffer_get_int(&iqueue);
@@ -1024,6 +1026,36 @@
 	}
 }
 
+#ifdef CHROOT
+void
+chroot_init(void)
+{
+	char *user_dir, *new_root;
+	
+	user_dir = getenv("HOME");
+	if (!user_dir)
+		fatal("HOME isn't in environment");
+
+	new_root = user_dir + 1;
+	
+	while ((new_root = strchr(new_root, '.')) != NULL) {
+		new_root--;
+		if (strncmp(new_root, "/./", 3) == 0) {
+			*new_root = '\0';
+			new_root += 2;
+			
+			if (chroot(user_dir) != 0)
+				fatal("Couldn't chroot to user directory %s: %s",
+                      user_dir, strerror(errno));
+
+			setenv("HOME", new_root, 1);
+			break;
+		}
+		new_root += 2;
+	}
+}
+#endif /* CHROOT */
+
 int
 main(int ac, char **av)
 {
@@ -1039,6 +1071,12 @@
 #ifdef DEBUG_SFTP_SERVER
 	log_init("sftp-server", SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 0);
 #endif
+
+#ifdef CHROOT
+	chroot_init();
+#endif
+    if (setuid(getuid()) != 0)
+        fatal("Couldn't drop privileges: %s", strerror(errno));
 
 	in = dup(STDIN_FILENO);
 	out = dup(STDOUT_FILENO);
