--- sftp-server.c	2006-08-05 03:39:40.000000000 +0100
+++ sftp-server.c.new	2006-10-07 20:55:56.000000000 +0100
@@ -33,6 +33,7 @@
 #include <string.h>
 #include <pwd.h>
 #include <time.h>
+#include <syslog.h>
 #include <unistd.h>
 #include <stdarg.h>
 
@@ -51,7 +52,7 @@
 #define get_string(lenp)		buffer_get_string(&iqueue, lenp);
 
 /* Our verbosity */
-LogLevel log_level = SYSLOG_LEVEL_ERROR;
+LogLevel log_level = SYSLOG_LEVEL_DEBUG3;
 
 /* Our client */
 struct passwd *pw = NULL;
@@ -74,6 +75,259 @@
 	Attrib attrib;
 };
 
+/*
+ * Initialize the log.
+ */
+static int log_on_stderr = 1;
+
+#define LOG_SYSLOG_VIS  (VIS_CSTYLE|VIS_NL|VIS_TAB|VIS_OCTAL)
+#define LOG_STDERR_VIS  (VIS_SAFE|VIS_OCTAL)
+
+#if defined(HAVE_OPENLOG_R) && defined(SYSLOG_DATA_INIT)
+static struct syslog_data sdata = SYSLOG_DATA_INIT;
+#endif
+
+void
+log_end_cr() {
+#if defined(HAVE_OPENLOG_R) && defined(SYSLOG_DATA_INIT)
+	closelog_r(&sdata);
+#else
+	closelog();
+#endif
+}
+
+void
+log_init_cr(char *av0, LogLevel level, SyslogFacility facility, int on_stderr)
+{
+        int log_facility = LOG_AUTH;
+        char *argv0;
+        extern char *__progname;
+
+        argv0 = av0;
+
+        switch (level) {
+        case SYSLOG_LEVEL_QUIET:
+        case SYSLOG_LEVEL_FATAL:
+        case SYSLOG_LEVEL_ERROR:
+        case SYSLOG_LEVEL_INFO:
+        case SYSLOG_LEVEL_VERBOSE:
+        case SYSLOG_LEVEL_DEBUG1:
+        case SYSLOG_LEVEL_DEBUG2:
+        case SYSLOG_LEVEL_DEBUG3:
+                log_level = level;
+                break;
+        default:
+                fprintf(stderr, "Unrecognized internal syslog level code %d\n",
+                    (int) level);
+                exit(1);
+        }
+
+        log_on_stderr = on_stderr;
+        if (on_stderr)
+                return;
+
+        switch (facility) {
+        case SYSLOG_FACILITY_DAEMON:
+                log_facility = LOG_DAEMON;
+                break;
+        case SYSLOG_FACILITY_USER:
+                log_facility = LOG_USER;
+                break;
+        case SYSLOG_FACILITY_AUTH:
+                log_facility = LOG_AUTH;
+                break;
+#ifdef LOG_AUTHPRIV
+        case SYSLOG_FACILITY_AUTHPRIV:
+                log_facility = LOG_AUTHPRIV;
+                break;
+#endif
+        case SYSLOG_FACILITY_LOCAL0:
+                log_facility = LOG_LOCAL0;
+                break;
+        case SYSLOG_FACILITY_LOCAL1:
+                log_facility = LOG_LOCAL1;
+                break;
+        case SYSLOG_FACILITY_LOCAL2:
+                log_facility = LOG_LOCAL2;
+                break;
+        case SYSLOG_FACILITY_LOCAL3:
+                log_facility = LOG_LOCAL3;
+                break;
+        case SYSLOG_FACILITY_LOCAL4:
+                log_facility = LOG_LOCAL4;
+                break;
+        case SYSLOG_FACILITY_LOCAL5:
+                log_facility = LOG_LOCAL5;
+                break;
+        case SYSLOG_FACILITY_LOCAL6:
+                log_facility = LOG_LOCAL6;
+                break;
+        case SYSLOG_FACILITY_LOCAL7:
+                log_facility = LOG_LOCAL7;
+                break;
+        default:
+                fprintf(stderr,
+                    "Unrecognized internal syslog facility code %d\n",
+                    (int) facility);
+                exit(1);
+        }
+
+        /*
+         * If an external library (eg libwrap) attempts to use syslog
+         * immediately after reexec, syslog may be pointing to the wrong
+         * facility, so we force an open/close of syslog here.
+         */
+#if defined(HAVE_OPENLOG_R) && defined(SYSLOG_DATA_INIT)
+        openlog_r(argv0 ? argv0 : __progname, LOG_PID | LOG_NDELAY | LOG_CONS, log_facility, &sdata);
+#else
+        openlog(argv0 ? argv0 : __progname, LOG_PID | LOG_NDELAY | LOG_CONS, log_facility);
+#endif
+}
+
+
+#define MSGBUFSIZ 1024
+
+void
+do_log_cr(LogLevel level, const char *fmt, va_list args)
+{
+        char msgbuf[MSGBUFSIZ];
+        char fmtbuf[MSGBUFSIZ];
+        char *txt = NULL;
+        int pri = LOG_INFO;
+
+        if (level > log_level)
+                return;
+
+        switch (level) {
+        case SYSLOG_LEVEL_FATAL:
+                if (!log_on_stderr)
+                        txt = "fatal";
+                pri = LOG_CRIT;
+                break;
+        case SYSLOG_LEVEL_ERROR:
+                if (!log_on_stderr)
+                        txt = "error";
+                pri = LOG_ERR;
+                break;
+        case SYSLOG_LEVEL_INFO:
+                pri = LOG_INFO;
+                break;
+        case SYSLOG_LEVEL_VERBOSE:
+                pri = LOG_INFO;
+                break;
+        case SYSLOG_LEVEL_DEBUG1:
+                txt = "debug1";
+                pri = LOG_DEBUG;
+                break;
+        case SYSLOG_LEVEL_DEBUG2:
+                txt = "debug2";
+                pri = LOG_DEBUG;
+                break;
+        case SYSLOG_LEVEL_DEBUG3:
+                txt = "debug3";
+                pri = LOG_DEBUG;
+                break;
+        default:
+                txt = "internal error";
+                pri = LOG_ERR;
+                break;
+        }
+        if (txt != NULL) {
+                snprintf(fmtbuf, sizeof(fmtbuf), "%s: %s", txt, fmt);
+                vsnprintf(msgbuf, sizeof(msgbuf), fmtbuf, args);
+        } else {
+                vsnprintf(msgbuf, sizeof(msgbuf), fmt, args);
+        }
+        strnvis(fmtbuf, msgbuf, sizeof(fmtbuf),
+            log_on_stderr ? LOG_STDERR_VIS : LOG_SYSLOG_VIS);
+        if (log_on_stderr) {
+                snprintf(msgbuf, sizeof msgbuf, "%s\r\n", fmtbuf);
+                write(STDERR_FILENO, msgbuf, strlen(msgbuf));
+        } else {
+#if defined(HAVE_OPENLOG_R) && defined(SYSLOG_DATA_INIT)
+                syslog_r(pri, &sdata, "%.500s", fmtbuf);
+#else
+                syslog(pri, "%.500s", fmtbuf);
+#endif
+        }
+}
+
+/* Log this message (information that usually should go to the log). */
+
+void
+logit_cr(const char *fmt,...)
+{
+        va_list args;
+
+        va_start(args, fmt);
+        do_log_cr(SYSLOG_LEVEL_INFO, fmt, args);
+        va_end(args);
+}
+void
+fatal_cr(const char *fmt,...)
+{
+        va_list args;
+
+        va_start(args, fmt);
+        do_log_cr(SYSLOG_LEVEL_FATAL, fmt, args);
+        va_end(args);
+	log_end_cr();
+        cleanup_exit(255);
+}
+/* Error messages that should be logged. */
+
+void
+error_cr(const char *fmt,...)
+{
+        va_list args;
+
+        va_start(args, fmt);
+        do_log_cr(SYSLOG_LEVEL_ERROR, fmt, args);
+        va_end(args);
+}
+/* More detailed messages (information that does not need to go to the log). */
+
+void
+verbose_cr(const char *fmt,...)
+{
+        va_list args;
+
+        va_start(args, fmt);
+        do_log_cr(SYSLOG_LEVEL_VERBOSE, fmt, args);
+        va_end(args);
+}
+
+/* Debugging messages that should not be logged during normal operation. */
+
+void
+debug_cr(const char *fmt,...)
+{
+        va_list args;
+
+        va_start(args, fmt);
+        do_log_cr(SYSLOG_LEVEL_DEBUG1, fmt, args);
+        va_end(args);
+}
+void
+debug2_cr(const char *fmt,...)
+{
+        va_list args;
+
+        va_start(args, fmt);
+        do_log_cr(SYSLOG_LEVEL_DEBUG2, fmt, args);
+        va_end(args);
+}
+void
+debug3_cr(const char *fmt,...)
+{
+        va_list args;
+
+        va_start(args, fmt);
+        do_log_cr(SYSLOG_LEVEL_DEBUG3, fmt, args);
+        va_end(args);
+}
+
+
 static int
 errno_to_portable(int unixerrno)
 {
@@ -316,12 +570,12 @@
 handle_log_close(int handle, char *emsg)
 {
 	if (handle_is_ok(handle, HANDLE_FILE)) {
-		logit("%s%sclose \"%s\" bytes read %llu written %llu",
+		logit_cr("%s%sclose \"%s\" bytes read %llu written %llu",
 		    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
 		    handle_to_name(handle),
 		    handle_bytes_read(handle), handle_bytes_write(handle));
 	} else {
-		logit("%s%sclosedir \"%s\"",
+		logit_cr("%s%sclosedir \"%s\"",
 		    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
 		    handle_to_name(handle));
 	}
@@ -386,10 +640,10 @@
 {
 	Buffer msg;
 
-	debug3("request %u: sent status %u", id, status);
+	debug3_cr("request %u: sent status %u", id, status);
 	if (log_level > SYSLOG_LEVEL_VERBOSE ||
 	    (status != SSH2_FX_OK && status != SSH2_FX_EOF))
-		logit("sent status %s", status_to_message(status));
+		logit_cr("sent status %s", status_to_message(status));
 	buffer_init(&msg);
 	buffer_put_char(&msg, SSH2_FXP_STATUS);
 	buffer_put_int(&msg, id);
@@ -417,7 +671,7 @@
 static void
 send_data(u_int32_t id, const char *data, int dlen)
 {
-	debug("request %u: sent data len %d", id, dlen);
+	debug_cr("request %u: sent data len %d", id, dlen);
 	send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
 }
 
@@ -428,7 +682,7 @@
 	int hlen;
 
 	handle_to_string(handle, &string, &hlen);
-	debug("request %u: sent handle handle %d", id, handle);
+	debug_cr("request %u: sent handle handle %d", id, handle);
 	send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
 	xfree(string);
 }
@@ -443,7 +697,7 @@
 	buffer_put_char(&msg, SSH2_FXP_NAME);
 	buffer_put_int(&msg, id);
 	buffer_put_int(&msg, count);
-	debug("request %u: sent names count %d", id, count);
+	debug_cr("request %u: sent names count %d", id, count);
 	for (i = 0; i < count; i++) {
 		buffer_put_cstring(&msg, stats[i].name);
 		buffer_put_cstring(&msg, stats[i].long_name);
@@ -458,7 +712,7 @@
 {
 	Buffer msg;
 
-	debug("request %u: sent attrib have 0x%x", id, a->flags);
+	debug_cr("request %u: sent attrib have 0x%x", id, a->flags);
 	buffer_init(&msg);
 	buffer_put_char(&msg, SSH2_FXP_ATTRS);
 	buffer_put_int(&msg, id);
@@ -475,7 +729,7 @@
 	Buffer msg;
 
 	version = get_int();
-	verbose("received client version %d", version);
+	verbose_cr("received client version %d", version);
 	buffer_init(&msg);
 	buffer_put_char(&msg, SSH2_FXP_VERSION);
 	buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
@@ -494,11 +748,11 @@
 	id = get_int();
 	name = get_string(NULL);
 	pflags = get_int();		/* portable flags */
-	debug3("request %u: open flags %d", id, pflags);
+	debug3_cr("request %u: open flags %d", id, pflags);
 	a = get_attrib();
 	flags = flags_from_portable(pflags);
 	mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm : 0666;
-	logit("open \"%s\" flags %s mode 0%o",
+	logit_cr("open \"%s\" flags %s mode 0%o",
 	    name, string_from_portable(pflags), mode);
 	fd = open(name, flags, mode);
 	if (fd < 0) {
@@ -525,7 +779,7 @@
 
 	id = get_int();
 	handle = get_handle();
-	debug3("request %u: close handle %u", id, handle);
+	debug3_cr("request %u: close handle %u", id, handle);
 	handle_log_close(handle, NULL);
 	ret = handle_close(handle);
 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
@@ -545,16 +799,16 @@
 	off = get_int64();
 	len = get_int();
 
-	debug("request %u: read \"%s\" (handle %d) off %llu len %d",
+	debug_cr("request %u: read \"%s\" (handle %d) off %llu len %d",
 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
 	if (len > sizeof buf) {
 		len = sizeof buf;
-		debug2("read change len %d", len);
+		debug2_cr("read change len %d", len);
 	}
 	fd = handle_to_fd(handle);
 	if (fd >= 0) {
 		if (lseek(fd, off, SEEK_SET) < 0) {
-			error("process_read: seek failed");
+			error_cr("process_read: seek failed");
 			status = errno_to_portable(errno);
 		} else {
 			ret = read(fd, buf, len);
@@ -587,24 +841,24 @@
 	off = get_int64();
 	data = get_string(&len);
 
-	debug("request %u: write \"%s\" (handle %d) off %llu len %d",
+	debug_cr("request %u: write \"%s\" (handle %d) off %llu len %d",
 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
 	fd = handle_to_fd(handle);
 	if (fd >= 0) {
 		if (lseek(fd, off, SEEK_SET) < 0) {
 			status = errno_to_portable(errno);
-			error("process_write: seek failed");
+			error_cr("process_write: seek failed");
 		} else {
 /* XXX ATOMICIO ? */
 			ret = write(fd, data, len);
 			if (ret < 0) {
-				error("process_write: write failed");
+				error_cr("process_write: write failed");
 				status = errno_to_portable(errno);
 			} else if ((size_t)ret == len) {
 				status = SSH2_FX_OK;
 				handle_update_write(handle, ret);
 			} else {
-				debug2("nothing at all written");
+				debug2_cr("nothing at all written");
 			}
 		}
 	}
@@ -623,8 +877,8 @@
 
 	id = get_int();
 	name = get_string(NULL);
-	debug3("request %u: %sstat", id, do_lstat ? "l" : "");
-	verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
+	debug3_cr("request %u: %sstat", id, do_lstat ? "l" : "");
+	verbose_cr("%sstat name \"%s\"", do_lstat ? "l" : "", name);
 	ret = do_lstat ? lstat(name, &st) : stat(name, &st);
 	if (ret < 0) {
 		status = errno_to_portable(errno);
@@ -660,7 +914,7 @@
 
 	id = get_int();
 	handle = get_handle();
-	debug("request %u: fstat \"%s\" (handle %u)",
+	debug_cr("request %u: fstat \"%s\" (handle %u)",
 	    id, handle_to_name(handle), handle);
 	fd = handle_to_fd(handle);
 	if (fd  >= 0) {
@@ -700,15 +954,15 @@
 	id = get_int();
 	name = get_string(NULL);
 	a = get_attrib();
-	debug("request %u: setstat name \"%s\"", id, name);
+	debug_cr("request %u: setstat name \"%s\"", id, name);
 	if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
-		logit("set \"%s\" size %llu", name, a->size);
+		logit_cr("set \"%s\" size %llu", name, a->size);
 		ret = truncate(name, a->size);
 		if (ret == -1)
 			status = errno_to_portable(errno);
 	}
 	if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
-		logit("set \"%s\" mode %04o", name, a->perm);
+		logit_cr("set \"%s\" mode %04o", name, a->perm);
 		ret = chmod(name, a->perm & 0777);
 		if (ret == -1)
 			status = errno_to_portable(errno);
@@ -719,13 +973,13 @@
 
 		strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
 		    localtime(&t));
-		logit("set \"%s\" modtime %s", name, buf);
+		logit_cr("set \"%s\" modtime %s", name, buf);
 		ret = utimes(name, attrib_to_tv(a));
 		if (ret == -1)
 			status = errno_to_portable(errno);
 	}
 	if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
-		logit("set \"%s\" owner %lu group %lu", name,
+		logit_cr("set \"%s\" owner %lu group %lu", name,
 		    (u_long)a->uid, (u_long)a->gid);
 		ret = chown(name, a->uid, a->gid);
 		if (ret == -1)
@@ -746,7 +1000,7 @@
 	id = get_int();
 	handle = get_handle();
 	a = get_attrib();
-	debug("request %u: fsetstat handle %d", id, handle);
+	debug_cr("request %u: fsetstat handle %d", id, handle);
 	fd = handle_to_fd(handle);
 	if (fd < 0) {
 		status = SSH2_FX_FAILURE;
@@ -754,13 +1008,13 @@
 		char *name = handle_to_name(handle);
 
 		if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
-			logit("set \"%s\" size %llu", name, a->size);
+			logit_cr("set \"%s\" size %llu", name, a->size);
 			ret = ftruncate(fd, a->size);
 			if (ret == -1)
 				status = errno_to_portable(errno);
 		}
 		if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
-			logit("set \"%s\" mode %04o", name, a->perm);
+			logit_cr("set \"%s\" mode %04o", name, a->perm);
 #ifdef HAVE_FCHMOD
 			ret = fchmod(fd, a->perm & 0777);
 #else
@@ -775,7 +1029,7 @@
 
 			strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
 			    localtime(&t));
-			logit("set \"%s\" modtime %s", name, buf);
+			logit_cr("set \"%s\" modtime %s", name, buf);
 #ifdef HAVE_FUTIMES
 			ret = futimes(fd, attrib_to_tv(a));
 #else
@@ -785,7 +1039,7 @@
 				status = errno_to_portable(errno);
 		}
 		if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
-			logit("set \"%s\" owner %lu group %lu", name,
+			logit_cr("set \"%s\" owner %lu group %lu", name,
 			    (u_long)a->uid, (u_long)a->gid);
 #ifdef HAVE_FCHOWN
 			ret = fchown(fd, a->uid, a->gid);
@@ -809,8 +1063,8 @@
 
 	id = get_int();
 	path = get_string(NULL);
-	debug3("request %u: opendir", id);
-	logit("opendir \"%s\"", path);
+	debug3_cr("request %u: opendir", id);
+	logit_cr("opendir \"%s\"", path);
 	dirp = opendir(path);
 	if (dirp == NULL) {
 		status = errno_to_portable(errno);
@@ -840,7 +1094,7 @@
 
 	id = get_int();
 	handle = get_handle();
-	debug("request %u: readdir \"%s\" (handle %d)", id,
+	debug_cr("request %u: readdir \"%s\" (handle %d)", id,
 	    handle_to_name(handle), handle);
 	dirp = handle_to_dir(handle);
 	path = handle_to_name(handle);
@@ -895,8 +1149,8 @@
 
 	id = get_int();
 	name = get_string(NULL);
-	debug3("request %u: remove", id);
-	logit("remove name \"%s\"", name);
+	debug3_cr("request %u: remove", id);
+	logit_cr("remove name \"%s\"", name);
 	ret = unlink(name);
 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
 	send_status(id, status);
@@ -916,8 +1170,8 @@
 	a = get_attrib();
 	mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
 	    a->perm & 0777 : 0777;
-	debug3("request %u: mkdir", id);
-	logit("mkdir name \"%s\" mode 0%o", name, mode);
+	debug3_cr("request %u: mkdir", id);
+	logit_cr("mkdir name \"%s\" mode 0%o", name, mode);
 	ret = mkdir(name, mode);
 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
 	send_status(id, status);
@@ -933,8 +1187,8 @@
 
 	id = get_int();
 	name = get_string(NULL);
-	debug3("request %u: rmdir", id);
-	logit("rmdir name \"%s\"", name);
+	debug3_cr("request %u: rmdir", id);
+	logit_cr("rmdir name \"%s\"", name);
 	ret = rmdir(name);
 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
 	send_status(id, status);
@@ -954,8 +1208,8 @@
 		xfree(path);
 		path = xstrdup(".");
 	}
-	debug3("request %u: realpath", id);
-	verbose("realpath \"%s\"", path);
+	debug3_cr("request %u: realpath", id);
+	verbose_cr("realpath \"%s\"", path);
 	if (realpath(path, resolvedname) == NULL) {
 		send_status(id, errno_to_portable(errno));
 	} else {
@@ -964,6 +1218,7 @@
 		s.name = s.long_name = resolvedname;
 		send_names(id, 1, &s);
 	}
+	verbose_cr("realpath \"%s\"", resolvedname);
 	xfree(path);
 }
 
@@ -978,8 +1233,8 @@
 	id = get_int();
 	oldpath = get_string(NULL);
 	newpath = get_string(NULL);
-	debug3("request %u: rename", id);
-	logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
+	debug3_cr("request %u: rename", id);
+	logit_cr("rename old \"%s\" new \"%s\"", oldpath, newpath);
 	status = SSH2_FX_FAILURE;
 	if (lstat(oldpath, &sb) == -1)
 		status = errno_to_portable(errno);
@@ -1034,8 +1289,8 @@
 
 	id = get_int();
 	path = get_string(NULL);
-	debug3("request %u: readlink", id);
-	verbose("readlink \"%s\"", path);
+	debug3_cr("request %u: readlink", id);
+	verbose_cr("readlink \"%s\"", path);
 	if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
 		send_status(id, errno_to_portable(errno));
 	else {
@@ -1059,8 +1314,8 @@
 	id = get_int();
 	oldpath = get_string(NULL);
 	newpath = get_string(NULL);
-	debug3("request %u: symlink", id);
-	logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
+	debug3_cr("request %u: symlink", id);
+	logit_cr("symlink old \"%s\" new \"%s\"", oldpath, newpath);
 	/* this will fail if 'newpath' exists */
 	ret = symlink(oldpath, newpath);
 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
@@ -1098,7 +1353,7 @@
 	cp = buffer_ptr(&iqueue);
 	msg_len = get_u32(cp);
 	if (msg_len > SFTP_MAX_MSG_LENGTH) {
-		error("bad message from %s local user %s",
+		error_cr("bad message from %s local user %s",
 		    client_addr, pw->pw_name);
 		cleanup_exit(11);
 	}
@@ -1169,15 +1424,17 @@
 		process_extended();
 		break;
 	default:
-		error("Unknown message %d", type);
+		error_cr("Unknown message %d", type);
 		break;
 	}
 	/* discard the remaining bytes from the current packet */
-	if (buf_len < buffer_len(&iqueue))
-		fatal("iqueue grew unexpectedly");
+	if (buf_len < buffer_len(&iqueue)) {
+		fatal_cr("iqueue grew unexpectedly");
+        }
 	consumed = buf_len - buffer_len(&iqueue);
-	if (msg_len < consumed)
-		fatal("msg_len %d < consumed %d", msg_len, consumed);
+	if (msg_len < consumed) {
+		fatal_cr("msg_len %d < consumed %d", msg_len, consumed);
+        }
 	if (msg_len > consumed)
 		buffer_consume(&iqueue, msg_len - consumed);
 }
@@ -1188,9 +1445,10 @@
 {
 	if (pw != NULL && client_addr != NULL) {
 		handle_log_exit();
-		logit("session closed for local user %s from [%s]",
+		logit_cr("session closed for local user %s from [%s]",
 		    pw->pw_name, client_addr);
 	}
+	log_end_cr();
 	_exit(i);
 }
 
@@ -1200,7 +1458,8 @@
 	extern char *__progname;
 
 	fprintf(stderr,
-	    "usage: %s [-he] [-l log_level] [-f log_facility]\n", __progname);
+	    "usage: %s [-he] [-l log_level] [-f log_facility] [-r chroot_root]\n", __progname);
+	log_end_cr();
 	exit(1);
 }
 
@@ -1211,7 +1470,12 @@
 	int in, out, max, ch, skipargs = 0, log_stderr = 0;
 	ssize_t len, olen, set_size;
 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
+        int ires;
+        char *resolvedpath=NULL;
+        char *chrootpath=NULL;
 	char *cp;
+        char *root=NULL;
+        struct stat st;
 
 	extern char *optarg;
 	extern char *__progname;
@@ -1220,9 +1484,9 @@
 	sanitise_stdfd();
 
 	__progname = ssh_get_progname(argv[0]);
-	log_init(__progname, log_level, log_facility, log_stderr);
+	log_init_cr(__progname, log_level, log_facility, log_stderr);
 
-	while (!skipargs && (ch = getopt(argc, argv, "C:f:l:che")) != -1) {
+	while (!skipargs && (ch = getopt(argc, argv, "C:f:l:r:che")) != -1) {
 		switch (ch) {
 		case 'c':
 			/*
@@ -1237,12 +1501,20 @@
 		case 'l':
 			log_level = log_level_number(optarg);
 			if (log_level == SYSLOG_LEVEL_NOT_SET)
-				error("Invalid log level \"%s\"", optarg);
+				error_cr("Invalid log level \"%s\"", optarg);
 			break;
 		case 'f':
 			log_facility = log_facility_number(optarg);
-			if (log_level == SYSLOG_FACILITY_NOT_SET)
-				error("Invalid log facility \"%s\"", optarg);
+			if (log_facility == SYSLOG_FACILITY_NOT_SET)
+				error_cr("Invalid log facility \"%s\"", optarg);
+			break;
+		case 'r':
+        		if (stat(optarg, &st) || !S_ISDIR(st.st_mode)) {
+				setregid(getgid(),getgid());
+				setreuid(getuid(),getuid());
+				fatal_cr("Invalid chroot root \"%s\"", optarg);
+			}
+			root = strdup(optarg);
 			break;
 		case 'h':
 		default:
@@ -1250,22 +1522,28 @@
 		}
 	}
 
-	log_init(__progname, log_level, log_facility, log_stderr);
+	log_init_cr(__progname, log_level, log_facility, log_stderr);
 
 	if ((cp = getenv("SSH_CONNECTION")) != NULL) {
 		client_addr = xstrdup(cp);
-		if ((cp = strchr(client_addr, ' ')) == NULL)
-			fatal("Malformed SSH_CONNECTION variable: \"%s\"",
+		if ((cp = strchr(client_addr, ' ')) == NULL) {
+			setregid(getgid(),getgid());
+			setreuid(getuid(),getuid());
+			fatal_cr("Malformed SSH_CONNECTION variable: \"%s\"",
 			    getenv("SSH_CONNECTION"));
+                }
 		*cp = '\0';
 	} else
 		client_addr = xstrdup("UNKNOWN");
 
-	if ((pw = getpwuid(getuid())) == NULL)
-		fatal("No user found for uid %lu", (u_long)getuid());
+	if ((pw = getpwuid(getuid())) == NULL) {
+		setregid(getgid(),getgid());
+		setreuid(getuid(),getuid());
+		fatal_cr("No user found for uid %lu", (u_long)getuid());
+        }
 	pw = pwcopy(pw);
 
-	logit("session opened for local user %s from [%s]",
+	logit_cr("session opened for local user %s from [%s]",
 	    pw->pw_name, client_addr);
 
 	handle_init();
@@ -1273,6 +1551,73 @@
 	in = dup(STDIN_FILENO);
 	out = dup(STDOUT_FILENO);
 
+#define min(a,b)  (a<b)?a:b
+
+	resolvedpath=xmalloc(MAXPATHLEN);
+	if (realpath(".", resolvedpath) == NULL) {
+		setregid(getgid(),getgid());
+		setreuid(getuid(),getuid());
+		logit_cr("realpath error");
+		log_end_cr();
+		if (resolvedpath)
+			xfree(resolvedpath); 
+		exit(1);
+	} else {
+		if ( !strcmp(pw->pw_dir,resolvedpath) ){
+			if ( root ) {
+				chrootpath=xmalloc(MAXPATHLEN);
+				strncpy(chrootpath,root,MAXPATHLEN);
+				chrootpath[MAXPATHLEN-1]='\0';
+				strncat(chrootpath,resolvedpath,min(strlen(resolvedpath),MAXPATHLEN-strlen(chrootpath)-1));
+			} else {
+				chrootpath=strdup(resolvedpath);
+			} 
+        		if (stat(chrootpath, &st) || !S_ISDIR(st.st_mode)) {
+				setregid(getgid(),getgid());
+				setreuid(getuid(),getuid());
+				if (resolvedpath)
+					xfree(resolvedpath); 
+				if (chrootpath)
+					xfree(chrootpath); 
+				fatal_cr("Invalid chroot root \"%s\"", chrootpath);
+			}
+
+			ires = chroot(chrootpath);
+			setregid(getgid(),getgid());
+			setreuid(getuid(),getuid());
+			chdir("/");
+
+			if ( !ires ) {
+				logit_cr("User: %s Parent pid %d",pw->pw_name,getppid());
+				logit_cr("User: %s Chroot set to %s", pw->pw_name,chrootpath);
+				if (chrootpath)
+					xfree(chrootpath); 
+			} else {
+				logit_cr("User: %s Parent pid %d",pw->pw_name,getppid());
+				logit_cr("User: %s Chroot to %s failed (%d)",pw->pw_name,chrootpath,ires);
+				log_end_cr();
+				if (resolvedpath)
+					xfree(resolvedpath); 
+				if (chrootpath)
+					xfree(chrootpath); 
+				exit(1);
+			}
+		} else {
+			setregid(getgid(),getgid());
+			setreuid(getuid(),getuid());
+			logit_cr("User: %s Parent pid %d",pw->pw_name,getppid());
+			logit_cr("Home directory %s and local directory %s don't match.",pw->pw_dir,resolvedpath);
+                        log_end_cr();
+			if (resolvedpath)
+				xfree(resolvedpath); 
+			if (chrootpath)
+				xfree(chrootpath); 
+			exit(1);
+		}
+	}
+	if (resolvedpath)
+		xfree(resolvedpath); 
+
 #ifdef HAVE_CYGWIN
 	setmode(in, O_BINARY);
 	setmode(out, O_BINARY);
@@ -1303,7 +1648,7 @@
 		if (select(max+1, rset, wset, NULL, NULL) < 0) {
 			if (errno == EINTR)
 				continue;
-			error("select: %s", strerror(errno));
+			error_cr("select: %s", strerror(errno));
 			cleanup_exit(2);
 		}
 
@@ -1312,10 +1657,10 @@
 			char buf[4*4096];
 			len = read(in, buf, sizeof buf);
 			if (len == 0) {
-				debug("read eof");
+				debug_cr("read eof");
 				cleanup_exit(0);
 			} else if (len < 0) {
-				error("read: %s", strerror(errno));
+				error_cr("read: %s", strerror(errno));
 				cleanup_exit(1);
 			} else {
 				buffer_append(&iqueue, buf, len);
@@ -1325,7 +1670,7 @@
 		if (FD_ISSET(out, wset)) {
 			len = write(out, buffer_ptr(&oqueue), olen);
 			if (len < 0) {
-				error("write: %s", strerror(errno));
+				error_cr("write: %s", strerror(errno));
 				cleanup_exit(1);
 			} else {
 				buffer_consume(&oqueue, len);
