changeset 511:582cb38e4eb5 insecure-nocrypto

propagate from branch 'au.asn.ucc.matt.dropbear' (head cdcc3c729e29544e8b98a408e2dc60e4483dfd2a) to branch 'au.asn.ucc.matt.dropbear.insecure-nocrypto' (head 0ca38a1cf349f7426ac9de34ebe4c3e3735effab)
author Matt Johnston <matt@ucc.asn.au>
date Thu, 06 Nov 2008 13:16:55 +0000
parents 461c4b1fb35f (current diff) b85507ade010 (diff)
children 0129fd8ccc71
files cli-auth.c common-algo.c common-kex.c libtomcrypt/src/headers/ltc_tommath.h libtomcrypt/src/headers/tommath_class.h libtomcrypt/src/headers/tommath_superclass.h libtomcrypt/src/misc/mpi/is_prime.c libtomcrypt/src/misc/mpi/mpi_to_ltc_error.c libtomcrypt/src/misc/mpi/rand_prime.c libtomcrypt/src/pk/asn1/der/sequence/der_decode_sequence.c libtomcrypt/src/pk/asn1/der/sequence/der_encode_sequence.c libtomcrypt/src/pk/dh/dh.c libtomcrypt/src/pk/dh/dh_sys.c libtomcrypt/src/pk/ecc/ecc_sys.c libtomcrypt/src/pk/packet_store_header.c libtomcrypt/src/pk/packet_valid_header.c libtomcrypt/testprof/dh_tests.c libtomcrypt/testprof/test.c libtommath/TODO libtommath/logs/sqr.old options.h
diffstat 601 files changed, 31573 insertions(+), 13003 deletions(-) [+]
line wrap: on
line diff
--- a/CHANGES	Mon Oct 02 06:40:51 2006 +0000
+++ b/CHANGES	Thu Nov 06 13:16:55 2008 +0000
@@ -1,3 +1,144 @@
+0.52
+
+- Add "netcat-alike" option (-B) to dbclient, allowing Dropbear to tunnel
+  standard input/output to a TCP port-forwarded remote host.
+
+- Add "proxy command" support to dbclient, to allow using a spawned process for
+  IO rather than a direct TCP connection. eg
+	  dbclient remotehost
+  is equivalent to
+	  dbclient -J 'nc remotehost 22' remotehost
+  (the hostname is still provided purely for looking up saved host keys)
+
+- Combine netcat-alike and proxy support to allow "multihop" connections, with
+  comma-separated host syntax.  Allows running
+	  dbclient [email protected],[email protected],[email protected]
+  to end up at host3 via the other two, using SSH TCP forwarding. It's a bit
+  like onion-routing. All connections are established from the local machine.
+  The comma-separated syntax can also be used for scp/rsync, eg
+	  scp -S dbclient [email protected],[email protected],canyons:/tmp/dump .
+  to bounce through a few hosts.
+
+- Allow restrictions on authorized_keys logins such as restricting commands
+  to be run etc. This is a subset of those allowed by OpenSSH, doesn't
+  yet allow restricting source host.
+
+- Use vfork() for scp on uClinux
+
+- Default to PATH=/usr/bin:/bin for shells.
+
+- Report errors if -R forwarding fails
+
+- Add counter mode cipher support, which avoids some security problems with the
+  standard CBC mode.
+
+- Support [email protected] delayed compression for client/server. It can be
+  required for the Dropbear server with the '-Z' option. This is useful for
+  security as it avoids exposing the server to attacks on zlib by
+  unauthenticated remote users, though requires client side support.
+
+- options.h has been split into options.h (user-changable) and sysoptions.h
+  (less commonly changed)
+
+- Support "dbclient -s sftp" to specify a subsystem
+
+- Fix a bug in replies to channel requests that could be triggered by recent
+  versions of PuTTY
+
+0.51 - Thu 27 March 2008
+
+- Make a copy of password fields rather erroneously relying on getwpnam()
+  to be safe to call multiple times
+
+- If $SSH_ASKPASS_ALWAYS environment variable is set (and $SSH_ASKPASS is
+  as well) always use that program, ignoring isatty() and $DISPLAY
+
+- Wait until a process exits before the server closes a connection, so
+  that an exit code can be sent. This fixes problems with exit codes not
+  being returned, which could cause scp to fail.
+
+0.50 - Wed 8 August 2007
+
+- Add DROPBEAR_PASSWORD environment variable to specify a dbclient password
+
+- Use /dev/urandom by default, since that's what everyone does anyway
+
+- Correct vfork() use for uClinux in scp
+  (thanks to Alex Landau)
+
+- Exit with an exit code of 1 if dropbear can't bind to any ports
+  (thanks to Nicolai Ehemann)
+
+- Improve network performance and add a -W <receive_window> argument for
+  adjusting the tradeoff between network performance and memory consumption.
+
+- Fix a problem where reply packets could be sent during key exchange,
+  in violation of the SSH spec. This could manifest itself with connections
+  being terminated after 8 hours with new TCP-forward connections being
+  established.
+
+- Add -K <keepalive_time> argument, ensuring that data is transmitted
+  over the connection at least every N seconds.
+
+- dropbearkey will no longer generate DSS keys of sizes other than 1024
+  bits, as required by the DSS specification. (Other sizes are still
+  accepted for use to provide backwards compatibility).
+
+0.49 - Fri 23 February 2007
+
+- Security: dbclient previously would prompt to confirm a 
+  mismatching hostkey but wouldn't warn loudly. It will now
+  exit upon a mismatch.
+
+- Compile fixes, make sure that all variable definitions are at the start
+  of a scope.
+
+- Added -P pidfile argument to the server (from Swen Schillig)
+
+- Add -N dbclient option for "no command"
+
+- Add -f dbclient option for "background after auth"
+
+- Add ability to limit binding to particular addresses, use 
+  -p [address:]port, patch from Max-Gerd Retzlaff.
+
+- Try to finally fix ss_family compilation problems (for old
+  glibc systems)
+
+- Fix finding relative-path server hostkeys when running daemonized
+
+- Use $HOME in preference to that from /etc/passwd, so that
+  dbclient can still work on broken systems.
+
+- Fix various issues found by Klocwork defect analysis, mostly memory leaks
+  and error-handling. Thanks to Klocwork for their service.
+
+- Improve building in a separate directory
+
+- Add compile-time LOG_COMMANDS option to log user commands
+
+- Add '-y' flag to dbclient to unconditionally accept host keys,
+  patch from Luciano Miguel Ferreira Rocha
+
+- Return immediately for "sleep 10 & echo foo", rather than waiting
+  for the sleep to return (pointed out by Rob Landley).
+  
+- Avoid hanging after exit in certain cases (such as scp)
+
+- Various minor fixes, in particular various leaks reported by
+  Erik Hovland
+  
+- Disable core dumps on startup
+
+- Don't erase over every single buffer, since it was a bottleneck.
+  On systems where it really matters, encrypted swap should be utilised.
+
+- Read /dev/[u]random only once at startup to conserve kernel entropy
+
+- Upgrade to LibTomCrypt 1.16 and LibTomMath 0.40
+
+- Upgrade config.status and config.guess 
+
 0.48.1 - Sat 11 March 2006
 
 - Compile fix for scp
--- a/INSTALL	Mon Oct 02 06:40:51 2006 +0000
+++ b/INSTALL	Thu Nov 06 13:16:55 2008 +0000
@@ -24,7 +24,7 @@
 
 If you want to compile statically, add "STATIC=1" to the make command-line.
 
-Binaries can be strippd with "make strip"
+Binaries can be stripped with "make strip"
 
 ============================================================================
 
--- a/LICENSE	Mon Oct 02 06:40:51 2006 +0000
+++ b/LICENSE	Thu Nov 06 13:16:55 2008 +0000
@@ -8,7 +8,7 @@
 Portions of the client-mode work are (c) 2004 Mihnea Stoenescu, under the
 same license:
 
-Copyright (c) 2002-2004 Matt Johnston
+Copyright (c) 2002-2008 Matt Johnston
 Portions copyright (c) 2004 Mihnea Stoenescu
 All rights reserved.
 
--- a/Makefile.in	Mon Oct 02 06:40:51 2006 +0000
+++ b/Makefile.in	Thu Nov 06 13:16:55 2008 +0000
@@ -23,7 +23,7 @@
 		atomicio.o compat.o  fake-rfc2553.o
 
 SVROBJS=svr-kex.o svr-algo.o svr-auth.o sshpty.o \
-		svr-authpasswd.o svr-authpubkey.o svr-session.o svr-service.o \
+		svr-authpasswd.o svr-authpubkey.o svr-authpubkeyoptions.o svr-session.o svr-service.o \
 		svr-chansession.o svr-runopts.o svr-agentfwd.o svr-main.o svr-x11fwd.o\
 		svr-tcpfwd.o svr-authpam.o
 
@@ -64,12 +64,12 @@
 sbindir=${exec_prefix}/sbin
 
 [email protected]@
[email protected]@
 [email protected]@
 [email protected]@
 [email protected]@
 [email protected]@
-CFLAGS=-I. -I$(srcdir)/libtomcrypt/src/headers/ @[email protected]
[email protected]@
+CFLAGS=-I. -I$(srcdir) -I$(srcdir)/libtomcrypt/src/headers/ $(CPPFLAGS) @[email protected]
 LIBS=$(LTC) $(LTM) @[email protected]
 [email protected]@
 
@@ -155,11 +155,11 @@
 
 dropbear dbclient dropbearkey dropbearconvert: $(HEADERS)  $(LTC) $(LTM) \
 													Makefile
-	$(LD) $(LDFLAGS) -o [email protected]$(EXEEXT) $([email protected]) $(LIBS)
+	$(CC) $(LDFLAGS) -o [email protected]$(EXEEXT) $([email protected]) $(LIBS)
 
 # scp doesn't use the libs so is special.
 scp: $(SCPOBJS)  $(HEADERS) Makefile
-	$(LD) $(LDFLAGS) -o [email protected]$(EXEEXT) $(SCPOBJS)
+	$(CC) $(LDFLAGS) -o [email protected]$(EXEEXT) $(SCPOBJS)
 
 
 # multi-binary compilation.
@@ -172,7 +172,7 @@
 dropbearmulti: multilink 
 
 multibinary: $(HEADERS) $(MULTIOBJS) $(LTC) $(LTM) Makefile
-	$(LD) $(LDFLAGS) -o dropbearmulti$(EXEEXT) $(MULTIOBJS) $(LIBS)
+	$(CC) $(LDFLAGS) -o dropbearmulti$(EXEEXT) $(MULTIOBJS) $(LIBS)
 
 multilink: multibinary $(addprefix link, $(PROGRAMS))
 
@@ -186,6 +186,8 @@
 $(LTM): options.h
 	cd libtommath && $(MAKE)
 
+.PHONY : clean sizes thisclean distclean tidy ltc-clean ltm-clean
+
 ltc-clean:
 	cd libtomcrypt && $(MAKE) clean
 
--- a/algo.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/algo.h	Thu Nov 06 13:16:55 2008 +0000
@@ -29,13 +29,18 @@
 #include "includes.h"
 #include "buffer.h"
 
+#define DROPBEAR_MODE_UNUSED 0
+#define DROPBEAR_MODE_CBC 1
+#define DROPBEAR_MODE_CTR 2
+
 struct Algo_Type {
 
 	unsigned char *name; /* identifying name */
 	char val; /* a value for this cipher, or -1 for invalid */
-	void *data; /* algorithm specific data */
-	unsigned usable : 1; /* whether we can use this algorithm */
-
+	const void *data; /* algorithm specific data */
+	char usable; /* whether we can use this algorithm */
+	const void *mode; /* the mode, currently only used for ciphers,
+						 points to a 'struct dropbear_cipher_mode' */
 };
 
 typedef struct Algo_Type algo_type;
@@ -48,6 +53,7 @@
 extern algo_type sshcompress[];
 
 extern const struct dropbear_cipher dropbear_nocipher;
+extern const struct dropbear_cipher_mode dropbear_mode_none;
 extern const struct dropbear_hash dropbear_nohash;
 
 struct dropbear_cipher {
@@ -56,6 +62,16 @@
 	unsigned char blocksize;
 };
 
+struct dropbear_cipher_mode {
+	int (*start)(int cipher, const unsigned char *IV, 
+			const unsigned char *key, 
+			int keylen, int num_rounds, void *cipher_state);
+	int (*encrypt)(const unsigned char *pt, unsigned char *ct, 
+			unsigned long len, void *cipher_state);
+	int (*decrypt)(const unsigned char *ct, unsigned char *pt, 
+			unsigned long len, void *cipher_state);
+};
+
 struct dropbear_hash {
 	const struct ltc_hash_descriptor *hashdesc;
 	unsigned long keysize;
--- a/auth.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/auth.h	Thu Nov 06 13:16:55 2008 +0000
@@ -26,6 +26,7 @@
 #define _AUTH_H_
 
 #include "includes.h"
+#include "chansession.h"
 
 void svr_authinitialise();
 void cli_authinitialise();
@@ -38,6 +39,25 @@
 void svr_auth_pubkey();
 void svr_auth_pam();
 
+#ifdef ENABLE_SVR_PUBKEY_OPTIONS
+int svr_pubkey_allows_agentfwd();
+int svr_pubkey_allows_tcpfwd();
+int svr_pubkey_allows_x11fwd();
+int svr_pubkey_allows_pty();
+void svr_pubkey_set_forced_command(struct ChanSess *chansess);
+void svr_pubkey_options_cleanup();
+int svr_add_pubkey_options(buffer *options_buf, int line_num, const char* filename);
+#else
+/* no option : success */
+#define svr_pubkey_allows_agentfwd() 1
+#define svr_pubkey_allows_tcpfwd() 1
+#define svr_pubkey_allows_x11fwd() 1
+#define svr_pubkey_allows_pty() 1
+static inline void svr_pubkey_set_forced_command(struct ChanSess *chansess) { }
+static inline void svr_pubkey_options_cleanup() { }
+#define svr_add_pubkey_options(x,y,z) DROPBEAR_SUCCESS
+#endif
+
 /* Client functions */
 void recv_msg_userauth_failure();
 void recv_msg_userauth_success();
@@ -52,7 +72,7 @@
 void cli_auth_password();
 int cli_auth_pubkey();
 void cli_auth_interactive();
-char* getpass_or_cancel();
+char* getpass_or_cancel(char* prompt);
 
 
 #define MAX_USERNAME_LEN 25 /* arbitrary for the moment */
@@ -91,8 +111,15 @@
 							   logged. */
 
 	/* These are only used for the server */
-	char *printableuser; /* stripped of control chars, used for logs etc */
-	struct passwd * pw;
+	uid_t pw_uid;
+	gid_t pw_gid;
+	char *pw_dir;
+	char *pw_shell;
+	char *pw_name;
+	char *pw_passwd;
+#ifdef ENABLE_SVR_PUBKEY_OPTIONS
+	struct PubKeyOptions* pubkey_options;
+#endif
 
 };
 
@@ -108,4 +135,18 @@
 
 };
 
+#ifdef ENABLE_SVR_PUBKEY_OPTIONS
+struct PubKeyOptions;
+struct PubKeyOptions {
+	/* Flags */
+	int no_port_forwarding_flag;
+	int no_agent_forwarding_flag;
+	int no_x11_forwarding_flag;
+	int no_pty_flag;
+	/* "command=" option. */
+	unsigned char * forced_command;
+
+};
+#endif
+
 #endif /* _AUTH_H_ */
--- a/channel.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/channel.h	Thu Nov 06 13:16:55 2008 +0000
@@ -45,16 +45,8 @@
 /* Not a real type */
 #define SSH_OPEN_IN_PROGRESS					99
 
-#define MAX_CHANNELS 100 /* simple mem restriction, includes each tcp/x11
-							connection, so can't be _too_ small */
-
 #define CHAN_EXTEND_SIZE 3 /* how many extra slots to add when we need more */
 
-#define RECV_MAXWINDOW 8000 /* tweak */
-#define RECV_WINDOWEXTEND 1000 /* We send a "window extend" every
-								RECV_WINDOWEXTEND bytes */
-#define RECV_MAXPACKET RECV_MAXWINDOW /* tweak */
-
 struct ChanType;
 
 struct Channel {
@@ -73,10 +65,9 @@
 	circbuffer *extrabuf; /* extended-data for the program - used like writebuf
 					     but for stderr */
 
-	int sentclosed, recvclosed;
-
-	/* this is set when we receive/send a channel eof packet */
-	int recveof, senteof;
+	/* whether close/eof messages have been exchanged */
+	int sent_close, recv_close;
+	int recv_eof, sent_eof;
 
 	int initconn; /* used for TCP forwarding, whether the channel has been
 					 fully initialised */
@@ -85,6 +76,8 @@
 					   for this channel (and are awaiting a confirmation
 					   or failure). */
 
+	int flushing;
+
 	const struct ChanType* type;
 
 };
@@ -94,7 +87,7 @@
 	int sepfds; /* Whether this channel has seperate pipes for in/out or not */
 	char *name;
 	int (*inithandler)(struct Channel*);
-	int (*checkclose)(struct Channel*);
+	int (*check_close)(struct Channel*);
 	void (*reqhandler)(struct Channel*);
 	void (*closehandler)(struct Channel*);
 
--- a/chansession.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/chansession.h	Thu Nov 06 13:16:55 2008 +0000
@@ -78,6 +78,9 @@
 void cli_send_chansess_request();
 void cli_tty_cleanup();
 void cli_chansess_winchange();
+#ifdef ENABLE_CLI_NETCAT
+void cli_send_netcat_request();
+#endif
 
 void svr_chansessinitialise();
 extern const struct ChanType svrchansess;
--- a/cli-auth.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-auth.c	Thu Nov 06 13:16:55 2008 +0000
@@ -229,6 +229,8 @@
 
 void recv_msg_userauth_success() {
 	TRACE(("received msg_userauth_success"))
+	/* Note: in delayed-zlib mode, setting authdone here 
+	 * will enable compression in the transport layer */
 	ses.authstate.authdone = 1;
 	cli_ses.state = USERAUTH_SUCCESS_RCVD;
 	cli_ses.lastauthtype = AUTH_TYPE_NONE;
@@ -236,8 +238,8 @@
 
 void cli_auth_try() {
 
+	int finished = 0;
 	TRACE(("enter cli_auth_try"))
-	int finished = 0;
 
 	CHECKCLEARTOWRITE();
 	
@@ -287,11 +289,20 @@
 
 /* A helper for getpass() that exits if the user cancels. The returned
  * password is statically allocated by getpass() */
-char* getpass_or_cancel()
+char* getpass_or_cancel(char* prompt)
 {
 	char* password = NULL;
+	
+#ifdef DROPBEAR_PASSWORD_ENV
+    /* Password provided in an environment var */
+    password = getenv(DROPBEAR_PASSWORD_ENV);
+    if (password)
+    {
+        return password;
+    }
+#endif
 
-	password = getpass("Password: ");
+	password = getpass(prompt);
 
 	/* 0x03 is a ctrl-c character in the buffer. */
 	if (password == NULL || strchr(password, '\3') != NULL) {
--- a/cli-authinteract.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-authinteract.c	Thu Nov 06 13:16:55 2008 +0000
@@ -77,6 +77,11 @@
 
 	TRACE(("enter recv_msg_recv_userauth_info_request"))
 
+	/* Let the user know what password/host they are authing for */
+	if (!cli_ses.interact_request_received) {
+		fprintf(stderr, "Login for %[email protected]%s\n", cli_opts.username,
+				cli_opts.remotehost);
+	}
 	cli_ses.interact_request_received = 1;
 
 	name = buf_getstring(ses.payload, NULL);
@@ -99,13 +104,14 @@
 	if (strlen(name) > 0) {
 		cleantext(name);
 		fprintf(stderr, "%s", name);
-		m_free(name);
 	}
+	m_free(name);
+
 	if (strlen(instruction) > 0) {
 		cleantext(instruction);
 		fprintf(stderr, "%s", instruction);
-		m_free(instruction);
 	}
+	m_free(instruction);
 
 	for (i = 0; i < num_prompts; i++) {
 		unsigned int response_len = 0;
--- a/cli-authpasswd.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-authpasswd.c	Thu Nov 06 13:16:55 2008 +0000
@@ -38,7 +38,9 @@
 	char* askpass_prog = NULL;
 
 	askpass_prog = getenv("SSH_ASKPASS");
-	return askpass_prog && !isatty(STDIN_FILENO) && getenv("DISPLAY");
+	return askpass_prog && 
+		((!isatty(STDIN_FILENO) && getenv("DISPLAY") )
+		 	|| getenv("SSH_ASKPASS_ALWAYS"));
 }
 
 /* returns a statically allocated password from a helper app, or NULL
@@ -116,16 +118,25 @@
 void cli_auth_password() {
 
 	char* password = NULL;
+	char prompt[80];
 
 	TRACE(("enter cli_auth_password"))
 	CHECKCLEARTOWRITE();
 
+	snprintf(prompt, sizeof(prompt), "%[email protected]%s's password: ", 
+				cli_opts.username, cli_opts.remotehost);
 #ifdef ENABLE_CLI_ASKPASS_HELPER
 	if (want_askpass())
-		password = gui_getpass("Password: ");
-	else
+	{
+		password = gui_getpass(prompt);
+		if (!password) {
+			dropbear_exit("No password");
+		}
+	} else
 #endif
-		password = getpass_or_cancel("Password: ");
+	{
+		password = getpass_or_cancel(prompt);
+	}
 
 	buf_putbyte(ses.writepayload, SSH_MSG_USERAUTH_REQUEST);
 
--- a/cli-authpubkey.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-authpubkey.c	Thu Nov 06 13:16:55 2008 +0000
@@ -60,8 +60,8 @@
 
 void recv_msg_userauth_pk_ok() {
 
-	struct SignKeyList *keyitem;
-	buffer* keybuf;
+	struct SignKeyList *keyitem = NULL;
+	buffer* keybuf = NULL;
 	char* algotype = NULL;
 	unsigned int algolen;
 	int keytype;
@@ -112,6 +112,7 @@
 		/* Success */
 		break;
 	}
+	buf_free(keybuf);
 
 	if (keyitem != NULL) {
 		TRACE(("matching key"))
@@ -121,7 +122,7 @@
 	} else {
 		TRACE(("That was whacky. We got told that a key was valid, but it didn't match our list. Sounds like dodgy code on Dropbear's part"))
 	}
-
+	
 	TRACE(("leave recv_msg_userauth_pk_ok"))
 }
 
--- a/cli-channel.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-channel.c	Thu Nov 06 13:16:55 2008 +0000
@@ -39,9 +39,6 @@
 	TRACE(("enter recv_msg_channel_extended_data"))
 
 	channel = getchannel();
-	if (channel == NULL) {
-		dropbear_exit("Unknown channel");
-	}
 
 	if (channel->type != &clichansess) {
 		TRACE(("leave recv_msg_channel_extended_data: chantype is wrong"))
--- a/cli-chansession.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-chansession.c	Thu Nov 06 13:16:55 2008 +0000
@@ -64,16 +64,17 @@
 	type = buf_getstring(ses.payload, NULL);
 	wantreply = buf_getbool(ses.payload);
 
-	if (strcmp(type, "exit-status") != 0) {
+	if (strcmp(type, "exit-status") == 0) {
+		cli_ses.retval = buf_getint(ses.payload);
+		TRACE(("got exit-status of '%d'", cli_ses.retval))
+	} else if (strcmp(type, "exit-signal") == 0) {
+		TRACE(("got exit-signal, ignoring it"))
+	} else {
 		TRACE(("unknown request '%s'", type))
 		send_msg_channel_failure(channel);
 		goto out;
 	}
 		
-	/* We'll just trust what they tell us */
-	cli_ses.retval = buf_getint(ses.payload);
-	TRACE(("got exit-status of '%d'", cli_ses.retval))
-
 out:
 	m_free(type);
 }
@@ -162,8 +163,6 @@
 
 static void put_termcodes() {
 
-	TRACE(("enter put_termcodes"))
-
 	struct termios tio;
 	unsigned int sshcode;
 	const struct TermCode *termcode;
@@ -172,6 +171,8 @@
 
 	unsigned int bufpos1, bufpos2;
 
+	TRACE(("enter put_termcodes"))
+
 	if (tcgetattr(STDIN_FILENO, &tio) == -1) {
 		dropbear_log(LOG_WARNING, "Failed reading termmodes");
 		buf_putint(ses.writepayload, 1); /* Just the terminator */
@@ -320,7 +321,11 @@
 	TRACE(("enter send_chansess_shell_req"))
 
 	if (cli_opts.cmd) {
-		reqtype = "exec";
+		if (cli_opts.is_subsystem) {
+			reqtype = "subsystem";
+		} else {
+			reqtype = "exec";
+		}
 	} else {
 		reqtype = "shell";
 	}
@@ -337,9 +342,8 @@
 	TRACE(("leave send_chansess_shell_req"))
 }
 
-static int cli_initchansess(struct Channel *channel) {
-
-
+/* Shared for normal client channel and netcat-alike */
+static int cli_init_stdpipe_sess(struct Channel *channel) {
 	channel->writefd = STDOUT_FILENO;
 	setnonblocking(STDOUT_FILENO);
 
@@ -349,7 +353,13 @@
 	channel->errfd = STDERR_FILENO;
 	setnonblocking(STDERR_FILENO);
 
-	channel->extrabuf = cbuf_new(RECV_MAXWINDOW);
+	channel->extrabuf = cbuf_new(opts.recv_window);
+	return 0;
+}
+
+static int cli_initchansess(struct Channel *channel) {
+
+	cli_init_stdpipe_sess(channel);
 
 	if (cli_opts.wantpty) {
 		send_chansess_pty_req(channel);
@@ -362,12 +372,48 @@
 	}
 
 	return 0; /* Success */
+}
 
+#ifdef ENABLE_CLI_NETCAT
+
+void cli_send_netcat_request() {
+
+	const unsigned char* source_host = "127.0.0.1";
+	const int source_port = 22;
+
+	const struct ChanType cli_chan_netcat = {
+		0, /* sepfds */
+		"direct-tcpip",
+		cli_init_stdpipe_sess, /* inithandler */
+		NULL,
+		NULL,
+		cli_closechansess
+	};
+
+	cli_opts.wantpty = 0;
+
+	if (send_msg_channel_open_init(STDIN_FILENO, &cli_chan_netcat) 
+			== DROPBEAR_FAILURE) {
+		dropbear_exit("Couldn't open initial channel");
+	}
+
+	buf_putstring(ses.writepayload, cli_opts.netcat_host, 
+			strlen(cli_opts.netcat_host));
+	buf_putint(ses.writepayload, cli_opts.netcat_port);
+
+	/* originator ip - localhost is accurate enough */
+	buf_putstring(ses.writepayload, source_host, strlen(source_host));
+	buf_putint(ses.writepayload, source_port);
+
+	encrypt_packet();
+	TRACE(("leave cli_send_chansess_request"))
 }
+#endif
 
 void cli_send_chansess_request() {
 
 	TRACE(("enter cli_send_chansess_request"))
+
 	if (send_msg_channel_open_init(STDIN_FILENO, &clichansess) 
 			== DROPBEAR_FAILURE) {
 		dropbear_exit("Couldn't open initial channel");
@@ -378,3 +424,16 @@
 	TRACE(("leave cli_send_chansess_request"))
 
 }
+
+
+#if 0
+	while (cli_opts.localfwds != NULL) {
+		ret = cli_localtcp(cli_opts.localfwds->listenport,
+				cli_opts.localfwds->connectaddr,
+				cli_opts.localfwds->connectport);
+		if (ret == DROPBEAR_FAILURE) {
+			dropbear_log(LOG_WARNING, "Failed local port forward %d:%s:%d",
+					cli_opts.localfwds->listenport,
+					cli_opts.localfwds->connectaddr,
+					cli_opts.localfwds->connectport);
+#endif
--- a/cli-kex.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-kex.c	Thu Nov 06 13:16:55 2008 +0000
@@ -119,9 +119,17 @@
 	char response = 'z';
 
 	fp = sign_key_fingerprint(keyblob, keybloblen);
-	fprintf(stderr, "\nHost '%s' is not in the trusted hosts file.\n(fingerprint %s)\nDo you want to continue connecting? (y/n)\n", 
+	if (cli_opts.always_accept_key) {
+		fprintf(stderr, "\nHost '%s' key accepted unconditionally.\n(fingerprint %s)\n",
+				cli_opts.remotehost,
+				fp);
+		m_free(fp);
+		return;
+	}
+	fprintf(stderr, "\nHost '%s' is not in the trusted hosts file.\n(fingerprint %s)\nDo you want to continue connecting? (y/n) ", 
 			cli_opts.remotehost, 
 			fp);
+	m_free(fp);
 
 	tty = fopen(_PATH_TTY, "r");
 	if (tty) {
@@ -132,66 +140,90 @@
 	}
 
 	if (response == 'y') {
-		m_free(fp);
 		return;
 	}
 
 	dropbear_exit("Didn't validate host key");
 }
 
-static void checkhostkey(unsigned char* keyblob, unsigned int keybloblen) {
-
+static FILE* open_known_hosts_file(int * readonly)
+{
+	FILE * hostsfile = NULL;
 	char * filename = NULL;
-	FILE *hostsfile = NULL;
-	int readonly = 0;
-	struct passwd *pw = NULL;
-	unsigned int hostlen, algolen;
-	unsigned long len;
-	const char *algoname = NULL;
-	buffer * line = NULL;
-	int ret;
+	char * homedir = NULL;
 	
-	pw = getpwuid(getuid());
+	homedir = getenv("HOME");
 
-	if (pw == NULL) {
-		dropbear_exit("Failed to get homedir");
-	}
-
-	len = strlen(pw->pw_dir);
-	filename = m_malloc(len + 18); /* "/.ssh/known_hosts" and null-terminator*/
-
-	snprintf(filename, len+18, "%s/.ssh", pw->pw_dir);
-	/* Check that ~/.ssh exists - easiest way is just to mkdir */
-	if (mkdir(filename, S_IRWXU) != 0) {
-		if (errno != EEXIST) {
-			dropbear_log(LOG_INFO, "Warning: failed creating ~/.ssh: %s",
-					strerror(errno));
-			TRACE(("mkdir didn't work: %s", strerror(errno)))
-			ask_to_confirm(keyblob, keybloblen);
-			goto out; /* only get here on success */
+	if (!homedir) {
+		struct passwd * pw = NULL;
+		pw = getpwuid(getuid());
+		if (pw) {
+			homedir = pw->pw_dir;
 		}
 	}
 
-	snprintf(filename, len+18, "%s/.ssh/known_hosts", pw->pw_dir);
-	hostsfile = fopen(filename, "a+");
-	
-	if (hostsfile != NULL) {
-		fseek(hostsfile, 0, SEEK_SET);
-	} else {
-		/* We mightn't have been able to open it if it was read-only */
-		if (errno == EACCES || errno == EROFS) {
-				TRACE(("trying readonly: %s", strerror(errno)))
-				readonly = 1;
-				hostsfile = fopen(filename, "r");
+	if (homedir) {
+		unsigned int len;
+		len = strlen(homedir);
+		filename = m_malloc(len + 18); /* "/.ssh/known_hosts" and null-terminator*/
+
+		snprintf(filename, len+18, "%s/.ssh", homedir);
+		/* Check that ~/.ssh exists - easiest way is just to mkdir */
+		if (mkdir(filename, S_IRWXU) != 0) {
+			if (errno != EEXIST) {
+				dropbear_log(LOG_INFO, "Warning: failed creating %s/.ssh: %s",
+						homedir, strerror(errno));
+				TRACE(("mkdir didn't work: %s", strerror(errno)))
+				goto out;
+			}
+		}
+
+		snprintf(filename, len+18, "%s/.ssh/known_hosts", homedir);
+		hostsfile = fopen(filename, "a+");
+		
+		if (hostsfile != NULL) {
+			*readonly = 0;
+			fseek(hostsfile, 0, SEEK_SET);
+		} else {
+			/* We mightn't have been able to open it if it was read-only */
+			if (errno == EACCES || errno == EROFS) {
+					TRACE(("trying readonly: %s", strerror(errno)))
+					*readonly = 1;
+					hostsfile = fopen(filename, "r");
+			}
 		}
 	}
 
 	if (hostsfile == NULL) {
 		TRACE(("hostsfile didn't open: %s", strerror(errno)))
+		dropbear_log(LOG_WARNING, "Failed to open %s/.ssh/known_hosts",
+				homedir);
+		goto out;
+	}	
+
+out:
+	m_free(filename);
+	return hostsfile;
+}
+
+static void checkhostkey(unsigned char* keyblob, unsigned int keybloblen) {
+
+	FILE *hostsfile = NULL;
+	int readonly = 0;
+	unsigned int hostlen, algolen;
+	unsigned long len;
+	const char *algoname = NULL;
+	char * fingerprint = NULL;
+	buffer * line = NULL;
+	int ret;
+
+	hostsfile = open_known_hosts_file(&readonly);
+	if (!hostsfile)	{
 		ask_to_confirm(keyblob, keybloblen);
-		goto out; /* We only get here on success */
+		/* ask_to_confirm will exit upon failure */
+		return;
 	}
-
+	
 	line = buf_new(MAX_KNOWNHOSTS_LINE);
 	hostlen = strlen(cli_opts.remotehost);
 	algoname = signkey_name_from_type(ses.newkeys->algo_hostkey, &algolen);
@@ -225,7 +257,7 @@
 			continue;
 		}
 
-		if ( strncmp(buf_getptr(line, algolen), algoname, algolen) != 0) {
+		if (strncmp(buf_getptr(line, algolen), algoname, algolen) != 0) {
 			TRACE(("algo doesn't match"))
 			continue;
 		}
@@ -237,7 +269,8 @@
 		}
 
 		/* Now we're at the interesting hostkey */
-		ret = cmp_base64_key(keyblob, keybloblen, algoname, algolen, line);
+		ret = cmp_base64_key(keyblob, keybloblen, algoname, algolen,
+						line, &fingerprint);
 
 		if (ret == DROPBEAR_SUCCESS) {
 			/* Good matching key */
@@ -245,7 +278,15 @@
 			goto out;
 		}
 
-		/* The keys didn't match. eep. */
+		/* The keys didn't match. eep. Note that we're "leaking"
+		   the fingerprint strings here, but we're exiting anyway */
+		dropbear_exit("\n\nHost key mismatch for %s !\n"
+					"Fingerprint is %s\n"
+					"Expected %s\n"
+					"If you know that the host key is correct you can\nremove the bad entry from ~/.ssh/known_hosts", 
+					cli_opts.remotehost,
+					sign_key_fingerprint(keyblob, keybloblen),
+					fingerprint ? fingerprint : "UNKNOWN");
 	} while (1); /* keep going 'til something happens */
 
 	/* Key doesn't exist yet */
@@ -258,30 +299,31 @@
 		goto out;
 	}
 
-	/* put the new entry in the file */
-	fseek(hostsfile, 0, SEEK_END); /* In case it wasn't opened append */
-	buf_setpos(line, 0);
-	buf_setlen(line, 0);
-	buf_putbytes(line, ses.remotehost, hostlen);
-	buf_putbyte(line, ' ');
-	buf_putbytes(line, algoname, algolen);
-	buf_putbyte(line, ' ');
-	len = line->size - line->pos;
-	TRACE(("keybloblen %d, len %d", keybloblen, len))
-	/* The only failure with base64 is buffer_overflow, but buf_getwriteptr
-	 * will die horribly in the case anyway */
-	base64_encode(keyblob, keybloblen, buf_getwriteptr(line, len), &len);
-	buf_incrwritepos(line, len);
-	buf_putbyte(line, '\n');
-	buf_setpos(line, 0);
-	fwrite(buf_getptr(line, line->len), line->len, 1, hostsfile);
-	/* We ignore errors, since there's not much we can do about them */
+	if (!cli_opts.always_accept_key) {
+		/* put the new entry in the file */
+		fseek(hostsfile, 0, SEEK_END); /* In case it wasn't opened append */
+		buf_setpos(line, 0);
+		buf_setlen(line, 0);
+		buf_putbytes(line, ses.remotehost, hostlen);
+		buf_putbyte(line, ' ');
+		buf_putbytes(line, algoname, algolen);
+		buf_putbyte(line, ' ');
+		len = line->size - line->pos;
+		TRACE(("keybloblen %d, len %d", keybloblen, len))
+		/* The only failure with base64 is buffer_overflow, but buf_getwriteptr
+		 * will die horribly in the case anyway */
+		base64_encode(keyblob, keybloblen, buf_getwriteptr(line, len), &len);
+		buf_incrwritepos(line, len);
+		buf_putbyte(line, '\n');
+		buf_setpos(line, 0);
+		fwrite(buf_getptr(line, line->len), line->len, 1, hostsfile);
+		/* We ignore errors, since there's not much we can do about them */
+	}
 
 out:
 	if (hostsfile != NULL) {
 		fclose(hostsfile);
 	}
-	m_free(filename);
 	if (line != NULL) {
 		buf_free(line);
 	}
--- a/cli-main.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-main.c	Thu Nov 06 13:16:55 2008 +0000
@@ -32,6 +32,8 @@
 static void cli_dropbear_exit(int exitcode, const char* format, va_list param);
 static void cli_dropbear_log(int priority, const char* format, va_list param);
 
+static void cli_proxy_cmd(int *sock_in, int *sock_out);
+
 #if defined(DBMULTI_dbclient) || !defined(DROPBEAR_MULTI)
 #if defined(DBMULTI_dbclient) && defined(DROPBEAR_MULTI)
 int cli_main(int argc, char ** argv) {
@@ -39,7 +41,7 @@
 int main(int argc, char ** argv) {
 #endif
 
-	int sock;
+	int sock_in, sock_out;
 	char* error = NULL;
 	char* hostandport;
 	int len;
@@ -47,6 +49,8 @@
 	_dropbear_exit = cli_dropbear_exit;
 	_dropbear_log = cli_dropbear_log;
 
+	disallow_core();
+
 	cli_getopts(argc, argv);
 
 	TRACE(("user='%s' host='%s' port='%s'", cli_opts.username,
@@ -56,10 +60,18 @@
 		dropbear_exit("signal() error");
 	}
 
-	sock = connect_remote(cli_opts.remotehost, cli_opts.remoteport, 
-			0, &error);
+#ifdef ENABLE_CLI_PROXYCMD
+	if (cli_opts.proxycmd) {
+		cli_proxy_cmd(&sock_in, &sock_out);
+	} else
+#endif
+	{
+		int sock = connect_remote(cli_opts.remotehost, cli_opts.remoteport, 
+				0, &error);
+		sock_in = sock_out = sock;
+	}
 
-	if (sock < 0) {
+	if (sock_in < 0) {
 		dropbear_exit("%s", error);
 	}
 
@@ -70,7 +82,7 @@
 	snprintf(hostandport, len, "%s:%s", 
 			cli_opts.remotehost, cli_opts.remoteport);
 
-	cli_session(sock, hostandport);
+	cli_session(sock_in, sock_out, hostandport);
 
 	/* not reached */
 	return -1;
@@ -110,3 +122,25 @@
 	fprintf(stderr, "%s: %s\n", cli_opts.progname, printbuf);
 
 }
+
+static void exec_proxy_cmd(void *user_data_cmd) {
+	const char *cmd = user_data_cmd;
+	char *usershell;
+
+	usershell = m_strdup(get_user_shell());
+	run_shell_command(cmd, ses.maxfd, usershell);
+	dropbear_exit("Failed to run '%s'\n", cmd);
+}
+
+static void cli_proxy_cmd(int *sock_in, int *sock_out) {
+	int ret;
+
+	fill_passwd(cli_opts.own_user);
+
+	ret = spawn_command(exec_proxy_cmd, cli_opts.proxycmd,
+			sock_out, sock_in, NULL, NULL);
+	if (ret == DROPBEAR_FAILURE) {
+		dropbear_exit("Failed running proxy command");
+		*sock_in = *sock_out = -1;
+	}
+}
--- a/cli-runopts.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-runopts.c	Thu Nov 06 13:16:55 2008 +0000
@@ -33,23 +33,36 @@
 cli_runopts cli_opts; /* GLOBAL */
 
 static void printhelp();
-static void parsehostname(char* userhostarg);
+static void parse_hostname(const char* orighostarg);
+static void parse_multihop_hostname(const char* orighostarg, const char* argv0);
+static void fill_own_user();
 #ifdef ENABLE_CLI_PUBKEY_AUTH
 static void loadidentityfile(const char* filename);
 #endif
 #ifdef ENABLE_CLI_ANYTCPFWD
-static void addforward(char* str, struct TCPFwdList** fwdlist);
+static void addforward(const char* str, struct TCPFwdList** fwdlist);
+#endif
+#ifdef ENABLE_CLI_NETCAT
+static void add_netcat(const char *str);
 #endif
 
 static void printhelp() {
 
 	fprintf(stderr, "Dropbear client v%s\n"
-					"Usage: %s [options] [[email protected]]host\n"
+#ifdef ENABLE_CLI_MULTIHOP
+					"Usage: %s [options] [[email protected]]host[/port][,[[email protected]]host/port],...] [command]\n"
+#else
+					"Usage: %s [options] [[email protected]]host[/port] [command]\n"
+#endif
 					"Options are:\n"
 					"-p <remoteport>\n"
 					"-l <username>\n"
 					"-t    Allocate a pty\n"
 					"-T    Don't allocate a pty\n"
+					"-N    Don't run a remote command\n"
+					"-f    Run in background after auth\n"
+					"-y    Always accept remote host key if unknown\n"
+					"-s    Request a subsystem (use for sftp)\n"
 #ifdef ENABLE_CLI_PUBKEY_AUTH
 					"-i <identityfile>   (multiple allowed)\n"
 #endif
@@ -60,10 +73,20 @@
 #ifdef ENABLE_CLI_REMOTETCPFWD
 					"-R <listenport:remotehost:remoteport> Remote port forwarding\n"
 #endif
+					"-W <receive_window_buffer> (default %d, larger may be faster, max 1MB)\n"
+					"-K <keepalive>  (0 is never, default %d)\n"
+#ifdef ENABLE_CLI_NETCAT
+					"-B <endhost:endport> Netcat-alike forwarding\n"
+#endif				
+#ifdef ENABLE_CLI_PROXYCMD
+					"-J <proxy_program> Use program pipe rather than TCP connection\n"
+#endif
 #ifdef DEBUG_TRACE
-					"-v    verbose\n"
+					"-v    verbose (compiled with DEBUG_TRACE)\n"
 #endif
-					,DROPBEAR_VERSION, cli_opts.progname);
+					,DROPBEAR_VERSION, cli_opts.progname,
+					DEFAULT_RECV_WINDOW, DEFAULT_KEEPALIVE);
+					
 }
 
 void cli_getopts(int argc, char ** argv) {
@@ -80,15 +103,25 @@
 #ifdef ENABLE_CLI_REMOTETCPFWD
 	int nextisremote = 0;
 #endif
+#ifdef ENABLE_CLI_NETCAT
+	int nextisnetcat = 0;
+#endif
 	char* dummy = NULL; /* Not used for anything real */
 
+	char* recv_window_arg = NULL;
+	char* keepalive_arg = NULL;
+
 	/* see printhelp() for options */
 	cli_opts.progname = argv[0];
 	cli_opts.remotehost = NULL;
 	cli_opts.remoteport = NULL;
 	cli_opts.username = NULL;
 	cli_opts.cmd = NULL;
+	cli_opts.no_cmd = 0;
+	cli_opts.backgrounded = 0;
 	cli_opts.wantpty = 9; /* 9 means "it hasn't been touched", gets set later */
+	cli_opts.always_accept_key = 0;
+	cli_opts.is_subsystem = 0;
 #ifdef ENABLE_CLI_PUBKEY_AUTH
 	cli_opts.privkeys = NULL;
 #endif
@@ -99,10 +132,16 @@
 #ifdef ENABLE_CLI_REMOTETCPFWD
 	cli_opts.remotefwds = NULL;
 #endif
+#ifdef ENABLE_CLI_PROXYCMD
+	cli_opts.proxycmd = NULL;
+#endif
 	/* not yet
 	opts.ipv4 = 1;
 	opts.ipv6 = 1;
 	*/
+	opts.recv_window = DEFAULT_RECV_WINDOW;
+
+	fill_own_user();
 
 	/* Iterate all the arguments */
 	for (i = 1; i < (unsigned int)argc; i++) {
@@ -130,6 +169,14 @@
 			continue;
 		}
 #endif
+#ifdef ENABLE_CLI_NETCAT
+		if (nextisnetcat) {
+			TRACE(("nextisnetcat true"))
+			add_netcat(argv[i]);
+			nextisnetcat = 0;
+			continue;
+		}
+#endif
 		if (next) {
 			/* The previous flag set a value to assign */
 			*next = argv[i];
@@ -144,6 +191,9 @@
 			/* A flag *waves* */
 
 			switch (argv[i][1]) {
+				case 'y': /* always accept the remote hostkey */
+					cli_opts.always_accept_key = 1;
+					break;
 				case 'p': /* remoteport */
 					next = &cli_opts.remoteport;
 					break;
@@ -163,6 +213,15 @@
 				case 'T': /* don't want a pty */
 					cli_opts.wantpty = 0;
 					break;
+				case 'N':
+					cli_opts.no_cmd = 1;
+					break;
+				case 'f':
+					cli_opts.backgrounded = 1;
+					break;
+				case 's':
+					cli_opts.is_subsystem = 1;
+					break;
 #ifdef ENABLE_CLI_LOCALTCPFWD
 				case 'L':
 					nextislocal = 1;
@@ -176,6 +235,16 @@
 					nextisremote = 1;
 					break;
 #endif
+#ifdef ENABLE_CLI_NETCAT
+				case 'B':
+					nextisnetcat = 1;
+					break;
+#endif
+#ifdef ENABLE_CLI_PROXYCMD
+				case 'J':
+					next = &cli_opts.proxycmd;
+					break;
+#endif
 				case 'l':
 					next = &cli_opts.username;
 					break;
@@ -183,6 +252,15 @@
 					printhelp();
 					exit(EXIT_SUCCESS);
 					break;
+				case 'u':
+					/* backwards compatibility with old urandom option */
+					break;
+				case 'W':
+					next = &recv_window_arg;
+					break;
+				case 'K':
+					next = &keepalive_arg;
+					break;
 #ifdef DEBUG_TRACE
 				case 'v':
 					debug_trace = 1;
@@ -222,9 +300,11 @@
 			/* Either the hostname or commands */
 
 			if (cli_opts.remotehost == NULL) {
-
-				parsehostname(argv[i]);
-
+#ifdef ENABLE_CLI_MULTIHOP
+				parse_multihop_hostname(argv[i], argv[0]);
+#else
+				parse_hostname(argv[i]);
+#endif
 			} else {
 
 				/* this is part of the commands to send - after this we
@@ -251,6 +331,8 @@
 		}
 	}
 
+	/* And now a few sanity checks and setup */
+
 	if (cli_opts.remotehost == NULL) {
 		printhelp();
 		exit(EXIT_FAILURE);
@@ -269,6 +351,30 @@
 			cli_opts.wantpty = 0;
 		}
 	}
+
+	if (cli_opts.backgrounded && cli_opts.cmd == NULL
+			&& cli_opts.no_cmd == 0) {
+		dropbear_exit("command required for -f");
+	}
+	
+	if (recv_window_arg) {
+		opts.recv_window = atol(recv_window_arg);
+		if (opts.recv_window == 0 || opts.recv_window > MAX_RECV_WINDOW) {
+			dropbear_exit("Bad recv window '%s'", recv_window_arg);
+		}
+	}
+	if (keepalive_arg) {
+		if (m_str_to_uint(keepalive_arg, &opts.keepalive_secs) == DROPBEAR_FAILURE) {
+			dropbear_exit("Bad keepalive '%s'", keepalive_arg);
+		}
+	}
+
+#ifdef ENABLE_CLI_NETCAT
+	if (cli_opts.cmd && cli_opts.netcat_host) {
+		dropbear_log(LOG_INFO, "Ignoring command '%s' in netcat mode", cli_opts.cmd);
+	}
+#endif
+	
 }
 
 #ifdef ENABLE_CLI_PUBKEY_AUTH
@@ -296,16 +402,77 @@
 }
 #endif
 
+#ifdef ENABLE_CLI_MULTIHOP
 
-/* Parses a [[email protected]]hostname argument. userhostarg is the argv[i] corresponding
- * - note that it will be modified */
-static void parsehostname(char* orighostarg) {
+/* Sets up 'onion-forwarding' connections. This will spawn
+ * a separate dbclient process for each hop.
+ * As an example, if the cmdline is
+ *   dbclient wrt,madako,canyons
+ * then we want to run:
+ *   dbclient -J "dbclient -B canyons:22 wrt,madako" canyons
+ * and then the inner dbclient will recursively run:
+ *   dbclient -J "dbclient -B madako:22 wrt" madako
+ * etc for as many hosts as we want.
+ *
+ * Ports for hosts can be specified as host/port.
+ */
+static void parse_multihop_hostname(const char* orighostarg, const char* argv0) {
+	char *userhostarg = NULL;
+	char *last_hop = NULL;;
+	char *remainder = NULL;
+
+	/* both scp and rsync parse a [email protected] argument
+	 * and turn it into "-l user host". This breaks
+	 * for our multihop syntax, so we suture it back together.
+	 * This will break usernames that have both '@' and ',' in them,
+	 * though that should be fairly uncommon. */
+	if (cli_opts.username 
+			&& strchr(cli_opts.username, ',') 
+			&& strchr(cli_opts.username, '@')) {
+		unsigned int len = strlen(orighostarg) + strlen(cli_opts.username) + 2;
+		userhostarg = m_malloc(len);
+		snprintf(userhostarg, len, "%[email protected]%s", cli_opts.username, orighostarg);
+	} else {
+		userhostarg = m_strdup(orighostarg);
+	}
 
-	uid_t uid;
-	struct passwd *pw = NULL; 
+	last_hop = strrchr(userhostarg, ',');
+	if (last_hop) {
+		if (last_hop == userhostarg) {
+			dropbear_exit("Bad multi-hop hostnames");
+		}
+		*last_hop = '\0';
+		last_hop++;
+		remainder = userhostarg;
+		userhostarg = last_hop;
+	}
+
+	parse_hostname(userhostarg);
+
+	if (last_hop) {
+		/* Set up the proxycmd */
+		unsigned int cmd_len = 0;
+		if (cli_opts.proxycmd) {
+			dropbear_exit("-J can't be used with multihop mode");
+		}
+		if (cli_opts.remoteport == NULL) {
+			cli_opts.remoteport = "22";
+		}
+		cmd_len = strlen(remainder) 
+			+ strlen(cli_opts.remotehost) + strlen(cli_opts.remoteport)
+			+ strlen(argv0) + 30;
+		cli_opts.proxycmd = m_malloc(cmd_len);
+		snprintf(cli_opts.proxycmd, cmd_len, "%s -B %s:%s %s", 
+				argv0, cli_opts.remotehost, cli_opts.remoteport, remainder);
+	}
+}
+#endif /* !ENABLE_CLI_MULTIHOP */
+
+/* Parses a [[email protected]]hostname[/port] argument. */
+static void parse_hostname(const char* orighostarg) {
 	char *userhostarg = NULL;
+	char *port = NULL;
 
-	/* We probably don't want to be editing argvs */
 	userhostarg = m_strdup(orighostarg);
 
 	cli_opts.remotehost = strchr(userhostarg, '@');
@@ -320,14 +487,13 @@
 	}
 
 	if (cli_opts.username == NULL) {
-		uid = getuid();
-		
-		pw = getpwuid(uid);
-		if (pw == NULL || pw->pw_name == NULL) {
-			dropbear_exit("Unknown own user");
-		}
+		cli_opts.username = m_strdup(cli_opts.own_user);
+	}
 
-		cli_opts.username = m_strdup(pw->pw_name);
+	port = strchr(cli_opts.remotehost, '/');
+	if (port) {
+		*port = '\0';
+		cli_opts.remoteport = port+1;
 	}
 
 	if (cli_opts.remotehost[0] == '\0') {
@@ -335,10 +501,61 @@
 	}
 }
 
+#ifdef ENABLE_CLI_NETCAT
+static void add_netcat(const char* origstr) {
+	char *portstr = NULL;
+	
+	char * str = m_strdup(origstr);
+	
+	portstr = strchr(str, ':');
+	if (portstr == NULL) {
+		TRACE(("No netcat port"))
+		goto fail;
+	}
+	*portstr = '\0';
+	portstr++;
+	
+	if (strchr(portstr, ':')) {
+		TRACE(("Multiple netcat colons"))
+		goto fail;
+	}
+	
+	if (m_str_to_uint(portstr, &cli_opts.netcat_port) == DROPBEAR_FAILURE) {
+		TRACE(("bad netcat port"))
+		goto fail;
+	}
+	
+	if (cli_opts.netcat_port > 65535) {
+		TRACE(("too large netcat port"))
+		goto fail;
+	}
+	
+	cli_opts.netcat_host = str;
+	return;
+	
+fail:
+	dropbear_exit("Bad netcat endpoint '%s'", origstr);
+}
+#endif
+
+static void fill_own_user() {
+	uid_t uid;
+	struct passwd *pw = NULL; 
+
+	uid = getuid();
+
+	pw = getpwuid(uid);
+	if (pw == NULL || pw->pw_name == NULL) {
+		dropbear_exit("Unknown own user");
+	}
+
+	cli_opts.own_user = m_strdup(pw->pw_name);
+}
+
 #ifdef ENABLE_CLI_ANYTCPFWD
 /* Turn a "listenport:remoteaddr:remoteport" string into into a forwarding
  * set, and add it to the forwarding list */
-static void addforward(char* origstr, struct TCPFwdList** fwdlist) {
+static void addforward(const char* origstr, struct TCPFwdList** fwdlist) {
 
 	char * listenport = NULL;
 	char * connectport = NULL;
@@ -348,7 +565,8 @@
 
 	TRACE(("enter addforward"))
 
-	/* We probably don't want to be editing argvs */
+	/* We need to split the original argument up. This var
+	   is never free()d. */ 
 	str = m_strdup(origstr);
 
 	listenport = str;
@@ -358,8 +576,7 @@
 		TRACE(("connectaddr == NULL"))
 		goto fail;
 	}
-
-	connectaddr[0] = '\0';
+	*connectaddr = '\0';
 	connectaddr++;
 
 	connectport = strchr(connectaddr, ':');
@@ -367,23 +584,20 @@
 		TRACE(("connectport == NULL"))
 		goto fail;
 	}
-
-	connectport[0] = '\0';
+	*connectport = '\0';
 	connectport++;
 
 	newfwd = (struct TCPFwdList*)m_malloc(sizeof(struct TCPFwdList));
 
 	/* Now we check the ports - note that the port ints are unsigned,
 	 * the check later only checks for >= MAX_PORT */
-	newfwd->listenport = strtol(listenport, NULL, 10);
-	if (errno != 0) {
-		TRACE(("bad listenport strtol"))
+	if (m_str_to_uint(listenport, &newfwd->listenport) == DROPBEAR_FAILURE) {
+		TRACE(("bad listenport strtoul"))
 		goto fail;
 	}
 
-	newfwd->connectport = strtol(connectport, NULL, 10);
-	if (errno != 0) {
-		TRACE(("bad connectport strtol"))
+	if (m_str_to_uint(connectport, &newfwd->connectport) == DROPBEAR_FAILURE) {
+		TRACE(("bad connectport strtoul"))
 		goto fail;
 	}
 
@@ -399,6 +613,7 @@
 		goto badport;
 	}
 
+	newfwd->have_reply = 0;
 	newfwd->next = *fwdlist;
 	*fwdlist = newfwd;
 
--- a/cli-service.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-service.c	Thu Nov 06 13:16:55 2008 +0000
@@ -82,6 +82,4 @@
 	}
 
 	dropbear_exit("unrecognised service accept");
-	/* m_free(servicename); not reached */
-
 }
--- a/cli-session.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-session.c	Thu Nov 06 13:16:55 2008 +0000
@@ -64,6 +64,10 @@
 	{SSH_MSG_CHANNEL_OPEN_FAILURE, recv_msg_channel_open_failure},
 	{SSH_MSG_USERAUTH_BANNER, recv_msg_userauth_banner}, /* client */
 	{SSH_MSG_USERAUTH_SPECIFIC_60, recv_msg_userauth_specific_60}, /* client */
+#ifdef  ENABLE_CLI_REMOTETCPFWD
+	{SSH_MSG_REQUEST_SUCCESS, cli_recv_msg_request_success}, /* client */
+	{SSH_MSG_REQUEST_FAILURE, cli_recv_msg_request_failure}, /* client */
+#endif
 	{0, 0} /* End */
 };
 
@@ -74,13 +78,13 @@
 	NULL /* Null termination */
 };
 
-void cli_session(int sock, char* remotehost) {
+void cli_session(int sock_in, int sock_out, char* remotehost) {
 
 	seedrandom();
 
 	crypto_init();
 
-	common_session_init(sock, remotehost);
+	common_session_init(sock_in, sock_out, remotehost);
 
 	chaninitialise(cli_chantypes);
 
@@ -197,34 +201,45 @@
 			TRACE(("leave cli_sessionloop: cli_auth_try"))
 			return;
 
-			/*
 		case USERAUTH_SUCCESS_RCVD:
-			send_msg_service_request(SSH_SERVICE_CONNECTION);
-			cli_ses.state = SERVICE_CONN_REQ_SENT;
-			TRACE(("leave cli_sessionloop: sent ssh-connection service req"))
-			return;
 
-		case SERVICE_CONN_ACCEPT_RCVD:
-			cli_send_chansess_request();
-			TRACE(("leave cli_sessionloop: cli_send_chansess_request"))
-			cli_ses.state = SESSION_RUNNING;
-			return;
-			*/
-
-		case USERAUTH_SUCCESS_RCVD:
+			if (cli_opts.backgrounded) {
+				int devnull;
+				/* keeping stdin open steals input from the terminal and
+				   is confusing, though stdout/stderr could be useful. */
+				devnull = open(_PATH_DEVNULL, O_RDONLY);
+				if (devnull < 0) {
+					dropbear_exit("opening /dev/null: %d %s",
+							errno, strerror(errno));
+				}
+				dup2(devnull, STDIN_FILENO);
+				if (daemon(0, 1) < 0) {
+					dropbear_exit("Backgrounding failed: %d %s", 
+							errno, strerror(errno));
+				}
+			}
+			
 #ifdef ENABLE_CLI_LOCALTCPFWD
 			setup_localtcp();
 #endif
 #ifdef ENABLE_CLI_REMOTETCPFWD
 			setup_remotetcp();
 #endif
-			cli_send_chansess_request();
-			TRACE(("leave cli_sessionloop: cli_send_chansess_request"))
+
+#ifdef ENABLE_CLI_NETCAT
+			if (cli_opts.netcat_host) {
+				cli_send_netcat_request();
+			} else 
+#endif
+				if (!cli_opts.no_cmd) {
+				cli_send_chansess_request();
+			}
+			TRACE(("leave cli_sessionloop: running"))
 			cli_ses.state = SESSION_RUNNING;
 			return;
 
 		case SESSION_RUNNING:
-			if (ses.chancount < 1) {
+			if (ses.chancount < 1 && !cli_opts.no_cmd) {
 				cli_finished();
 			}
 
@@ -275,8 +290,10 @@
 
 	/* XXX TODO perhaps print a friendlier message if we get this but have
 	 * already sent/received disconnect message(s) ??? */
-	close(ses.sock);
-	ses.sock = -1;
+	m_close(ses.sock_in);
+	m_close(ses.sock_out);
+	ses.sock_in = -1;
+	ses.sock_out = -1;
 	dropbear_exit("remote closed the connection");
 }
 
--- a/cli-tcpfwd.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/cli-tcpfwd.c	Thu Nov 06 13:16:55 2008 +0000
@@ -128,7 +128,7 @@
 	CHECKCLEARTOWRITE();
 	buf_putbyte(ses.writepayload, SSH_MSG_GLOBAL_REQUEST);
 	buf_putstring(ses.writepayload, "tcpip-forward", 13);
-	buf_putbyte(ses.writepayload, 0);
+	buf_putbyte(ses.writepayload, 1); /* want_reply */
 	if (opts.listen_fwd_all) {
 		listenspec = "";
 	} else {
@@ -143,6 +143,42 @@
 	TRACE(("leave send_msg_global_request_remotetcp"))
 }
 
+/* The only global success/failure messages are for remotetcp.
+ * Since there isn't any identifier in these messages, we have to rely on them
+ * being in the same order as we sent the requests. This is the ordering
+ * of the cli_opts.remotefwds list */
+void cli_recv_msg_request_success() {
+
+	/* Nothing in the packet. We just mark off that we have received the reply,
+	 * so that we can report failure for later ones. */
+	struct TCPFwdList * iter = NULL;
+
+	iter = cli_opts.remotefwds;
+	while (iter != NULL) {
+		if (!iter->have_reply)
+		{
+			iter->have_reply = 1;
+			return;
+		}
+		iter = iter->next;
+	}
+}
+
+void cli_recv_msg_request_failure() {
+	struct TCPFwdList * iter = NULL;
+
+	iter = cli_opts.remotefwds;
+	while (iter != NULL) {
+		if (!iter->have_reply)
+		{
+			iter->have_reply = 1;
+			dropbear_log(LOG_WARNING, "Remote TCP forward request failed (port %d -> %s:%d)", iter->listenport, iter->connectaddr, iter->connectport);
+			return;
+		}
+		iter = iter->next;
+	}
+}
+
 void setup_remotetcp() {
 
 	struct TCPFwdList * iter = NULL;
--- a/common-algo.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/common-algo.c	Thu Nov 06 13:16:55 2008 +0000
@@ -29,30 +29,44 @@
 /* This file (algo.c) organises the ciphers which can be used, and is used to
  * decide which ciphers/hashes/compression/signing to use during key exchange*/
 
+static int void_cipher(const unsigned char* in, unsigned char* out,
+		unsigned long len, void *cipher_state) {
+	memcpy(out, in, len);
+	return CRYPT_OK;
+}
+
+static int void_start(int cipher, const unsigned char *IV, 
+			const unsigned char *key, 
+			int keylen, int num_rounds, void *cipher_state) {
+	return CRYPT_OK;
+}
+
 /* Mappings for ciphers, parameters are
    {&cipher_desc, keysize, blocksize} */
+/* NOTE: if keysize > 2*SHA1_HASH_SIZE, code such as hashkeys()
+   needs revisiting */
 
-#ifdef DROPBEAR_AES256_CBC
+#ifdef DROPBEAR_AES256
 static const struct dropbear_cipher dropbear_aes256 = 
 	{&aes_desc, 32, 16};
 #endif
-#ifdef DROPBEAR_AES128_CBC
+#ifdef DROPBEAR_AES128
 static const struct dropbear_cipher dropbear_aes128 = 
 	{&aes_desc, 16, 16};
 #endif
-#ifdef DROPBEAR_BLOWFISH_CBC
+#ifdef DROPBEAR_BLOWFISH
 static const struct dropbear_cipher dropbear_blowfish = 
 	{&blowfish_desc, 16, 8};
 #endif
-#ifdef DROPBEAR_TWOFISH256_CBC
+#ifdef DROPBEAR_TWOFISH256
 static const struct dropbear_cipher dropbear_twofish256 = 
 	{&twofish_desc, 32, 16};
 #endif
-#ifdef DROPBEAR_TWOFISH128_CBC
+#ifdef DROPBEAR_TWOFISH128
 static const struct dropbear_cipher dropbear_twofish128 = 
 	{&twofish_desc, 16, 16};
 #endif
-#ifdef DROPBEAR_3DES_CBC
+#ifdef DROPBEAR_3DES
 static const struct dropbear_cipher dropbear_3des = 
 	{&des3_desc, 24, 8};
 #endif
@@ -61,6 +75,24 @@
 const struct dropbear_cipher dropbear_nocipher =
 	{NULL, 16, 8}; 
 
+/* A few void* s are required to silence warnings
+ * about the symmetric_CBC vs symmetric_CTR cipher_state pointer */
+const struct dropbear_cipher_mode dropbear_mode_cbc =
+	{(void*)cbc_start, (void*)cbc_encrypt, (void*)cbc_decrypt};
+const struct dropbear_cipher_mode dropbear_mode_none =
+	{void_start, void_cipher, void_cipher};
+#ifdef DROPBEAR_ENABLE_CTR_MODE
+/* a wrapper to make ctr_start and cbc_start look the same */
+static int dropbear_big_endian_ctr_start(int cipher, 
+		const unsigned char *IV, 
+		const unsigned char *key, int keylen, 
+		int num_rounds, symmetric_CTR *ctr) {
+	return ctr_start(cipher, IV, key, keylen, num_rounds, CTR_COUNTER_BIG_ENDIAN, ctr);
+}
+const struct dropbear_cipher_mode dropbear_mode_ctr =
+	{(void*)dropbear_big_endian_ctr_start, (void*)ctr_encrypt, (void*)ctr_decrypt};
+#endif
+
 /* Mapping of ssh hashes to libtomcrypt hashes, including keysize etc.
    {&hash_desc, keysize, hashsize} */
 
@@ -81,27 +113,42 @@
 	{NULL, 16, 0}; /* used initially */
 	
 
-/* The following map ssh names to internal values */
+/* The following map ssh names to internal values.
+ * The ordering here is important for the client - the first mode
+ * that is also supported by the server will get used. */
 
 algo_type sshciphers[] = {
-#ifdef DROPBEAR_AES128_CBC
-	{"aes128-cbc", 0, (void*)&dropbear_aes128, 1},
+#ifdef DROPBEAR_ENABLE_CTR_MODE
+#ifdef DROPBEAR_AES128
+	{"aes128-ctr", 0, &dropbear_aes128, 1, &dropbear_mode_ctr},
+#endif
+#ifdef DROPBEAR_3DES
+	{"3des-ctr", 0, &dropbear_3des, 1, &dropbear_mode_ctr},
 #endif
-#ifdef DROPBEAR_3DES_CBC
-	{"3des-cbc", 0, (void*)&dropbear_3des, 1},
+#ifdef DROPBEAR_AES256
+	{"aes256-ctr", 0, &dropbear_aes256, 1, &dropbear_mode_ctr},
 #endif
-#ifdef DROPBEAR_AES256_CBC
-	{"aes256-cbc", 0, (void*)&dropbear_aes256, 1},
+#endif /* DROPBEAR_ENABLE_CTR_MODE */
+
+/* CBC modes are always enabled */
+#ifdef DROPBEAR_AES128
+	{"aes128-cbc", 0, &dropbear_aes128, 1, &dropbear_mode_cbc},
 #endif
-#ifdef DROPBEAR_TWOFISH256_CBC
-	{"twofish256-cbc", 0, (void*)&dropbear_twofish256, 1},
-	{"twofish-cbc", 0, (void*)&dropbear_twofish256, 1},
+#ifdef DROPBEAR_3DES
+	{"3des-cbc", 0, &dropbear_3des, 1, &dropbear_mode_cbc},
+#endif
+#ifdef DROPBEAR_AES256
+	{"aes256-cbc", 0, &dropbear_aes256, 1, &dropbear_mode_cbc},
 #endif
-#ifdef DROPBEAR_TWOFISH128_CBC
-	{"twofish128-cbc", 0, (void*)&dropbear_twofish128, 1},
+#ifdef DROPBEAR_TWOFISH256
+	{"twofish256-cbc", 0, &dropbear_twofish256, 1, &dropbear_mode_cbc},
+	{"twofish-cbc", 0, &dropbear_twofish256, 1, &dropbear_mode_cbc},
 #endif
-#ifdef DROPBEAR_BLOWFISH_CBC
-	{"blowfish-cbc", 0, (void*)&dropbear_blowfish, 1},
+#ifdef DROPBEAR_TWOFISH128
+	{"twofish128-cbc", 0, &dropbear_twofish128, 1, &dropbear_mode_cbc},
+#endif
+#ifdef DROPBEAR_BLOWFISH
+	{"blowfish-cbc", 0, &dropbear_blowfish, 1, &dropbear_mode_cbc},
 #endif
 #ifdef DROPBEAR_NONE_CIPHER
 	{"none", 0, (void*)&dropbear_nocipher, 1},
@@ -111,10 +158,10 @@
 
 algo_type sshhashes[] = {
 #ifdef DROPBEAR_SHA1_96_HMAC
-	{"hmac-sha1-96", 0, (void*)&dropbear_sha1_96, 1},
+	{"hmac-sha1-96", 0, &dropbear_sha1_96, 1, NULL},
 #endif
 #ifdef DROPBEAR_SHA1_HMAC
-	{"hmac-sha1", 0, (void*)&dropbear_sha1, 1},
+	{"hmac-sha1", 0, &dropbear_sha1, 1, NULL},
 #endif
 #ifdef DROPBEAR_MD5_HMAC
 	{"hmac-md5", 0, (void*)&dropbear_md5, 1},
@@ -127,25 +174,26 @@
 
 algo_type sshcompress[] = {
 #ifndef DISABLE_ZLIB
-	{"zlib", DROPBEAR_COMP_ZLIB, NULL, 1},
+	{"zlib", DROPBEAR_COMP_ZLIB, NULL, 1, NULL},
+	{"[email protected]", DROPBEAR_COMP_ZLIB_DELAY, NULL, 1, NULL},
 #endif
-	{"none", DROPBEAR_COMP_NONE, NULL, 1},
-	{NULL, 0, NULL, 0}
+	{"none", DROPBEAR_COMP_NONE, NULL, 1, NULL},
+	{NULL, 0, NULL, 0, NULL}
 };
 
 algo_type sshhostkey[] = {
 #ifdef DROPBEAR_RSA
-	{"ssh-rsa", DROPBEAR_SIGNKEY_RSA, NULL, 1},
+	{"ssh-rsa", DROPBEAR_SIGNKEY_RSA, NULL, 1, NULL},
 #endif
 #ifdef DROPBEAR_DSS
-	{"ssh-dss", DROPBEAR_SIGNKEY_DSS, NULL, 1},
+	{"ssh-dss", DROPBEAR_SIGNKEY_DSS, NULL, 1, NULL},
 #endif
-	{NULL, 0, NULL, 0}
+	{NULL, 0, NULL, 0, NULL}
 };
 
 algo_type sshkex[] = {
-	{"diffie-hellman-group1-sha1", DROPBEAR_KEX_DH_GROUP1, NULL, 1},
-	{NULL, 0, NULL, 0}
+	{"diffie-hellman-group1-sha1", DROPBEAR_KEX_DH_GROUP1, NULL, 1, NULL},
+	{NULL, 0, NULL, 0, NULL}
 };
 
 
@@ -154,16 +202,16 @@
 void crypto_init() {
 
 	const struct ltc_cipher_descriptor *regciphers[] = {
-#ifdef DROPBEAR_AES_CBC
+#ifdef DROPBEAR_AES
 		&aes_desc,
 #endif
-#ifdef DROPBEAR_BLOWFISH_CBC
+#ifdef DROPBEAR_BLOWFISH
 		&blowfish_desc,
 #endif
-#ifdef DROPBEAR_TWOFISH_CBC
+#ifdef DROPBEAR_TWOFISH
 		&twofish_desc,
 #endif
-#ifdef DROPBEAR_3DES_CBC
+#ifdef DROPBEAR_3DES
 		&des3_desc,
 #endif
 		NULL
@@ -219,7 +267,7 @@
 	unsigned int donefirst = 0;
 	buffer *algolist = NULL;
 
-	algolist = buf_new(100);
+	algolist = buf_new(160);
 	for (i = 0; localalgos[i].name != NULL; i++) {
 		if (localalgos[i].usable) {
 			if (donefirst)
--- a/common-channel.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/common-channel.c	Thu Nov 06 13:16:55 2008 +0000
@@ -34,6 +34,7 @@
 #include "channel.h"
 #include "ssh.h"
 #include "listener.h"
+#include "runopts.h"
 
 static void send_msg_channel_open_failure(unsigned int remotechan, int reason,
 		const unsigned char *text, const unsigned char *lang);
@@ -43,22 +44,22 @@
 static void writechannel(struct Channel* channel, int fd, circbuffer *cbuf);
 static void send_msg_channel_window_adjust(struct Channel *channel, 
 		unsigned int incr);
-static void send_msg_channel_data(struct Channel *channel, int isextended,
-		unsigned int exttype);
+static void send_msg_channel_data(struct Channel *channel, int isextended);
 static void send_msg_channel_eof(struct Channel *channel);
 static void send_msg_channel_close(struct Channel *channel);
-static void removechannel(struct Channel *channel);
-static void deletechannel(struct Channel *channel);
-static void checkinitdone(struct Channel *channel);
-static void checkclose(struct Channel *channel);
-
-static void closewritefd(struct Channel * channel);
-static void closereadfd(struct Channel * channel, int fd);
-static void closechanfd(struct Channel *channel, int fd, int how);
+static void remove_channel(struct Channel *channel);
+static void delete_channel(struct Channel *channel);
+static void check_in_progress(struct Channel *channel);
+static unsigned int write_pending(struct Channel * channel);
+static void check_close(struct Channel *channel);
+static void close_chan_fd(struct Channel *channel, int fd, int how);
 
 #define FD_UNINIT (-2)
 #define FD_CLOSED (-1)
 
+#define ERRFD_IS_READ(channel) ((channel)->extrabuf == NULL)
+#define ERRFD_IS_WRITE(channel) (!ERRFD_IS_READ(channel))
+
 /* Initialise all the channels */
 void chaninitialise(const struct ChanType *chantypes[]) {
 
@@ -85,7 +86,7 @@
 	for (i = 0; i < ses.chansize; i++) {
 		if (ses.channels[i] != NULL) {
 			TRACE(("channel %d closing", i))
-			removechannel(ses.channels[i]);
+			remove_channel(ses.channels[i]);
 		}
 	}
 	m_free(ses.channels);
@@ -135,8 +136,8 @@
 	newchan = (struct Channel*)m_malloc(sizeof(struct Channel));
 	newchan->type = type;
 	newchan->index = i;
-	newchan->sentclosed = newchan->recvclosed = 0;
-	newchan->senteof = newchan->recveof = 0;
+	newchan->sent_close = newchan->recv_close = 0;
+	newchan->sent_eof = newchan->recv_eof = 0;
 
 	newchan->remotechan = remotechan;
 	newchan->transwindow = transwindow;
@@ -148,12 +149,13 @@
 	newchan->errfd = FD_CLOSED; /* this isn't always set to start with */
 	newchan->initconn = 0;
 	newchan->await_open = 0;
+	newchan->flushing = 0;
 
-	newchan->writebuf = cbuf_new(RECV_MAXWINDOW);
+	newchan->writebuf = cbuf_new(opts.recv_window);
 	newchan->extrabuf = NULL; /* The user code can set it up */
-	newchan->recvwindow = RECV_MAXWINDOW;
+	newchan->recvwindow = opts.recv_window;
 	newchan->recvdonelen = 0;
-	newchan->recvmaxpacket = RECV_MAXPACKET;
+	newchan->recvmaxpacket = RECV_MAX_PAYLOAD_LEN;
 
 	ses.channels[i] = newchan;
 	ses.chancount++;
@@ -164,25 +166,35 @@
 }
 
 /* Returns the channel structure corresponding to the channel in the current
- * data packet (ses.payload must be positioned appropriately) */
-struct Channel* getchannel() {
+ * data packet (ses.payload must be positioned appropriately).
+ * A valid channel is always returns, it will fail fatally with an unknown
+ * channel */
+static struct Channel* getchannel_msg(const char* kind) {
 
 	unsigned int chan;
 
 	chan = buf_getint(ses.payload);
 	if (chan >= ses.chansize || ses.channels[chan] == NULL) {
-		return NULL;
+		if (kind) {
+			dropbear_exit("%s for unknown channel %d", kind, chan);
+		} else {
+			dropbear_exit("Unknown channel %d", chan);
+		}
 	}
 	return ses.channels[chan];
 }
 
+struct Channel* getchannel() {
+	return getchannel_msg(NULL);
+}
+
 /* Iterate through the channels, performing IO if available */
 void channelio(fd_set *readfds, fd_set *writefds) {
 
 	struct Channel *channel;
 	unsigned int i;
 
-	/* iterate through all the possible channels */
+	/* foreach channel */
 	for (i = 0; i < ses.chansize; i++) {
 
 		channel = ses.channels[i];
@@ -193,35 +205,38 @@
 
 		/* read data and send it over the wire */
 		if (channel->readfd >= 0 && FD_ISSET(channel->readfd, readfds)) {
-			send_msg_channel_data(channel, 0, 0);
+			TRACE(("send normal readfd"))
+			send_msg_channel_data(channel, 0);
 		}
 
 		/* read stderr data and send it over the wire */
-		if (channel->extrabuf == NULL &&
-				channel->errfd >= 0 && FD_ISSET(channel->errfd, readfds)) {
-				send_msg_channel_data(channel, 1, SSH_EXTENDED_DATA_STDERR);
+		if (ERRFD_IS_READ(channel) && channel->errfd >= 0 
+			&& FD_ISSET(channel->errfd, readfds)) {
+				TRACE(("send normal errfd"))
+				send_msg_channel_data(channel, 1);
 		}
 
 		/* write to program/pipe stdin */
 		if (channel->writefd >= 0 && FD_ISSET(channel->writefd, writefds)) {
 			if (channel->initconn) {
-				checkinitdone(channel);
+				/* XXX should this go somewhere cleaner? */
+				check_in_progress(channel);
 				continue; /* Important not to use the channel after
-							 checkinitdone(), as it may be NULL */
+							 check_in_progress(), as it may be NULL */
 			}
 			writechannel(channel, channel->writefd, channel->writebuf);
 		}
 		
 		/* stderr for client mode */
-		if (channel->extrabuf != NULL 
+		if (ERRFD_IS_WRITE(channel)
 				&& channel->errfd >= 0 && FD_ISSET(channel->errfd, writefds)) {
 			writechannel(channel, channel->errfd, channel->extrabuf);
 		}
 	
-		/* now handle any of the channel-closing type stuff */
-		checkclose(channel);
+		/* handle any channel closing etc */
+		check_close(channel);
 
-	} /* foreach channel */
+	}
 
 	/* Listeners such as TCP, X11, agent-auth */
 #ifdef USING_LISTENERS
@@ -230,94 +245,125 @@
 }
 
 
-/* do all the EOF/close type stuff checking for a channel */
-static void checkclose(struct Channel *channel) {
+/* Returns true if there is data remaining to be written to stdin or
+ * stderr of a channel's endpoint. */
+static unsigned int write_pending(struct Channel * channel) {
 
-	TRACE(("checkclose: writefd %d, readfd %d, errfd %d, sentclosed %d, recvclosed %d",
+	if (channel->writefd >= 0 && cbuf_getused(channel->writebuf) > 0) {
+		return 1;
+	} else if (channel->errfd >= 0 && channel->extrabuf && 
+			cbuf_getused(channel->extrabuf) > 0) {
+		return 1;
+	}
+	return 0;
+}
+
+
+/* EOF/close handling */
+static void check_close(struct Channel *channel) {
+	int close_allowed = 0;
+
+	TRACE(("check_close: writefd %d, readfd %d, errfd %d, sent_close %d, recv_close %d",
 				channel->writefd, channel->readfd,
-				channel->errfd, channel->sentclosed, channel->recvclosed))
-	TRACE(("writebuf %d extrabuf %s extrabuf %d",
+				channel->errfd, channel->sent_close, channel->recv_close))
+	TRACE(("writebuf size %d extrabuf size %d",
 				cbuf_getused(channel->writebuf),
-				channel->writebuf,
-				channel->writebuf ? 0 : cbuf_getused(channel->extrabuf)))
-
-	if (!channel->sentclosed) {
+				channel->extrabuf ? cbuf_getused(channel->extrabuf) : 0))
 
-		/* check for exited - currently only used for server sessions,
-		 * if the shell has exited etc */
-		if (channel->type->checkclose) {
-			if (channel->type->checkclose(channel)) {
-				closewritefd(channel);
-			}
-		}
+	if (!channel->flushing && channel->type->check_close
+		&& channel->type->check_close(channel))
+	{
+		channel->flushing = 1;
+	}
+	
+	/* if a type-specific check_close is defined we will only exit
+	   once that has been triggered. this is only used for a server "session"
+	   channel, to ensure that the shell has exited (and the exit status 
+	   retrieved) before we close things up. */
+	if (!channel->type->check_close	
+			|| channel->type->check_close(channel)) {
+		close_allowed = 1;
+	}
 
-		if (!channel->senteof
-			&& channel->readfd == FD_CLOSED 
-			&& (channel->extrabuf != NULL || channel->errfd == FD_CLOSED)) {
-			send_msg_channel_eof(channel);
+	if (channel->recv_close && !write_pending(channel) && close_allowed) {
+		if (!channel->sent_close) {
+			TRACE(("Sending MSG_CHANNEL_CLOSE in response to same."))
+			send_msg_channel_close(channel);
 		}
+		remove_channel(channel);
+		return;
+	}
 
-		if (channel->writefd == FD_CLOSED
-			&& channel->readfd == FD_CLOSED
-			&& (channel->extrabuf != NULL || channel->errfd == FD_CLOSED)) {
-			send_msg_channel_close(channel);
+	if (channel->recv_eof && !write_pending(channel)) {
+		close_chan_fd(channel, channel->writefd, SHUT_WR);
+	}
+
+	/* Special handling for flushing read data after an exit. We
+	   read regardless of whether the select FD was set,
+	   and if there isn't data available, the channel will get closed. */
+	if (channel->flushing) {
+		TRACE(("might send data, flushing"))
+		if (channel->readfd >= 0 && channel->transwindow > 0) {
+			TRACE(("send data readfd"))
+			send_msg_channel_data(channel, 0);
+		}
+		if (ERRFD_IS_READ(channel) && channel->errfd >= 0 
+			&& channel->transwindow > 0) {
+			TRACE(("send data errfd"))
+			send_msg_channel_data(channel, 1);
 		}
 	}
 
-	/* When either party wishes to terminate the channel, it sends
-	 * SSH_MSG_CHANNEL_CLOSE.  Upon receiving this message, a party MUST
-	 * send back a SSH_MSG_CHANNEL_CLOSE unless it has already sent this
-	 * message for the channel.  The channel is considered closed for a
-	 * party when it has both sent and received SSH_MSG_CHANNEL_CLOSE, and
-	 * the party may then reuse the channel number.  A party MAY send
-	 * SSH_MSG_CHANNEL_CLOSE without having sent or received
-	 * SSH_MSG_CHANNEL_EOF. 
-	 * (from draft-ietf-secsh-connect)
-	 */
-	if (channel->recvclosed) {
-		if (! channel->sentclosed) {
-			TRACE(("Sending MSG_CHANNEL_CLOSE in response to same."))
-			send_msg_channel_close(channel);
-		}
-		removechannel(channel);
+	/* If we're not going to send any more data, send EOF */
+	if (!channel->sent_eof
+			&& channel->readfd == FD_CLOSED 
+			&& (ERRFD_IS_WRITE(channel) || channel->errfd == FD_CLOSED)) {
+		send_msg_channel_eof(channel);
+	}
+
+	/* And if we can't receive any more data from them either, close up */
+	if (channel->readfd == FD_CLOSED
+			&& (ERRFD_IS_WRITE(channel) || channel->errfd == FD_CLOSED)
+			&& !channel->sent_close
+			&& close_allowed
+			&& !write_pending(channel)) {
+		TRACE(("sending close, readfd is closed"))
+		send_msg_channel_close(channel);
 	}
 }
 
-
 /* Check whether a deferred (EINPROGRESS) connect() was successful, and
  * if so, set up the channel properly. Otherwise, the channel is cleaned up, so
  * it is important that the channel reference isn't used after a call to this
  * function */
-static void checkinitdone(struct Channel *channel) {
+static void check_in_progress(struct Channel *channel) {
 
 	int val;
 	socklen_t vallen = sizeof(val);
 
-	TRACE(("enter checkinitdone"))
+	TRACE(("enter check_in_progress"))
 
 	if (getsockopt(channel->writefd, SOL_SOCKET, SO_ERROR, &val, &vallen)
 			|| val != 0) {
 		send_msg_channel_open_failure(channel->remotechan,
 				SSH_OPEN_CONNECT_FAILED, "", "");
 		close(channel->writefd);
-		deletechannel(channel);
-		TRACE(("leave checkinitdone: fail"))
+		delete_channel(channel);
+		TRACE(("leave check_in_progress: fail"))
 	} else {
 		send_msg_channel_open_confirmation(channel, channel->recvwindow,
 				channel->recvmaxpacket);
 		channel->readfd = channel->writefd;
 		channel->initconn = 0;
-		TRACE(("leave checkinitdone: success"))
+		TRACE(("leave check_in_progress: success"))
 	}
 }
 
 
-
 /* Send the close message and set the channel as closed */
 static void send_msg_channel_close(struct Channel *channel) {
 
 	TRACE(("enter send_msg_channel_close"))
-	/* XXX server */
 	if (channel->type->closehandler) {
 		channel->type->closehandler(channel);
 	}
@@ -329,8 +375,11 @@
 
 	encrypt_packet();
 
-	channel->senteof = 1;
-	channel->sentclosed = 1;
+	channel->sent_eof = 1;
+	channel->sent_close = 1;
+	close_chan_fd(channel, channel->readfd, SHUT_RD);
+	close_chan_fd(channel, channel->errfd, SHUT_RDWR);
+	close_chan_fd(channel, channel->writefd, SHUT_WR);
 	TRACE(("leave send_msg_channel_close"))
 }
 
@@ -345,7 +394,7 @@
 
 	encrypt_packet();
 
-	channel->senteof = 1;
+	channel->sent_eof = 1;
 
 	TRACE(("leave send_msg_channel_eof"))
 }
@@ -357,32 +406,25 @@
 
 	int len, maxlen;
 
-	TRACE(("enter writechannel"))
+	TRACE(("enter writechannel fd %d", fd))
 
 	maxlen = cbuf_readlen(cbuf);
 
 	/* Write the data out */
 	len = write(fd, cbuf_readptr(cbuf, maxlen), maxlen);
 	if (len <= 0) {
+		TRACE(("errno %d len %d", errno, len))
 		if (len < 0 && errno != EINTR) {
-			/* no more to write - we close it even if the fd was stderr, since
-			 * that's a nasty failure too */
-			closewritefd(channel);
+			close_chan_fd(channel, fd, SHUT_WR);
 		}
 		TRACE(("leave writechannel: len <= 0"))
 		return;
 	}
+	TRACE(("writechannel wrote %d", len))
 
 	cbuf_incrread(cbuf, len);
 	channel->recvdonelen += len;
 
-	if (fd == channel->writefd && cbuf_getused(cbuf) == 0 && channel->recveof) { 
-		/* Check if we're closing up */
-		closewritefd(channel);
-		TRACE(("leave writechannel: recveof set"))
-		return;
-	}
-
 	/* Window adjust handling */
 	if (channel->recvdonelen >= RECV_WINDOWEXTEND) {
 		/* Set it back to max window */
@@ -391,12 +433,11 @@
 		channel->recvdonelen = 0;
 	}
 
-	dropbear_assert(channel->recvwindow <= RECV_MAXWINDOW);
+	dropbear_assert(channel->recvwindow <= opts.recv_window);
 	dropbear_assert(channel->recvwindow <= cbuf_getavail(channel->writebuf));
 	dropbear_assert(channel->extrabuf == NULL ||
 			channel->recvwindow <= cbuf_getavail(channel->extrabuf));
 	
-	
 	TRACE(("leave writechannel"))
 }
 
@@ -421,7 +462,7 @@
 				FD_SET(channel->readfd, readfds);
 			}
 			
-			if (channel->extrabuf == NULL && channel->errfd >= 0) {
+			if (ERRFD_IS_READ(channel) && channel->errfd >= 0) {
 					FD_SET(channel->errfd, readfds);
 			}
 		}
@@ -429,11 +470,10 @@
 		/* Stuff from the wire */
 		if ((channel->writefd >= 0 && cbuf_getused(channel->writebuf) > 0 )
 				|| channel->initconn) {
-
 				FD_SET(channel->writefd, writefds);
 		}
 
-		if (channel->extrabuf != NULL && channel->errfd >= 0 
+		if (ERRFD_IS_WRITE(channel) && channel->errfd >= 0 
 				&& cbuf_getused(channel->extrabuf) > 0 ) {
 				FD_SET(channel->errfd, writefds);
 		}
@@ -455,18 +495,11 @@
 
 	TRACE(("enter recv_msg_channel_eof"))
 
-	channel = getchannel();
-	if (channel == NULL) {
-		dropbear_exit("EOF for unknown channel");
-	}
+	channel = getchannel_msg("EOF");
 
-	channel->recveof = 1;
-	if (cbuf_getused(channel->writebuf) == 0
-			&& (channel->extrabuf == NULL 
-					|| cbuf_getused(channel->extrabuf) == 0)) {
-		closewritefd(channel);
-	}
+	channel->recv_eof = 1;
 
+	check_close(channel);
 	TRACE(("leave recv_msg_channel_eof"))
 }
 
@@ -478,27 +511,20 @@
 
 	TRACE(("enter recv_msg_channel_close"))
 
-	channel = getchannel();
-	if (channel == NULL) {
-		/* disconnect ? */
-		dropbear_exit("Close for unknown channel");
-	}
+	channel = getchannel_msg("Close");
 
-	channel->recveof = 1;
-	channel->recvclosed = 1;
+	channel->recv_eof = 1;
+	channel->recv_close = 1;
 
-	if (channel->sentclosed) {
-		removechannel(channel);
-	}
-
+	check_close(channel);
 	TRACE(("leave recv_msg_channel_close"))
 }
 
 /* Remove a channel entry, this is only executed after both sides have sent
  * channel close */
-static void removechannel(struct Channel * channel) {
+static void remove_channel(struct Channel * channel) {
 
-	TRACE(("enter removechannel"))
+	TRACE(("enter remove_channel"))
 	TRACE(("channel index is %d", channel->index))
 
 	cbuf_free(channel->writebuf);
@@ -511,20 +537,23 @@
 
 
 	/* close the FDs in case they haven't been done
-	 * yet (ie they were shutdown etc */
+	 * yet (they might have been shutdown etc) */
+	TRACE(("CLOSE writefd %d", channel->writefd))
 	close(channel->writefd);
+	TRACE(("CLOSE readfd %d", channel->readfd))
 	close(channel->readfd);
+	TRACE(("CLOSE errfd %d", channel->errfd))
 	close(channel->errfd);
 
 	channel->typedata = NULL;
 
-	deletechannel(channel);
+	delete_channel(channel);
 
-	TRACE(("leave removechannel"))
+	TRACE(("leave remove_channel"))
 }
 
 /* Remove a channel entry */
-static void deletechannel(struct Channel *channel) {
+static void delete_channel(struct Channel *channel) {
 
 	ses.channels[channel->index] = NULL;
 	m_free(channel);
@@ -542,9 +571,10 @@
 	TRACE(("enter recv_msg_channel_request"))
 	
 	channel = getchannel();
-	if (channel == NULL) {
-		/* disconnect ? */
-		dropbear_exit("Unknown channel");
+
+	if (channel->sent_close) {
+		TRACE(("leave recv_msg_channel_request: already closed channel"))
+		return;
 	}
 
 	if (channel->type->reqhandler) {
@@ -562,26 +592,23 @@
  * chan is the remote channel, isextended is 0 if it is normal data, 1
  * if it is extended data. if it is extended, then the type is in
  * exttype */
-static void send_msg_channel_data(struct Channel *channel, int isextended,
-		unsigned int exttype) {
+static void send_msg_channel_data(struct Channel *channel, int isextended) {
 
-	buffer *buf;
 	int len;
-	unsigned int maxlen;
+	size_t maxlen, size_pos;
 	int fd;
 
-/*	TRACE(("enter send_msg_channel_data"))
-	TRACE(("extended = %d type = %d", isextended, exttype))*/
-
 	CHECKCLEARTOWRITE();
 
-	dropbear_assert(!channel->sentclosed);
+	TRACE(("enter send_msg_channel_data"))
+	dropbear_assert(!channel->sent_close);
 
 	if (isextended) {
 		fd = channel->errfd;
 	} else {
 		fd = channel->readfd;
 	}
+	TRACE(("enter send_msg_channel_data isextended %d fd %d", isextended, fd))
 	dropbear_assert(fd >= 0);
 
 	maxlen = MIN(channel->transwindow, channel->transmaxpacket);
@@ -589,44 +616,52 @@
 	 * exttype if is extended */
 	maxlen = MIN(maxlen, 
 			ses.writepayload->size - 1 - 4 - 4 - (isextended ? 4 : 0));
+	TRACE(("maxlen %d", maxlen))
 	if (maxlen == 0) {
 		TRACE(("leave send_msg_channel_data: no window"))
-		return; /* the data will get written later */
-	}
-
-	/* read the data */
-	TRACE(("maxlen %d", maxlen))
-	buf = buf_new(maxlen);
-	TRACE(("buf pos %d data %x", buf->pos, buf->data))
-	len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
-	if (len <= 0) {
-		/* on error/eof, send eof */
-		if (len == 0 || errno != EINTR) {
-			closereadfd(channel, fd);
-		}
-		buf_free(buf);
-		buf = NULL;
-		TRACE(("leave send_msg_channel_data: read err or EOF for fd %d", 
-					channel->index));
 		return;
 	}
-	buf_incrlen(buf, len);
 
 	buf_putbyte(ses.writepayload, 
 			isextended ? SSH_MSG_CHANNEL_EXTENDED_DATA : SSH_MSG_CHANNEL_DATA);
 	buf_putint(ses.writepayload, channel->remotechan);
-
 	if (isextended) {
-		buf_putint(ses.writepayload, exttype);
+		buf_putint(ses.writepayload, SSH_EXTENDED_DATA_STDERR);
 	}
+	/* a dummy size first ...*/
+	size_pos = ses.writepayload->pos;
+	buf_putint(ses.writepayload, 0);
 
-	buf_putstring(ses.writepayload, buf_getptr(buf, len), len);
-	buf_free(buf);
-	buf = NULL;
+	/* read the data */
+	len = read(fd, buf_getwriteptr(ses.writepayload, maxlen), maxlen);
+	if (len <= 0) {
+		if (len == 0 || errno != EINTR) {
+			/* This will also get hit in the case of EAGAIN. The only
+			time we expect to receive EAGAIN is when we're flushing a FD,
+			in which case it can be treated the same as EOF */
+			close_chan_fd(channel, fd, SHUT_RD);
+		}
+		ses.writepayload->len = ses.writepayload->pos = 0;
+		TRACE(("leave send_msg_channel_data: len %d read err %d or EOF for fd %d", 
+					len, errno, fd))
+		return;
+	}
+	buf_incrwritepos(ses.writepayload, len);
+	/* ... real size here */
+	buf_setpos(ses.writepayload, size_pos);
+	buf_putint(ses.writepayload, len);
 
 	channel->transwindow -= len;
 
 	encrypt_packet();
+	
+	/* If we receive less data than we requested when flushing, we've
+	   reached the equivalent of EOF */
+	if (channel->flushing && len < (ssize_t)maxlen)
+	{
+		TRACE(("closing from channel, flushing out."))
+		close_chan_fd(channel, fd, SHUT_RD);
+	}
 	TRACE(("leave send_msg_channel_data"))
 }
 
@@ -636,9 +671,6 @@
 	struct Channel *channel;
 
 	channel = getchannel();
-	if (channel == NULL) {
-		dropbear_exit("Unknown channel");
-	}
 
 	common_recv_msg_channel_data(channel, channel->writefd, channel->writebuf);
 }
@@ -655,16 +687,19 @@
 
 	TRACE(("enter recv_msg_channel_data"))
 
-	if (channel->recveof) {
+	if (channel->recv_eof) {
 		dropbear_exit("received data after eof");
 	}
 
  	if (fd < 0) {
-		dropbear_exit("received data with bad writefd");
+		/* If we have encountered failed write, the far side might still
+		 * be sending data without having yet received our close notification.
+		 * We just drop the data. */
+		return;
 	}
 
 	datalen = buf_getint(ses.payload);
-
+	TRACE(("length %d", datalen))
 
 	maxdata = cbuf_getavail(cbuf);
 
@@ -692,7 +727,7 @@
 
 	dropbear_assert(channel->recvwindow >= datalen);
 	channel->recvwindow -= datalen;
-	dropbear_assert(channel->recvwindow <= RECV_MAXWINDOW);
+	dropbear_assert(channel->recvwindow <= opts.recv_window);
 
 	TRACE(("leave recv_msg_channel_data"))
 }
@@ -706,16 +741,13 @@
 	unsigned int incr;
 	
 	channel = getchannel();
-	if (channel == NULL) {
-		dropbear_exit("Unknown channel");
-	}
 	
 	incr = buf_getint(ses.payload);
 	TRACE(("received window increment %d", incr))
-	incr = MIN(incr, MAX_TRANS_WIN_INCR);
+	incr = MIN(incr, TRANS_MAX_WIN_INCR);
 	
 	channel->transwindow += incr;
-	channel->transwindow = MIN(channel->transwindow, MAX_TRANS_WINDOW);
+	channel->transwindow = MIN(channel->transwindow, TRANS_MAX_WINDOW);
 
 }
 
@@ -735,7 +767,6 @@
 }
 	
 /* Handle a new channel request, performing any channel-type-specific setup */
-/* XXX server */
 void recv_msg_channel_open() {
 
 	unsigned char *type;
@@ -755,9 +786,9 @@
 
 	remotechan = buf_getint(ses.payload);
 	transwindow = buf_getint(ses.payload);
-	transwindow = MIN(transwindow, MAX_TRANS_WINDOW);
+	transwindow = MIN(transwindow, TRANS_MAX_WINDOW);
 	transmaxpacket = buf_getint(ses.payload);
-	transmaxpacket = MIN(transmaxpacket, MAX_TRANS_PAYLOAD_LEN);
+	transmaxpacket = MIN(transmaxpacket, TRANS_MAX_PAYLOAD_LEN);
 
 	/* figure what type of packet it is */
 	if (typelen > MAX_NAME_LEN) {
@@ -792,13 +823,13 @@
 
 	if (channel->type->inithandler) {
 		ret = channel->type->inithandler(channel);
+		if (ret == SSH_OPEN_IN_PROGRESS) {
+			/* We'll send the confirmation later */
+			goto cleanup;
+		}
 		if (ret > 0) {
-			if (ret == SSH_OPEN_IN_PROGRESS) {
-				/* We'll send the confirmation later */
-				goto cleanup;
-			}
 			errtype = ret;
-			deletechannel(channel);
+			delete_channel(channel);
 			TRACE(("inithandler returned failure %d", ret))
 			goto failure;
 		}
@@ -882,6 +913,49 @@
 	TRACE(("leave send_msg_channel_open_confirmation"))
 }
 
+/* close a fd, how is SHUT_RD or SHUT_WR */
+static void close_chan_fd(struct Channel *channel, int fd, int how) {
+
+	int closein = 0, closeout = 0;
+
+	if (channel->type->sepfds) {
+		TRACE(("SHUTDOWN(%d, %d)", fd, how))
+		shutdown(fd, how);
+		if (how == 0) {
+			closeout = 1;
+		} else {
+			closein = 1;
+		}
+	} else {
+		TRACE(("CLOSE some fd %d", fd))
+		close(fd);
+		closein = closeout = 1;
+	}
+
+	if (closeout && (fd == channel->readfd)) {
+		channel->readfd = FD_CLOSED;
+	}
+	if (closeout && ERRFD_IS_READ(channel) && (fd == channel->errfd)) {
+		channel->errfd = FD_CLOSED;
+	}
+
+	if (closein && fd == channel->writefd) {
+		channel->writefd = FD_CLOSED;
+	}
+	if (closein && ERRFD_IS_WRITE(channel) && (fd == channel->errfd)) {
+		channel->errfd = FD_CLOSED;
+	}
+
+	/* if we called shutdown on it and all references are gone, then we 
+	 * need to close() it to stop it lingering */
+	if (channel->type->sepfds && channel->readfd == FD_CLOSED 
+		&& channel->writefd == FD_CLOSED && channel->errfd == FD_CLOSED) {
+		TRACE(("CLOSE (finally) of %d", fd))
+		close(fd);
+	}
+}
+
+
 #if defined(USING_LISTENERS) || defined(DROPBEAR_CLIENT)
 /* Create a new channel, and start the open request. This is intended
  * for X11, agent, tcp forwarding, and should be filled with channel-specific
@@ -913,8 +987,8 @@
 	buf_putbyte(ses.writepayload, SSH_MSG_CHANNEL_OPEN);
 	buf_putstring(ses.writepayload, type->name, strlen(type->name));
 	buf_putint(ses.writepayload, chan->index);
-	buf_putint(ses.writepayload, RECV_MAXWINDOW);
-	buf_putint(ses.writepayload, RECV_MAXPACKET);
+	buf_putint(ses.writepayload, opts.recv_window);
+	buf_putint(ses.writepayload, RECV_MAX_PAYLOAD_LEN);
 
 	TRACE(("leave send_msg_channel_open_init()"))
 	return DROPBEAR_SUCCESS;
@@ -930,9 +1004,6 @@
 	TRACE(("enter recv_msg_channel_open_confirmation"))
 
 	channel = getchannel();
-	if (channel == NULL) {
-		dropbear_exit("Unknown channel");
-	}
 
 	if (!channel->await_open) {
 		dropbear_exit("unexpected channel reply");
@@ -950,7 +1021,7 @@
 	if (channel->type->inithandler) {
 		ret = channel->type->inithandler(channel);
 		if (ret > 0) {
-			removechannel(channel);
+			remove_channel(channel);
 			TRACE(("inithandler returned failure %d", ret))
 		}
 	}
@@ -965,74 +1036,12 @@
 	struct Channel * channel;
 
 	channel = getchannel();
-	if (channel == NULL) {
-		dropbear_exit("Unknown channel");
-	}
 
 	if (!channel->await_open) {
 		dropbear_exit("unexpected channel reply");
 	}
 	channel->await_open = 0;
 
-	removechannel(channel);
+	remove_channel(channel);
 }
 #endif /* USING_LISTENERS */
-
-/* close a stdout/stderr fd */
-static void closereadfd(struct Channel * channel, int fd) {
-
-	/* don't close it if it is the same as writefd,
-	 * unless writefd is already set -1 */
-	TRACE(("enter closereadfd"))
-	closechanfd(channel, fd, 0);
-	TRACE(("leave closereadfd"))
-}
-
-/* close a stdin fd */
-static void closewritefd(struct Channel * channel) {
-
-	TRACE(("enter closewritefd"))
-	closechanfd(channel, channel->writefd, 1);
-	TRACE(("leave closewritefd"))
-}
-
-/* close a fd, how is 0 for stdout/stderr, 1 for stdin */
-static void closechanfd(struct Channel *channel, int fd, int how) {
-
-	int closein = 0, closeout = 0;
-
-	/* XXX server */
-	if (channel->type->sepfds) {
-		TRACE(("shutdown((%d), %d)", fd, how))
-		shutdown(fd, how);
-		if (how == 0) {
-			closeout = 1;
-		} else {
-			closein = 1;
-		}
-	} else {
-		close(fd);
-		closein = closeout = 1;
-	}
-
-	if (closeout && fd == channel->readfd) {
-		channel->readfd = FD_CLOSED;
-	}
-	if (closeout && (channel->extrabuf == NULL) && (fd == channel->errfd)) {
-		channel->errfd = FD_CLOSED;
-	}
-
-	if (closein && fd == channel->writefd) {
-		channel->writefd = FD_CLOSED;
-	}
-	if (closein && (channel->extrabuf != NULL) && (fd == channel->errfd)) {
-		channel->errfd = FD_CLOSED;
-	}
-
-	/* if we called shutdown on it and all references are gone, then we 
-	 * need to close() it to stop it lingering */
-	if (channel->type->sepfds && channel->readfd == FD_CLOSED 
-		&& channel->writefd == FD_CLOSED && channel->errfd == FD_CLOSED) {
-		close(fd);
-	}
-}
--- a/common-kex.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/common-kex.c	Thu Nov 06 13:16:55 2008 +0000
@@ -188,8 +188,6 @@
 /* Reset the kex state, ready for a new negotiation */
 static void kexinitialise() {
 
-	struct timeval tv;
-
 	TRACE(("kexinitialise()"))
 
 	/* sent/recv'd MSG_KEXINIT */
@@ -206,10 +204,7 @@
 	ses.kexstate.datatrans = 0;
 	ses.kexstate.datarecv = 0;
 
-	if (gettimeofday(&tv, 0) < 0) {
-		dropbear_exit("Error getting time");
-	}
-	ses.kexstate.lastkextime = tv.tv_sec;
+	ses.kexstate.lastkextime = time(NULL);
 
 }
 
@@ -217,12 +212,10 @@
  * already initialised hash_state hs, which should already have processed
  * the dh_K and hash, since these are common. X is the letter 'A', 'B' etc.
  * out must have at least min(SHA1_HASH_SIZE, outlen) bytes allocated.
- * The output will only be expanded once, since that is all that is required
- * (for 3DES and SHA, with 24 and 20 bytes respectively). 
+ * The output will only be expanded once, as we are assured that
+ * outlen <= 2*SHA1_HASH_SIZE for all known hashes.
  *
- * See Section 5.2 of the IETF secsh Transport Draft for details */
-
-/* Duplicated verbatim from kex.c --mihnea */
+ * See Section 7.2 of rfc4253 (ssh transport) for details */
 static void hashkeys(unsigned char *out, int outlen, 
 		const hash_state * hs, const unsigned char X) {
 
@@ -262,6 +255,7 @@
 	hash_state hs;
 	unsigned int C2S_keysize, S2C_keysize;
 	char mactransletter, macrecvletter; /* Client or server specific */
+	int recv_cipher = 0, trans_cipher = 0;
 
 	TRACE(("enter gen_new_keys"))
 	/* the dh_K and hash are the start of all hashes, we make use of that */
@@ -298,6 +292,24 @@
 	hashkeys(C2S_key, C2S_keysize, &hs, 'C');
 	hashkeys(S2C_key, S2C_keysize, &hs, 'D');
 
+	recv_cipher = find_cipher(ses.newkeys->recv_algo_crypt->cipherdesc->name);
+	if (recv_cipher < 0)
+	    dropbear_exit("crypto error");
+	if (ses.newkeys->recv_crypt_mode->start(recv_cipher, 
+			recv_IV, recv_key, 
+			ses.newkeys->recv_algo_crypt->keysize, 0, 
+			&ses.newkeys->recv_cipher_state) != CRYPT_OK) {
+		dropbear_exit("crypto error");
+	}
+
+	trans_cipher = find_cipher(ses.newkeys->trans_algo_crypt->cipherdesc->name);
+	if (trans_cipher < 0)
+	    dropbear_exit("crypto error");
+	if (ses.newkeys->trans_crypt_mode->start(trans_cipher, 
+			trans_IV, trans_key, 
+			ses.newkeys->trans_algo_crypt->keysize, 0, 
+			&ses.newkeys->trans_cipher_state) != CRYPT_OK) {
+		dropbear_exit("crypto error");
 	if (ses.newkeys->recv_algo_crypt->cipherdesc != NULL) {
 		if (cbc_start(
 			find_cipher(ses.newkeys->recv_algo_crypt->cipherdesc->name),
@@ -342,12 +354,26 @@
 }
 
 #ifndef DISABLE_ZLIB
+
+int is_compress_trans() {
+	return ses.keys->trans_algo_comp == DROPBEAR_COMP_ZLIB
+		|| (ses.authstate.authdone
+			&& ses.keys->trans_algo_comp == DROPBEAR_COMP_ZLIB_DELAY);
+}
+
+int is_compress_recv() {
+	return ses.keys->recv_algo_comp == DROPBEAR_COMP_ZLIB
+		|| (ses.authstate.authdone
+			&& ses.keys->recv_algo_comp == DROPBEAR_COMP_ZLIB_DELAY);
+}
+
 /* Set up new zlib compression streams, close the old ones. Only
  * called from gen_new_keys() */
 static void gen_new_zstreams() {
 
 	/* create new zstreams */
-	if (ses.newkeys->recv_algo_comp == DROPBEAR_COMP_ZLIB) {
+	if (ses.newkeys->recv_algo_comp == DROPBEAR_COMP_ZLIB
+			|| ses.newkeys->recv_algo_comp == DROPBEAR_COMP_ZLIB_DELAY) {
 		ses.newkeys->recv_zstream = (z_streamp)m_malloc(sizeof(z_stream));
 		ses.newkeys->recv_zstream->zalloc = Z_NULL;
 		ses.newkeys->recv_zstream->zfree = Z_NULL;
@@ -359,7 +385,8 @@
 		ses.newkeys->recv_zstream = NULL;
 	}
 
-	if (ses.newkeys->trans_algo_comp == DROPBEAR_COMP_ZLIB) {
+	if (ses.newkeys->trans_algo_comp == DROPBEAR_COMP_ZLIB
+			|| ses.newkeys->trans_algo_comp == DROPBEAR_COMP_ZLIB_DELAY) {
 		ses.newkeys->trans_zstream = (z_streamp)m_malloc(sizeof(z_stream));
 		ses.newkeys->trans_zstream->zalloc = Z_NULL;
 		ses.newkeys->trans_zstream->zfree = Z_NULL;
@@ -371,7 +398,7 @@
 	} else {
 		ses.newkeys->trans_zstream = NULL;
 	}
-	
+
 	/* clean up old keys */
 	if (ses.keys->recv_zstream != NULL) {
 		if (inflateEnd(ses.keys->recv_zstream) == Z_STREAM_ERROR) {
@@ -388,7 +415,7 @@
 		m_free(ses.keys->trans_zstream);
 	}
 }
-#endif
+#endif /* DISABLE_ZLIB */
 
 
 /* Executed upon receiving a kexinit message from the client to initiate
@@ -525,7 +552,7 @@
 	hash_state hs;
 
 	/* read the prime and generator*/
-	mp_init(&dh_p);
+	m_mp_init(&dh_p);
 	bytes_to_mp(&dh_p, dh_p_val, DH_P_LEN);
 
 	/* Check that dh_pub_them (dh_e or dh_f) is in the range [1, p-1] */
@@ -697,6 +724,10 @@
 			(struct dropbear_cipher*)s2c_cipher_algo->data;
 		ses.newkeys->trans_algo_crypt = 
 			(struct dropbear_cipher*)c2s_cipher_algo->data;
+		ses.newkeys->recv_crypt_mode = 
+			(struct dropbear_cipher_mode*)s2c_cipher_algo->mode;
+		ses.newkeys->trans_crypt_mode =
+			(struct dropbear_cipher_mode*)c2s_cipher_algo->mode;
 		ses.newkeys->recv_algo_mac = 
 			(struct dropbear_hash*)s2c_hash_algo->data;
 		ses.newkeys->trans_algo_mac = 
@@ -709,6 +740,10 @@
 			(struct dropbear_cipher*)c2s_cipher_algo->data;
 		ses.newkeys->trans_algo_crypt = 
 			(struct dropbear_cipher*)s2c_cipher_algo->data;
+		ses.newkeys->recv_crypt_mode =
+			(struct dropbear_cipher_mode*)c2s_cipher_algo->mode;
+		ses.newkeys->trans_crypt_mode =
+			(struct dropbear_cipher_mode*)s2c_cipher_algo->mode;
 		ses.newkeys->recv_algo_mac = 
 			(struct dropbear_hash*)c2s_hash_algo->data;
 		ses.newkeys->trans_algo_mac = 
--- a/common-session.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/common-session.c	Thu Nov 06 13:16:55 2008 +0000
@@ -34,8 +34,10 @@
 #include "kex.h"
 #include "channel.h"
 #include "atomicio.h"
+#include "runopts.h"
 
 static void checktimeouts();
+static long select_timeout();
 static int ident_readln(int fd, char* buf, int count);
 
 struct sshsession ses; /* GLOBAL */
@@ -50,20 +52,28 @@
 
 
 /* called only at the start of a session, set up initial state */
-void common_session_init(int sock, char* remotehost) {
+void common_session_init(int sock_in, int sock_out, char* remotehost) {
 
 	TRACE(("enter session_init"))
 
 	ses.remotehost = remotehost;
 
-	ses.sock = sock;
-	ses.maxfd = sock;
+	ses.sock_in = sock_in;
+	ses.sock_out = sock_out;
+	ses.maxfd = MAX(sock_in, sock_out);
 
-	ses.connecttimeout = 0;
+	ses.connect_time = 0;
+	ses.last_packet_time = 0;
+	
+	if (pipe(ses.signal_pipe) < 0) {
+		dropbear_exit("signal pipe failed");
+	}
+	setnonblocking(ses.signal_pipe[0]);
+	setnonblocking(ses.signal_pipe[1]);
 	
 	kexfirstinitialise(); /* initialise the kex state */
 
-	ses.writepayload = buf_new(MAX_TRANS_PAYLOAD_LEN);
+	ses.writepayload = buf_new(TRANS_MAX_PAYLOAD_LEN);
 	ses.transseq = 0;
 
 	ses.readbuf = NULL;
@@ -74,15 +84,20 @@
 	initqueue(&ses.writequeue);
 
 	ses.requirenext = SSH_MSG_KEXINIT;
-	ses.dataallowed = 0; /* don't send data yet, we'll wait until after kex */
+	ses.dataallowed = 1; /* we can send data until we actually 
+							send the SSH_MSG_KEXINIT */
 	ses.ignorenext = 0;
 	ses.lastpacket = 0;
+	ses.reply_queue_head = NULL;
+	ses.reply_queue_tail = NULL;
 
 	/* set all the algos to none */
 	ses.keys = (struct key_context*)m_malloc(sizeof(struct key_context));
 	ses.newkeys = NULL;
 	ses.keys->recv_algo_crypt = &dropbear_nocipher;
 	ses.keys->trans_algo_crypt = &dropbear_nocipher;
+	ses.keys->recv_crypt_mode = &dropbear_mode_none;
+	ses.keys->trans_crypt_mode = &dropbear_mode_none;
 	
 	ses.keys->recv_algo_mac = &dropbear_nohash;
 	ses.keys->trans_algo_mac = &dropbear_nohash;
@@ -108,7 +123,6 @@
 
 	ses.allowprivport = 0;
 
-
 	TRACE(("leave session_init"))
 }
 
@@ -121,17 +135,21 @@
 	/* main loop, select()s for all sockets in use */
 	for(;;) {
 
-		timeout.tv_sec = SELECT_TIMEOUT;
+		timeout.tv_sec = select_timeout();
 		timeout.tv_usec = 0;
 		FD_ZERO(&writefd);
 		FD_ZERO(&readfd);
 		dropbear_assert(ses.payload == NULL);
-		if (ses.sock != -1) {
-			FD_SET(ses.sock, &readfd);
-			if (!isempty(&ses.writequeue)) {
-				FD_SET(ses.sock, &writefd);
-			}
+		if (ses.sock_in != -1) {
+			FD_SET(ses.sock_in, &readfd);
 		}
+		if (ses.sock_out != -1 && !isempty(&ses.writequeue)) {
+			FD_SET(ses.sock_out, &writefd);
+		}
+		
+		/* We get woken up when signal handlers write to this pipe.
+		   SIGCHLD in svr-chansession is the only one currently. */
+		FD_SET(ses.signal_pipe[0], &readfd);
 
 		/* set up for channels which require reading/writing */
 		if (ses.dataallowed) {
@@ -143,35 +161,39 @@
 			dropbear_exit("Terminated by signal");
 		}
 		
-		if (val < 0) {
-			if (errno == EINTR) {
-				/* This must happen even if we've been interrupted, so that
-				 * changed signal-handler vars can take effect etc */
-				if (loophandler) {
-					loophandler();
-				}
-				continue;
-			} else {
-				dropbear_exit("Error in select");
-			}
+		if (val < 0 && errno != EINTR) {
+			dropbear_exit("Error in select");
+		}
+
+		if (val <= 0) {
+			/* If we were interrupted or the select timed out, we still
+			 * want to iterate over channels etc for reading, to handle
+			 * server processes exiting etc. 
+			 * We don't want to read/write FDs. */
+			FD_ZERO(&writefd);
+			FD_ZERO(&readfd);
+		}
+		
+		/* We'll just empty out the pipe if required. We don't do
+		any thing with the data, since the pipe's purpose is purely to
+		wake up the select() above. */
+		if (FD_ISSET(ses.signal_pipe[0], &readfd)) {
+			char x;
+			while (read(ses.signal_pipe[0], &x, 1) > 0) {}
 		}
 
 		/* check for auth timeout, rekeying required etc */
 		checktimeouts();
-		
-		if (val == 0) {
-			/* timeout */
-			TRACE(("select timeout"))
-			continue;
+
+		/* process session socket's incoming/outgoing data */
+		if (ses.sock_out != -1) {
+			if (FD_ISSET(ses.sock_out, &writefd) && !isempty(&ses.writequeue)) {
+				write_packet();
+			}
 		}
 
-		/* process session socket's incoming/outgoing data */
-		if (ses.sock != -1) {
-			if (FD_ISSET(ses.sock, &writefd) && !isempty(&ses.writequeue)) {
-				write_packet();
-			}
-
-			if (FD_ISSET(ses.sock, &readfd)) {
+		if (ses.sock_in != -1) {
+			if (FD_ISSET(ses.sock_in, &readfd)) {
 				read_packet();
 			}
 			
@@ -181,6 +203,10 @@
 				process_packet();
 			}
 		}
+		
+		/* if required, flush out any queued reply packets that
+		were being held up during a KEX */
+		maybe_flush_reply_queue();
 
 		/* process pipes etc for the channels, ses.dataallowed == 0
 		 * during rekeying ) */
@@ -227,14 +253,14 @@
 	int i;
 
 	/* write our version string, this blocks */
-	if (atomicio(write, ses.sock, LOCAL_IDENT "\r\n",
+	if (atomicio(write, ses.sock_out, LOCAL_IDENT "\r\n",
 				strlen(LOCAL_IDENT "\r\n")) == DROPBEAR_FAILURE) {
-		dropbear_exit("Error writing ident string");
+		ses.remoteclosed();
 	}
 
     /* If they send more than 50 lines, something is wrong */
 	for (i = 0; i < 50; i++) {
-		len = ident_readln(ses.sock, linebuf, sizeof(linebuf));
+		len = ident_readln(ses.sock_in, linebuf, sizeof(linebuf));
 
 		if (len < 0 && errno != EINTR) {
 			/* It failed */
@@ -250,7 +276,7 @@
 
 	if (!done) {
 		TRACE(("err: %s for '%s'\n", strerror(errno), linebuf))
-		dropbear_exit("Failed to get remote version");
+		ses.remoteclosed();
 	} else {
 		/* linebuf is already null terminated */
 		ses.remoteident = m_malloc(len);
@@ -341,20 +367,22 @@
 	return pos+1;
 }
 
+void send_msg_ignore() {
+	CHECKCLEARTOWRITE();
+	buf_putbyte(ses.writepayload, SSH_MSG_IGNORE);
+	buf_putstring(ses.writepayload, "", 0);
+	encrypt_packet();
+}
+
 /* Check all timeouts which are required. Currently these are the time for
  * user authentication, and the automatic rekeying. */
 static void checktimeouts() {
 
-	struct timeval tv;
-	long secs;
+	time_t now;
 
-	if (gettimeofday(&tv, 0) < 0) {
-		dropbear_exit("Error getting time");
-	}
-
-	secs = tv.tv_sec;
+	now = time(NULL);
 	
-	if (ses.connecttimeout != 0 && secs > ses.connecttimeout) {
+	if (ses.connect_time != 0 && now - ses.connect_time >= AUTH_TIMEOUT) {
 			dropbear_close("Timeout before auth");
 	}
 
@@ -364,10 +392,59 @@
 	}
 
 	if (!ses.kexstate.sentkexinit
-			&& (secs - ses.kexstate.lastkextime >= KEX_REKEY_TIMEOUT
-			|| ses.kexstate.datarecv+ses.kexstate.datatrans >= KEX_REKEY_DATA)){
+			&& (now - ses.kexstate.lastkextime >= KEX_REKEY_TIMEOUT
+			|| ses.kexstate.datarecv+ses.kexstate.datatrans >= KEX_REKEY_DATA)) {
 		TRACE(("rekeying after timeout or max data reached"))
 		send_msg_kexinit();
 	}
+	
+	if (opts.keepalive_secs > 0 
+		&& now - ses.last_packet_time >= opts.keepalive_secs) {
+		send_msg_ignore();
+	}
+}
+
+static long select_timeout() {
+	/* determine the minimum timeout that might be required, so
+	as to avoid waking when unneccessary */
+	long ret = LONG_MAX;
+	if (KEX_REKEY_TIMEOUT > 0)
+		ret = MIN(KEX_REKEY_TIMEOUT, ret);
+	if (AUTH_TIMEOUT > 0)
+		ret = MIN(AUTH_TIMEOUT, ret);
+	if (opts.keepalive_secs > 0)
+		ret = MIN(opts.keepalive_secs, ret);
+	return ret;
 }
 
+const char* get_user_shell() {
+	/* an empty shell should be interpreted as "/bin/sh" */
+	if (ses.authstate.pw_shell[0] == '\0') {
+		return "/bin/sh";
+	} else {
+		return ses.authstate.pw_shell;
+	}
+}
+void fill_passwd(const char* username) {
+	struct passwd *pw = NULL;
+	if (ses.authstate.pw_name)
+		m_free(ses.authstate.pw_name);
+	if (ses.authstate.pw_dir)
+		m_free(ses.authstate.pw_dir);
+	if (ses.authstate.pw_shell)
+		m_free(ses.authstate.pw_shell);
+	if (ses.authstate.pw_passwd)
+		m_free(ses.authstate.pw_passwd);
+
+	pw = getpwnam(username);
+	if (!pw) {
+		return;
+	}
+	ses.authstate.pw_uid = pw->pw_uid;
+	ses.authstate.pw_gid = pw->pw_gid;
+	ses.authstate.pw_name = m_strdup(pw->pw_name);
+	ses.authstate.pw_dir = m_strdup(pw->pw_dir);
+	ses.authstate.pw_shell = m_strdup(pw->pw_shell);
+	ses.authstate.pw_passwd = m_strdup(pw->pw_passwd);
+}
+
--- a/config.guess	Mon Oct 02 06:40:51 2006 +0000
+++ b/config.guess	Thu Nov 06 13:16:55 2008 +0000
@@ -1,9 +1,10 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003 Free Software Foundation, Inc.
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
+#   Inc.
 
-timestamp='2003-05-19'
+timestamp='2007-01-15'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -17,13 +18,15 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
 #
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
 # the same distribution terms that you use for the rest of that program.
 
+
 # Originally written by Per Bothner <[email protected]>.
 # Please send patches to <[email protected]>.  Submit a context
 # diff and a properly formatted ChangeLog entry.
@@ -53,7 +56,7 @@
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
@@ -66,11 +69,11 @@
 while test $# -gt 0 ; do
   case $1 in
     --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit 0 ;;
+       echo "$timestamp" ; exit ;;
     --version | -v )
-       echo "$version" ; exit 0 ;;
+       echo "$version" ; exit ;;
     --help | --h* | -h )
-       echo "$usage"; exit 0 ;;
+       echo "$usage"; exit ;;
     -- )     # Stop option processing
        shift; break ;;
     - )	# Use stdin as input.
@@ -104,8 +107,9 @@
 trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
 trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
 : ${TMPDIR=/tmp} ;
- { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
  { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
  { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
 dummy=$tmp/dummy ;
 tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
@@ -122,7 +126,7 @@
 	;;
  ,,*)   CC_FOR_BUILD=$CC ;;
  ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
-esac ;'
+esac ; set_cc_for_build= ;'
 
 # This is needed to find uname on a Pyramid OSx when run in the BSD universe.
 # ([email protected] 1994-08-24)
@@ -157,6 +161,7 @@
 	    arm*) machine=arm-unknown ;;
 	    sh3el) machine=shl-unknown ;;
 	    sh3eb) machine=sh-unknown ;;
+	    sh5el) machine=sh5le-unknown ;;
 	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
 	esac
 	# The Operating System including object format, if it has switched
@@ -195,50 +200,32 @@
 	# contains redundant information, the shorter form:
 	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
 	echo "${machine}-${os}${release}"
-	exit 0 ;;
-    amiga:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    arc:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    hp300:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mac68k:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    macppc:OpenBSD:*:*)
-	echo powerpc-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mvme68k:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mvme88k:OpenBSD:*:*)
-	echo m88k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mvmeppc:OpenBSD:*:*)
-	echo powerpc-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    pmax:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    sgi:OpenBSD:*:*)
-	echo mipseb-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    sun3:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    wgrisc:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:OpenBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
+	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+	exit ;;
+    *:ekkoBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+	exit ;;
+    *:SolidBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+	exit ;;
+    macppc:MirBSD:*:*)
+	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    *:MirBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
     alpha:OSF1:*:*)
-	if test $UNAME_RELEASE = "V4.0"; then
+	case $UNAME_RELEASE in
+	*4.0)
 		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
-	fi
+		;;
+	*5.*)
+	        UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+		;;
+	esac
 	# According to Compaq, /usr/sbin/psrinfo has been available on
 	# OSF/1 and Tru64 systems produced since 1995.  I hope that
 	# covers most systems running today.  This code pipes the CPU
@@ -276,39 +263,49 @@
 	    "EV7.9 (21364A)")
 		UNAME_MACHINE="alphaev79" ;;
 	esac
+	# A Pn.n version is a patched version.
 	# A Vn.n version is a released version.
 	# A Tn.n version is a released field test version.
 	# A Xn.n version is an unreleased experimental baselevel.
 	# 1.2 uses "1.2" for uname -r.
-	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-	exit 0 ;;
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	exit ;;
     Alpha\ *:Windows_NT*:*)
 	# How do we know it's Interix rather than the generic POSIX subsystem?
 	# Should we change UNAME_MACHINE based on the output of uname instead
 	# of the specific Alpha model?
 	echo alpha-pc-interix
-	exit 0 ;;
+	exit ;;
     21064:Windows_NT:50:3)
 	echo alpha-dec-winnt3.5
-	exit 0 ;;
+	exit ;;
     Amiga*:UNIX_System_V:4.0:*)
 	echo m68k-unknown-sysv4
-	exit 0;;
+	exit ;;
     *:[Aa]miga[Oo][Ss]:*:*)
 	echo ${UNAME_MACHINE}-unknown-amigaos
-	exit 0 ;;
+	exit ;;
     *:[Mm]orph[Oo][Ss]:*:*)
 	echo ${UNAME_MACHINE}-unknown-morphos
-	exit 0 ;;
+	exit ;;
     *:OS/390:*:*)
 	echo i370-ibm-openedition
-	exit 0 ;;
+	exit ;;
+    *:z/VM:*:*)
+	echo s390-ibm-zvmoe
+	exit ;;
+    *:OS400:*:*)
+        echo powerpc-ibm-os400
+	exit ;;
     arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
 	echo arm-acorn-riscix${UNAME_RELEASE}
-	exit 0;;
+	exit ;;
+    arm:riscos:*:*|arm:RISCOS:*:*)
+	echo arm-unknown-riscos
+	exit ;;
     SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
 	echo hppa1.1-hitachi-hiuxmpp
-	exit 0;;
+	exit ;;
     Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
 	# [email protected] (Earle F. Ake) contributed MIS and NILE.
 	if test "`(/bin/universe) 2>/dev/null`" = att ; then
@@ -316,29 +313,32 @@
 	else
 		echo pyramid-pyramid-bsd
 	fi
-	exit 0 ;;
+	exit ;;
     NILE*:*:*:dcosx)
 	echo pyramid-pyramid-svr4
-	exit 0 ;;
-    DRS?6000:UNIX_SV:4.2*:7*)
+	exit ;;
+    DRS?6000:unix:4.0:6*)
+	echo sparc-icl-nx6
+	exit ;;
+    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
 	case `/usr/bin/uname -p` in
-	    sparc) echo sparc-icl-nx7 && exit 0 ;;
+	    sparc) echo sparc-icl-nx7; exit ;;
 	esac ;;
     sun4H:SunOS:5.*:*)
 	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
 	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     i86pc:SunOS:5.*:*)
 	echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     sun4*:SunOS:6*:*)
 	# According to config.sub, this is the proper way to canonicalize
 	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
 	# it's likely to be more like Solaris than SunOS4.
 	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     sun4*:SunOS:*:*)
 	case "`/usr/bin/arch -k`" in
 	    Series*|S4*)
@@ -347,10 +347,10 @@
 	esac
 	# Japanese Language versions have a version number like `4.1.3-JL'.
 	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
-	exit 0 ;;
+	exit ;;
     sun3*:SunOS:*:*)
 	echo m68k-sun-sunos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     sun*:*:4.2BSD:*)
 	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
 	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
@@ -362,10 +362,10 @@
 		echo sparc-sun-sunos${UNAME_RELEASE}
 		;;
 	esac
-	exit 0 ;;
+	exit ;;
     aushp:SunOS:*:*)
 	echo sparc-auspex-sunos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     # The situation for MiNT is a little confusing.  The machine name
     # can be virtually everything (everything which is not
     # "atarist" or "atariste" at least should have a processor
@@ -376,37 +376,40 @@
     # be no problem.
     atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
         echo m68k-atari-mint${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
 	echo m68k-atari-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
     *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
         echo m68k-atari-mint${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
         echo m68k-milan-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
     hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
         echo m68k-hades-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
     *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
         echo m68k-unknown-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
+    m68k:machten:*:*)
+	echo m68k-apple-machten${UNAME_RELEASE}
+	exit ;;
     powerpc:machten:*:*)
 	echo powerpc-apple-machten${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     RISC*:Mach:*:*)
 	echo mips-dec-mach_bsd4.3
-	exit 0 ;;
+	exit ;;
     RISC*:ULTRIX:*:*)
 	echo mips-dec-ultrix${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     VAX*:ULTRIX*:*:*)
 	echo vax-dec-ultrix${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     2020:CLIX:*:* | 2430:CLIX:*:*)
 	echo clipper-intergraph-clix${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     mips:*:*:UMIPS | mips:*:*:RISCos)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -430,32 +433,33 @@
 	  exit (-1);
 	}
 EOF
-	$CC_FOR_BUILD -o $dummy $dummy.c \
-	  && $dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
-	  && exit 0
+	$CC_FOR_BUILD -o $dummy $dummy.c &&
+	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+	  SYSTEM_NAME=`$dummy $dummyarg` &&
+	    { echo "$SYSTEM_NAME"; exit; }
 	echo mips-mips-riscos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     Motorola:PowerMAX_OS:*:*)
 	echo powerpc-motorola-powermax
-	exit 0 ;;
+	exit ;;
     Motorola:*:4.3:PL8-*)
 	echo powerpc-harris-powermax
-	exit 0 ;;
+	exit ;;
     Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
 	echo powerpc-harris-powermax
-	exit 0 ;;
+	exit ;;
     Night_Hawk:Power_UNIX:*:*)
 	echo powerpc-harris-powerunix
-	exit 0 ;;
+	exit ;;
     m88k:CX/UX:7*:*)
 	echo m88k-harris-cxux7
-	exit 0 ;;
+	exit ;;
     m88k:*:4*:R4*)
 	echo m88k-motorola-sysv4
-	exit 0 ;;
+	exit ;;
     m88k:*:3*:R3*)
 	echo m88k-motorola-sysv3
-	exit 0 ;;
+	exit ;;
     AViiON:dgux:*:*)
         # DG/UX returns AViiON for all architectures
         UNAME_PROCESSOR=`/usr/bin/uname -p`
@@ -471,29 +475,29 @@
 	else
 	    echo i586-dg-dgux${UNAME_RELEASE}
 	fi
- 	exit 0 ;;
+ 	exit ;;
     M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
 	echo m88k-dolphin-sysv3
-	exit 0 ;;
+	exit ;;
     M88*:*:R3*:*)
 	# Delta 88k system running SVR3
 	echo m88k-motorola-sysv3
-	exit 0 ;;
+	exit ;;
     XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
 	echo m88k-tektronix-sysv3
-	exit 0 ;;
+	exit ;;
     Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
 	echo m68k-tektronix-bsd
-	exit 0 ;;
+	exit ;;
     *:IRIX*:*:*)
 	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
-	exit 0 ;;
+	exit ;;
     ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
-	echo romp-ibm-aix      # uname -m gives an 8 hex-code CPU id
-	exit 0 ;;              # Note that: echo "'`uname -s`'" gives 'AIX '
+	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
+	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
     i*86:AIX:*:*)
 	echo i386-ibm-aix
-	exit 0 ;;
+	exit ;;
     ia64:AIX:*:*)
 	if [ -x /usr/bin/oslevel ] ; then
 		IBM_REV=`/usr/bin/oslevel`
@@ -501,7 +505,7 @@
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
 	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
-	exit 0 ;;
+	exit ;;
     *:AIX:2:3)
 	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
 		eval $set_cc_for_build
@@ -516,14 +520,18 @@
 			exit(0);
 			}
 EOF
-		$CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
-		echo rs6000-ibm-aix3.2.5
+		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+		then
+			echo "$SYSTEM_NAME"
+		else
+			echo rs6000-ibm-aix3.2.5
+		fi
 	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
 		echo rs6000-ibm-aix3.2.4
 	else
 		echo rs6000-ibm-aix3.2
 	fi
-	exit 0 ;;
+	exit ;;
     *:AIX:*:[45])
 	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
 	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
@@ -537,28 +545,28 @@
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
 	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
-	exit 0 ;;
+	exit ;;
     *:AIX:*:*)
 	echo rs6000-ibm-aix
-	exit 0 ;;
+	exit ;;
     ibmrt:4.4BSD:*|romp-ibm:BSD:*)
 	echo romp-ibm-bsd4.4
-	exit 0 ;;
+	exit ;;
     ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
 	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
-	exit 0 ;;                           # report: romp-ibm BSD 4.3
+	exit ;;                             # report: romp-ibm BSD 4.3
     *:BOSX:*:*)
 	echo rs6000-bull-bosx
-	exit 0 ;;
+	exit ;;
     DPX/2?00:B.O.S.:*:*)
 	echo m68k-bull-sysv3
-	exit 0 ;;
+	exit ;;
     9000/[34]??:4.3bsd:1.*:*)
 	echo m68k-hp-bsd
-	exit 0 ;;
+	exit ;;
     hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
 	echo m68k-hp-bsd4.4
-	exit 0 ;;
+	exit ;;
     9000/[34678]??:HP-UX:*:*)
 	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
 	case "${UNAME_MACHINE}" in
@@ -620,9 +628,19 @@
 	esac
 	if [ ${HP_ARCH} = "hppa2.0w" ]
 	then
-	    # avoid double evaluation of $set_cc_for_build
-	    test -n "$CC_FOR_BUILD" || eval $set_cc_for_build
-	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E -) | grep __LP64__ >/dev/null
+	    eval $set_cc_for_build
+
+	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
+	    # generating 64-bit code.  GNU and HP use different nomenclature:
+	    #
+	    # $ CC_FOR_BUILD=cc ./config.guess
+	    # => hppa2.0w-hp-hpux11.23
+	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+	    # => hppa64-hp-hpux11.23
+
+	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+		grep __LP64__ >/dev/null
 	    then
 		HP_ARCH="hppa2.0w"
 	    else
@@ -630,11 +648,11 @@
 	    fi
 	fi
 	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
-	exit 0 ;;
+	exit ;;
     ia64:HP-UX:*:*)
 	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
 	echo ia64-hp-hpux${HPUX_REV}
-	exit 0 ;;
+	exit ;;
     3050*:HI-UX:*:*)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -662,150 +680,179 @@
 	  exit (0);
 	}
 EOF
-	$CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
+	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+		{ echo "$SYSTEM_NAME"; exit; }
 	echo unknown-hitachi-hiuxwe2
-	exit 0 ;;
+	exit ;;
     9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
 	echo hppa1.1-hp-bsd
-	exit 0 ;;
+	exit ;;
     9000/8??:4.3bsd:*:*)
 	echo hppa1.0-hp-bsd
-	exit 0 ;;
+	exit ;;
     *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
 	echo hppa1.0-hp-mpeix
-	exit 0 ;;
+	exit ;;
     hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
 	echo hppa1.1-hp-osf
-	exit 0 ;;
+	exit ;;
     hp8??:OSF1:*:*)
 	echo hppa1.0-hp-osf
-	exit 0 ;;
+	exit ;;
     i*86:OSF1:*:*)
 	if [ -x /usr/sbin/sysversion ] ; then
 	    echo ${UNAME_MACHINE}-unknown-osf1mk
 	else
 	    echo ${UNAME_MACHINE}-unknown-osf1
 	fi
-	exit 0 ;;
+	exit ;;
     parisc*:Lites*:*:*)
 	echo hppa1.1-hp-lites
-	exit 0 ;;
+	exit ;;
     C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
 	echo c1-convex-bsd
-        exit 0 ;;
+        exit ;;
     C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
 	if getsysinfo -f scalar_acc
 	then echo c32-convex-bsd
 	else echo c2-convex-bsd
 	fi
-        exit 0 ;;
+        exit ;;
     C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
 	echo c34-convex-bsd
-        exit 0 ;;
+        exit ;;
     C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
 	echo c38-convex-bsd
-        exit 0 ;;
+        exit ;;
     C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
 	echo c4-convex-bsd
-        exit 0 ;;
+        exit ;;
     CRAY*Y-MP:*:*:*)
 	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*[A-Z]90:*:*:*)
 	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
 	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
 	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
 	      -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*TS:*:*:*)
 	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*T3E:*:*:*)
 	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*SV1:*:*:*)
 	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     *:UNICOS/mp:*:*)
-	echo nv1-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' 
-	exit 0 ;;
+	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
     F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
 	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
         FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
         FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
         echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
-        exit 0 ;;
+        exit ;;
+    5000:UNIX_System_V:4.*:*)
+        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+        FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+        echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
     i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
 	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     sparc*:BSD/OS:*:*)
 	echo sparc-unknown-bsdi${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:BSD/OS:*:*)
 	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
-	exit 0 ;;
-    *:FreeBSD:*:*|*:GNU/FreeBSD:*:*)
-	# Determine whether the default compiler uses glibc.
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#include <features.h>
-	#if __GLIBC__ >= 2
-	LIBC=gnu
-	#else
-	LIBC=
-	#endif
-EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
-	echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`${LIBC:+-$LIBC}
-	exit 0 ;;
+	exit ;;
+    *:FreeBSD:*:*)
+	case ${UNAME_MACHINE} in
+	    pc98)
+		echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    amd64)
+		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    *)
+		echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	esac
+	exit ;;
     i*:CYGWIN*:*)
 	echo ${UNAME_MACHINE}-pc-cygwin
-	exit 0 ;;
-    i*:MINGW*:*)
+	exit ;;
+    *:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
-	exit 0 ;;
+	exit ;;
+    i*:windows32*:*)
+    	# uname -m includes "-pc" on this system.
+    	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
     i*:PW*:*)
 	echo ${UNAME_MACHINE}-pc-pw32
-	exit 0 ;;
-    x86:Interix*:3*)
-	echo i586-pc-interix3
-	exit 0 ;;
+	exit ;;
+    x86:Interix*:[3456]*)
+	echo i586-pc-interix${UNAME_RELEASE}
+	exit ;;
+    EM64T:Interix*:[3456]* | authenticamd:Interix*:[3456]*)
+	echo x86_64-unknown-interix${UNAME_RELEASE}
+	exit ;;
     [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
 	echo i${UNAME_MACHINE}-pc-mks
-	exit 0 ;;
+	exit ;;
     i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
 	# How do we know it's Interix rather than the generic POSIX subsystem?
 	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
 	# UNAME_MACHINE based on the output of uname instead of i386?
 	echo i586-pc-interix
-	exit 0 ;;
+	exit ;;
     i*:UWIN*:*)
 	echo ${UNAME_MACHINE}-pc-uwin
-	exit 0 ;;
+	exit ;;
+    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+	echo x86_64-unknown-cygwin
+	exit ;;
     p*:CYGWIN*:*)
 	echo powerpcle-unknown-cygwin
-	exit 0 ;;
+	exit ;;
     prep*:SunOS:5.*:*)
 	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     *:GNU:*:*)
+	# the GNU system
 	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
-	exit 0 ;;
+	exit ;;
+    *:GNU/*:*:*)
+	# other systems with GNU libc and userland
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	exit ;;
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
-	exit 0 ;;
+	exit ;;
     arm*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    avr32*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
     cris:Linux:*:*)
 	echo cris-axis-linux-gnu
-	exit 0 ;;
+	exit ;;
+    crisv32:Linux:*:*)
+	echo crisv32-axis-linux-gnu
+	exit ;;
+    frv:Linux:*:*)
+    	echo frv-unknown-linux-gnu
+	exit ;;
     ia64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
     m68*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     mips:Linux:*:*)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -822,8 +869,12 @@
 	#endif
 	#endif
 EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
-	test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^CPU/{
+		s: ::g
+		p
+	    }'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
 	;;
     mips64:Linux:*:*)
 	eval $set_cc_for_build
@@ -841,15 +892,22 @@
 	#endif
 	#endif
 EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
-	test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^CPU/{
+		s: ::g
+		p
+	    }'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
 	;;
+    or32:Linux:*:*)
+	echo or32-unknown-linux-gnu
+	exit ;;
     ppc:Linux:*:*)
 	echo powerpc-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     ppc64:Linux:*:*)
 	echo powerpc64-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     alpha:Linux:*:*)
 	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
 	  EV5)   UNAME_MACHINE=alphaev5 ;;
@@ -863,7 +921,7 @@
 	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
 	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
 	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
-	exit 0 ;;
+	exit ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
 	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
@@ -871,22 +929,31 @@
 	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
 	  *)    echo hppa-unknown-linux-gnu ;;
 	esac
-	exit 0 ;;
+	exit ;;
     parisc64:Linux:*:* | hppa64:Linux:*:*)
 	echo hppa64-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
 	echo ${UNAME_MACHINE}-ibm-linux
-	exit 0 ;;
+	exit ;;
+    sh64*:Linux:*:*)
+    	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
     sh*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     sparc:Linux:*:* | sparc64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-gnu
+	exit ;;
     x86_64:Linux:*:*)
 	echo x86_64-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    xtensa:Linux:*:*)
+    	echo xtensa-unknown-linux-gnu
+	exit ;;
     i*86:Linux:*:*)
 	# The BFD linker knows what the default object file format is, so
 	# first see if it will tell us. cd to the root directory to prevent
@@ -904,15 +971,15 @@
 		;;
 	  a.out-i386-linux)
 		echo "${UNAME_MACHINE}-pc-linux-gnuaout"
-		exit 0 ;;
+		exit ;;
 	  coff-i386)
 		echo "${UNAME_MACHINE}-pc-linux-gnucoff"
-		exit 0 ;;
+		exit ;;
 	  "")
 		# Either a pre-BFD a.out linker (linux-gnuoldld) or
 		# one that does not give us useful --help.
 		echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
-		exit 0 ;;
+		exit ;;
 	esac
 	# Determine whether the default compiler is a.out or elf
 	eval $set_cc_for_build
@@ -929,23 +996,33 @@
 	LIBC=gnulibc1
 	# endif
 	#else
-	#ifdef __INTEL_COMPILER
+	#if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 	LIBC=gnu
 	#else
 	LIBC=gnuaout
 	#endif
 	#endif
+	#ifdef __dietlibc__
+	LIBC=dietlibc
+	#endif
 EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
-	test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0
-	test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^LIBC/{
+		s: ::g
+		p
+	    }'`"
+	test x"${LIBC}" != x && {
+		echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+		exit
+	}
+	test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; }
 	;;
     i*86:DYNIX/ptx:4*:*)
 	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
 	# earlier versions are messed up and put the nodename in both
 	# sysname and nodename.
 	echo i386-sequent-sysv4
-	exit 0 ;;
+	exit ;;
     i*86:UNIX_SV:4.2MP:2.*)
         # Unixware is an offshoot of SVR4, but it has its own version
         # number series starting with 2...
@@ -953,24 +1030,27 @@
 	# I just have to hope.  -- rms.
         # Use sysv4.2uw... so that sysv4* matches it.
 	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
-	exit 0 ;;
+	exit ;;
     i*86:OS/2:*:*)
 	# If we were able to find `uname', then EMX Unix compatibility
 	# is probably installed.
 	echo ${UNAME_MACHINE}-pc-os2-emx
-	exit 0 ;;
+	exit ;;
     i*86:XTS-300:*:STOP)
 	echo ${UNAME_MACHINE}-unknown-stop
-	exit 0 ;;
+	exit ;;
     i*86:atheos:*:*)
 	echo ${UNAME_MACHINE}-unknown-atheos
-	exit 0 ;;
+	exit ;;
+    i*86:syllable:*:*)
+	echo ${UNAME_MACHINE}-pc-syllable
+	exit ;;
     i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
 	echo i386-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     i*86:*DOS:*:*)
 	echo ${UNAME_MACHINE}-pc-msdosdjgpp
-	exit 0 ;;
+	exit ;;
     i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
 	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
 	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
@@ -978,15 +1058,16 @@
 	else
 		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
 	fi
-	exit 0 ;;
-    i*86:*:5:[78]*)
+	exit ;;
+    i*86:*:5:[678]*)
+    	# UnixWare 7.x, OpenUNIX and OpenServer 6.
 	case `/bin/uname -X | grep "^Machine"` in
 	    *486*)	     UNAME_MACHINE=i486 ;;
 	    *Pentium)	     UNAME_MACHINE=i586 ;;
 	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
 	esac
 	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
-	exit 0 ;;
+	exit ;;
     i*86:*:3.2:*)
 	if test -f /usr/options/cb.name; then
 		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
@@ -1004,73 +1085,73 @@
 	else
 		echo ${UNAME_MACHINE}-pc-sysv32
 	fi
-	exit 0 ;;
+	exit ;;
     pc:*:*:*)
 	# Left here for compatibility:
         # uname -m prints for DJGPP always 'pc', but it prints nothing about
         # the processor, so we play safe by assuming i386.
 	echo i386-pc-msdosdjgpp
-        exit 0 ;;
+        exit ;;
     Intel:Mach:3*:*)
 	echo i386-pc-mach3
-	exit 0 ;;
+	exit ;;
     paragon:*:*:*)
 	echo i860-intel-osf1
-	exit 0 ;;
+	exit ;;
     i860:*:4.*:*) # i860-SVR4
 	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
 	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
 	else # Add other i860-SVR4 vendors below as they are discovered.
 	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
 	fi
-	exit 0 ;;
+	exit ;;
     mini*:CTIX:SYS*5:*)
 	# "miniframe"
 	echo m68010-convergent-sysv
-	exit 0 ;;
+	exit ;;
     mc68k:UNIX:SYSTEM5:3.51m)
 	echo m68k-convergent-sysv
-	exit 0 ;;
+	exit ;;
     M680?0:D-NIX:5.3:*)
 	echo m68k-diab-dnix
-	exit 0 ;;
-    M68*:*:R3V[567]*:*)
-	test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
-    3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0)
+	exit ;;
+    M68*:*:R3V[5678]*:*)
+	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
 	OS_REL=''
 	test -r /etc/.relid \
 	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
 	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-	  && echo i486-ncr-sysv4.3${OS_REL} && exit 0
+	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
 	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
-	  && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
+	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
     3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
         /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-          && echo i486-ncr-sysv4 && exit 0 ;;
+          && { echo i486-ncr-sysv4; exit; } ;;
     m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
 	echo m68k-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     mc68030:UNIX_System_V:4.*:*)
 	echo m68k-atari-sysv4
-	exit 0 ;;
+	exit ;;
     TSUNAMI:LynxOS:2.*:*)
 	echo sparc-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     rs6000:LynxOS:2.*:*)
 	echo rs6000-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
 	echo powerpc-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     SM[BE]S:UNIX_SV:*:*)
 	echo mips-dde-sysv${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     RM*:ReliantUNIX-*:*:*)
 	echo mips-sni-sysv4
-	exit 0 ;;
+	exit ;;
     RM*:SINIX-*:*:*)
 	echo mips-sni-sysv4
-	exit 0 ;;
+	exit ;;
     *:SINIX-*:*:*)
 	if uname -p 2>/dev/null >/dev/null ; then
 		UNAME_MACHINE=`(uname -p) 2>/dev/null`
@@ -1078,68 +1159,81 @@
 	else
 		echo ns32k-sni-sysv
 	fi
-	exit 0 ;;
+	exit ;;
     PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
                       # says <[email protected]>
         echo i586-unisys-sysv4
-        exit 0 ;;
+        exit ;;
     *:UNIX_System_V:4*:FTX*)
 	# From Gerald Hewes <[email protected]>.
 	# How about differentiating between stratus architectures? -djm
 	echo hppa1.1-stratus-sysv4
-	exit 0 ;;
+	exit ;;
     *:*:*:FTX*)
 	# From [email protected]
 	echo i860-stratus-sysv4
-	exit 0 ;;
+	exit ;;
+    i*86:VOS:*:*)
+	# From [email protected]
+	echo ${UNAME_MACHINE}-stratus-vos
+	exit ;;
     *:VOS:*:*)
 	# From [email protected]
 	echo hppa1.1-stratus-vos
-	exit 0 ;;
+	exit ;;
     mc68*:A/UX:*:*)
 	echo m68k-apple-aux${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     news*:NEWS-OS:6*:*)
 	echo mips-sony-newsos6
-	exit 0 ;;
+	exit ;;
     R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
 	if [ -d /usr/nec ]; then
 	        echo mips-nec-sysv${UNAME_RELEASE}
 	else
 	        echo mips-unknown-sysv${UNAME_RELEASE}
 	fi
-        exit 0 ;;
+        exit ;;
     BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
 	echo powerpc-be-beos
-	exit 0 ;;
+	exit ;;
     BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
 	echo powerpc-apple-beos
-	exit 0 ;;
+	exit ;;
     BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
 	echo i586-pc-beos
-	exit 0 ;;
+	exit ;;
     SX-4:SUPER-UX:*:*)
 	echo sx4-nec-superux${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     SX-5:SUPER-UX:*:*)
 	echo sx5-nec-superux${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     SX-6:SUPER-UX:*:*)
 	echo sx6-nec-superux${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
+    SX-7:SUPER-UX:*:*)
+	echo sx7-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8:SUPER-UX:*:*)
+	echo sx8-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8R:SUPER-UX:*:*)
+	echo sx8r-nec-superux${UNAME_RELEASE}
+	exit ;;
     Power*:Rhapsody:*:*)
 	echo powerpc-apple-rhapsody${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:Rhapsody:*:*)
 	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:Darwin:*:*)
-	case `uname -p` in
-	    *86) UNAME_PROCESSOR=i686 ;;
-	    powerpc) UNAME_PROCESSOR=powerpc ;;
+	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+	case $UNAME_PROCESSOR in
+	    unknown) UNAME_PROCESSOR=powerpc ;;
 	esac
 	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
 	UNAME_PROCESSOR=`uname -p`
 	if test "$UNAME_PROCESSOR" = "x86"; then
@@ -1147,22 +1241,25 @@
 		UNAME_MACHINE=pc
 	fi
 	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:QNX:*:4*)
 	echo i386-pc-qnx
-	exit 0 ;;
-    NSR-[DGKLNPTVW]:NONSTOP_KERNEL:*:*)
+	exit ;;
+    NSE-?:NONSTOP_KERNEL:*:*)
+	echo nse-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSR-?:NONSTOP_KERNEL:*:*)
 	echo nsr-tandem-nsk${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:NonStop-UX:*:*)
 	echo mips-compaq-nonstopux
-	exit 0 ;;
+	exit ;;
     BS2000:POSIX*:*:*)
 	echo bs2000-siemens-sysv
-	exit 0 ;;
+	exit ;;
     DS/*:UNIX_System_V:*:*)
 	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:Plan9:*:*)
 	# "uname -m" is not consistent, so use $cputype instead. 386
 	# is converted to i386 for consistency with other x86
@@ -1173,25 +1270,47 @@
 	    UNAME_MACHINE="$cputype"
 	fi
 	echo ${UNAME_MACHINE}-unknown-plan9
-	exit 0 ;;
+	exit ;;
     *:TOPS-10:*:*)
 	echo pdp10-unknown-tops10
-	exit 0 ;;
+	exit ;;
     *:TENEX:*:*)
 	echo pdp10-unknown-tenex
-	exit 0 ;;
+	exit ;;
     KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
 	echo pdp10-dec-tops20
-	exit 0 ;;
+	exit ;;
     XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
 	echo pdp10-xkl-tops20
-	exit 0 ;;
+	exit ;;
     *:TOPS-20:*:*)
 	echo pdp10-unknown-tops20
-	exit 0 ;;
+	exit ;;
     *:ITS:*:*)
 	echo pdp10-unknown-its
-	exit 0 ;;
+	exit ;;
+    SEI:*:*:SEIUX)
+        echo mips-sei-seiux${UNAME_RELEASE}
+	exit ;;
+    *:DragonFly:*:*)
+	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+	exit ;;
+    *:*VMS:*:*)
+    	UNAME_MACHINE=`(uname -p) 2>/dev/null`
+	case "${UNAME_MACHINE}" in
+	    A*) echo alpha-dec-vms ; exit ;;
+	    I*) echo ia64-dec-vms ; exit ;;
+	    V*) echo vax-dec-vms ; exit ;;
+	esac ;;
+    *:XENIX:*:SysV)
+	echo i386-pc-xenix
+	exit ;;
+    i*86:skyos:*:*)
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	exit ;;
+    i*86:rdos:*:*)
+	echo ${UNAME_MACHINE}-pc-rdos
+	exit ;;
 esac
 
 #echo '(No uname command or uname output not recognized.)' 1>&2
@@ -1223,7 +1342,7 @@
 #endif
 
 #if defined (__arm) && defined (__acorn) && defined (__unix)
-  printf ("arm-acorn-riscix"); exit (0);
+  printf ("arm-acorn-riscix\n"); exit (0);
 #endif
 
 #if defined (hp300) && !defined (hpux)
@@ -1312,11 +1431,12 @@
 }
 EOF
 
-$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && $dummy && exit 0
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+	{ echo "$SYSTEM_NAME"; exit; }
 
 # Apollos put the system type in the environment.
 
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
 
 # Convex versions that predate uname can use getsysinfo(1)
 
@@ -1325,22 +1445,22 @@
     case `getsysinfo -f cpu_type` in
     c1*)
 	echo c1-convex-bsd
-	exit 0 ;;
+	exit ;;
     c2*)
 	if getsysinfo -f scalar_acc
 	then echo c32-convex-bsd
 	else echo c2-convex-bsd
 	fi
-	exit 0 ;;
+	exit ;;
     c34*)
 	echo c34-convex-bsd
-	exit 0 ;;
+	exit ;;
     c38*)
 	echo c38-convex-bsd
-	exit 0 ;;
+	exit ;;
     c4*)
 	echo c4-convex-bsd
-	exit 0 ;;
+	exit ;;
     esac
 fi
 
@@ -1351,7 +1471,9 @@
 the operating system you are using. It is advised that you
 download the most up to date version of the config scripts from
 
-    ftp://ftp.gnu.org/pub/gnu/config/
+  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess
+and
+  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub
 
 If the version you run ($0) is already up to date, please
 send the following data and any information you think might be
--- a/config.sub	Mon Oct 02 06:40:51 2006 +0000
+++ b/config.sub	Thu Nov 06 13:16:55 2008 +0000
@@ -1,9 +1,10 @@
 #! /bin/sh
 # Configuration validation subroutine script.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003 Free Software Foundation, Inc.
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
+#   Inc.
 
-timestamp='2003-05-09'
+timestamp='2007-01-18'
 
 # This file is (in principle) common to ALL GNU software.
 # The presence of a machine in this file suggests that SOME GNU software
@@ -21,14 +22,15 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330,
-# Boston, MA 02111-1307, USA.
-
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
 # the same distribution terms that you use for the rest of that program.
 
+
 # Please send patches to <[email protected]>.  Submit a context
 # diff and a properly formatted ChangeLog entry.
 #
@@ -70,7 +72,7 @@
 version="\
 GNU config.sub ($timestamp)
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
@@ -83,11 +85,11 @@
 while test $# -gt 0 ; do
   case $1 in
     --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit 0 ;;
+       echo "$timestamp" ; exit ;;
     --version | -v )
-       echo "$version" ; exit 0 ;;
+       echo "$version" ; exit ;;
     --help | --h* | -h )
-       echo "$usage"; exit 0 ;;
+       echo "$usage"; exit ;;
     -- )     # Stop option processing
        shift; break ;;
     - )	# Use stdin as input.
@@ -99,7 +101,7 @@
     *local*)
        # First pass through any local machine types.
        echo $1
-       exit 0;;
+       exit ;;
 
     * )
        break ;;
@@ -118,7 +120,9 @@
 # Here we must recognize all the valid KERNEL-OS combinations.
 maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
 case $maybe_os in
-  nto-qnx* | linux-gnu* | freebsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*)
+  nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
+  uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
     os=-$maybe_os
     basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
     ;;
@@ -144,7 +148,7 @@
 	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
 	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
 	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-	-apple | -axis)
+	-apple | -axis | -knuth | -cray)
 		os=
 		basic_machine=$1
 		;;
@@ -169,6 +173,10 @@
 	-hiux*)
 		os=-hiuxwe2
 		;;
+	-sco6)
+		os=-sco5v6
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
 	-sco5)
 		os=-sco3.2v5
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
@@ -185,6 +193,10 @@
 		# Don't forget version if it is 3.2v4 or newer.
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
 		;;
+	-sco5v6*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
 	-sco*)
 		os=-sco3.2v2
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
@@ -228,14 +240,17 @@
 	| a29k \
 	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
 	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
-	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
-	| clipper \
+	| am33_2.0 \
+	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
+	| bfin \
+	| c4x | clipper \
 	| d10v | d30v | dlx | dsp16xx \
-	| fr30 | frv \
+	| fido | fr30 | frv \
 	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
 	| i370 | i860 | i960 | ia64 \
-	| ip2k \
-	| m32r | m68000 | m68k | m88k | mcore \
+	| ip2k | iq2000 \
+	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+	| maxq | mb | microblaze | mcore | mep \
 	| mips | mipsbe | mipseb | mipsel | mipsle \
 	| mips16 \
 	| mips64 | mips64el \
@@ -244,27 +259,33 @@
 	| mips64vr4100 | mips64vr4100el \
 	| mips64vr4300 | mips64vr4300el \
 	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
 	| mipsisa32 | mipsisa32el \
 	| mipsisa32r2 | mipsisa32r2el \
 	| mipsisa64 | mipsisa64el \
+	| mipsisa64r2 | mipsisa64r2el \
 	| mipsisa64sb1 | mipsisa64sb1el \
 	| mipsisa64sr71k | mipsisa64sr71kel \
 	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
+	| mt \
 	| msp430 \
+	| nios | nios2 \
 	| ns16k | ns32k \
-	| openrisc | or32 \
+	| or32 \
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
 	| pyramid \
-	| sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
+	| score \
+	| sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
 	| sh64 | sh64le \
-	| sparc | sparc64 | sparc86x | sparclet | sparclite | sparcv9 | sparcv9b \
-	| strongarm \
-	| tahoe | thumb | tic80 | tron \
+	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+	| spu | strongarm \
+	| tahoe | thumb | tic4x | tic80 | tron \
 	| v850 | v850e \
 	| we32k \
-	| x86 | xscale | xstormy16 | xtensa \
+	| x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \
 	| z8k)
 		basic_machine=$basic_machine-unknown
 		;;
@@ -275,6 +296,9 @@
 		;;
 	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
 		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
 
 	# We use `pc' rather than `unknown'
 	# because (1) that's what they normally are, and
@@ -294,20 +318,20 @@
 	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
 	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
 	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
-	| avr-* \
-	| bs2000-* \
+	| avr-* | avr32-* \
+	| bfin-* | bs2000-* \
 	| c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
-	| clipper-* | cydra-* \
+	| clipper-* | craynv-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
 	| elxsi-* \
-	| f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
+	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
 	| h8300-* | h8500-* \
 	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
-	| ip2k-* \
-	| m32r-* \
+	| ip2k-* | iq2000-* \
+	| m32c-* | m32r-* | m32rle-* \
 	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
-	| m88110-* | m88k-* | mcore-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* \
 	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
 	| mips16-* \
 	| mips64-* | mips64el-* \
@@ -316,30 +340,36 @@
 	| mips64vr4100-* | mips64vr4100el-* \
 	| mips64vr4300-* | mips64vr4300el-* \
 	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
 	| mipsisa32-* | mipsisa32el-* \
 	| mipsisa32r2-* | mipsisa32r2el-* \
 	| mipsisa64-* | mipsisa64el-* \
+	| mipsisa64r2-* | mipsisa64r2el-* \
 	| mipsisa64sb1-* | mipsisa64sb1el-* \
 	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
 	| mipstx39-* | mipstx39el-* \
+	| mmix-* \
+	| mt-* \
 	| msp430-* \
-	| none-* | np1-* | nv1-* | ns16k-* | ns32k-* \
+	| nios-* | nios2-* \
+	| none-* | np1-* | ns16k-* | ns32k-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
 	| pyramid-* \
 	| romp-* | rs6000-* \
-	| sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
 	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
-	| sparc-* | sparc64-* | sparc86x-* | sparclet-* | sparclite-* \
-	| sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
+	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+	| sparclite-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \
 	| tahoe-* | thumb-* \
 	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
 	| tron-* \
 	| v850-* | v850e-* | vax-* \
 	| we32k-* \
-	| x86-* | x86_64-* | xps100-* | xscale-* | xstormy16-* \
-	| xtensa-* \
+	| x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \
+	| xstormy16-* | xtensa-* \
 	| ymp-* \
 	| z8k-*)
 		;;
@@ -359,6 +389,9 @@
 		basic_machine=a29k-amd
 		os=-udi
 		;;
+    	abacus)
+		basic_machine=abacus-unknown
+		;;
 	adobe68k)
 		basic_machine=m68010-adobe
 		os=-scout
@@ -376,6 +409,9 @@
 	amd64)
 		basic_machine=x86_64-pc
 		;;
+	amd64-*)
+		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	amdahl)
 		basic_machine=580-amdahl
 		os=-sysv
@@ -435,12 +471,27 @@
 		basic_machine=j90-cray
 		os=-unicos
 		;;
+	craynv)
+		basic_machine=craynv-cray
+		os=-unicosmp
+		;;
+	cr16c)
+		basic_machine=cr16c-unknown
+		os=-elf
+		;;
 	crds | unos)
 		basic_machine=m68k-crds
 		;;
+	crisv32 | crisv32-* | etraxfs*)
+		basic_machine=crisv32-axis
+		;;
 	cris | cris-* | etrax*)
 		basic_machine=cris-axis
 		;;
+	crx)
+		basic_machine=crx-unknown
+		os=-elf
+		;;
 	da30 | da30-*)
 		basic_machine=m68k-da30
 		;;
@@ -463,6 +514,10 @@
 		basic_machine=m88k-motorola
 		os=-sysv3
 		;;
+	djgpp)
+		basic_machine=i586-pc
+		os=-msdosdjgpp
+		;;
 	dpx20 | dpx20-*)
 		basic_machine=rs6000-bull
 		os=-bosx
@@ -641,10 +696,6 @@
 	mips3*)
 		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
 		;;
-	mmix*)
-		basic_machine=mmix-knuth
-		os=-mmixware
-		;;
 	monitor)
 		basic_machine=m68k-rom68k
 		os=-coff
@@ -657,6 +708,9 @@
 		basic_machine=i386-pc
 		os=-msdos
 		;;
+	ms1-*)
+		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+		;;
 	mvs)
 		basic_machine=i370-ibm
 		os=-mvs
@@ -725,10 +779,6 @@
 	np1)
 		basic_machine=np1-gould
 		;;
-	nv1)
-		basic_machine=nv1-cray
-		os=-unicosmp
-		;;
 	nsr-tandem)
 		basic_machine=nsr-tandem
 		;;
@@ -736,9 +786,12 @@
 		basic_machine=hppa1.1-oki
 		os=-proelf
 		;;
-	or32 | or32-*)
+	openrisc | openrisc-*)
 		basic_machine=or32-unknown
-		os=-coff
+		;;
+	os400)
+		basic_machine=powerpc-ibm
+		os=-os400
 		;;
 	OSE68000 | ose68000)
 		basic_machine=m68000-ericsson
@@ -765,24 +818,36 @@
 	pc532 | pc532-*)
 		basic_machine=ns32k-pc532
 		;;
+	pc98)
+		basic_machine=i386-pc
+		;;
+	pc98-*)
+		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	pentium | p5 | k5 | k6 | nexgen | viac3)
 		basic_machine=i586-pc
 		;;
 	pentiumpro | p6 | 6x86 | athlon | athlon_*)
 		basic_machine=i686-pc
 		;;
-	pentiumii | pentium2)
+	pentiumii | pentium2 | pentiumiii | pentium3)
 		basic_machine=i686-pc
 		;;
+	pentium4)
+		basic_machine=i786-pc
+		;;
 	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
 		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
 	pentiumpro-* | p6-* | 6x86-* | athlon-*)
 		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
-	pentiumii-* | pentium2-*)
+	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
 		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
+	pentium4-*)
+		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	pn)
 		basic_machine=pn-gould
 		;;
@@ -815,6 +880,10 @@
 		basic_machine=i586-unknown
 		os=-pw32
 		;;
+	rdos)
+		basic_machine=i386-pc
+		os=-rdos
+		;;
 	rom68k)
 		basic_machine=m68k-rom68k
 		os=-coff
@@ -841,6 +910,14 @@
 	sb1el)
 		basic_machine=mipsisa64sb1el-unknown
 		;;
+	sde)
+		basic_machine=mipsisa32-sde
+		os=-elf
+		;;
+	sei)
+		basic_machine=mips-sei
+		os=-seiux
+		;;
 	sequent)
 		basic_machine=i386-sequent
 		;;
@@ -848,6 +925,12 @@
 		basic_machine=sh-hitachi
 		os=-hms
 		;;
+	sh5el)
+		basic_machine=sh5le-unknown
+		;;
+	sh64)
+		basic_machine=sh64-unknown
+		;;
 	sparclite-wrs | simso-wrs)
 		basic_machine=sparclite-wrs
 		os=-vxworks
@@ -922,10 +1005,6 @@
 		basic_machine=t90-cray
 		os=-unicos
 		;;
-        tic4x | c4x*)
-		basic_machine=tic4x-unknown
-		os=-coff
-		;;
 	tic54x | c54x*)
 		basic_machine=tic54x-unknown
 		os=-coff
@@ -951,6 +1030,10 @@
 	tower | tower-32)
 		basic_machine=m68k-ncr
 		;;
+	tpf)
+		basic_machine=s390x-ibm
+		os=-tpf
+		;;
 	udi29k)
 		basic_machine=a29k-amd
 		os=-udi
@@ -994,6 +1077,10 @@
 		basic_machine=hppa1.1-winbond
 		os=-proelf
 		;;
+	xbox)
+		basic_machine=i686-pc
+		os=-mingw32
+		;;
 	xps | xps100)
 		basic_machine=xps100-honeywell
 		;;
@@ -1024,6 +1111,9 @@
 	romp)
 		basic_machine=romp-ibm
 		;;
+	mmix)
+		basic_machine=mmix-knuth
+		;;
 	rs6000)
 		basic_machine=rs6000-ibm
 		;;
@@ -1040,13 +1130,10 @@
 	we32k)
 		basic_machine=we32k-att
 		;;
-	sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele)
+	sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
 		basic_machine=sh-unknown
 		;;
-	sh64)
-		basic_machine=sh64-unknown
-		;;
-	sparc | sparcv9 | sparcv9b)
+	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
 		basic_machine=sparc-sun
 		;;
 	cydra)
@@ -1119,19 +1206,23 @@
 	      | -aos* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
 	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
-	      | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \
-	      | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+	      | -openbsd* | -solidbsd* \
+	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
 	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
 	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
 	      | -chorusos* | -chorusrdb* \
 	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
-	      | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* \
 	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
 	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
 	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
 	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
-	      | -powermax* | -dnix*)
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1149,12 +1240,15 @@
 		os=`echo $os | sed -e 's|nto|nto-qnx|'`
 		;;
 	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
-	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* \
+	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
 	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
 		;;
 	-mac*)
 		os=`echo $os | sed -e 's|mac|macos|'`
 		;;
+	-linux-dietlibc)
+		os=-linux-dietlibc
+		;;
 	-linux*)
 		os=`echo $os | sed -e 's|linux|linux-gnu|'`
 		;;
@@ -1167,6 +1261,9 @@
 	-opened*)
 		os=-openedition
 		;;
+        -os400*)
+		os=-os400
+		;;
 	-wince*)
 		os=-wince
 		;;
@@ -1188,6 +1285,9 @@
 	-atheos*)
 		os=-atheos
 		;;
+	-syllable*)
+		os=-syllable
+		;;
 	-386bsd)
 		os=-bsd
 		;;
@@ -1210,6 +1310,9 @@
 	-sinix*)
 		os=-sysv4
 		;;
+        -tpf*)
+		os=-tpf
+		;;
 	-triton*)
 		os=-sysv3
 		;;
@@ -1246,6 +1349,9 @@
 	-kaos*)
 		os=-kaos
 		;;
+	-zvmoe)
+		os=-zvmoe
+		;;
 	-none)
 		;;
 	*)
@@ -1268,6 +1374,12 @@
 # system, and we'll never get to this point.
 
 case $basic_machine in
+        score-*)
+		os=-elf
+		;;
+        spu-*)
+		os=-elf
+		;;
 	*-acorn)
 		os=-riscix1.2
 		;;
@@ -1277,6 +1389,9 @@
 	arm*-semi)
 		os=-aout
 		;;
+        c4x-* | tic4x-*)
+        	os=-coff
+		;;
 	# This must come before the *-dec entry.
 	pdp10-*)
 		os=-tops20
@@ -1302,6 +1417,9 @@
 	m68*-cisco)
 		os=-aout
 		;;
+        mep-*)
+		os=-elf
+		;;
 	mips*-cisco)
 		os=-elf
 		;;
@@ -1320,9 +1438,15 @@
 	*-be)
 		os=-beos
 		;;
+	*-haiku)
+		os=-haiku
+		;;
 	*-ibm)
 		os=-aix
 		;;
+    	*-knuth)
+		os=-mmixware
+		;;
 	*-wec)
 		os=-proelf
 		;;
@@ -1455,9 +1579,15 @@
 			-mvs* | -opened*)
 				vendor=ibm
 				;;
+			-os400*)
+				vendor=ibm
+				;;
 			-ptx*)
 				vendor=sequent
 				;;
+			-tpf*)
+				vendor=ibm
+				;;
 			-vxsim* | -vxworks* | -windiss*)
 				vendor=wrs
 				;;
@@ -1482,7 +1612,7 @@
 esac
 
 echo $basic_machine$os
-exit 0
+exit
 
 # Local variables:
 # eval: (add-hook 'write-file-hooks 'time-stamp)
--- a/configure.in	Mon Oct 02 06:40:51 2006 +0000
+++ b/configure.in	Thu Nov 06 13:16:55 2008 +0000
@@ -19,10 +19,13 @@
 AC_SUBST(LD)	
 
 if test -z "$OLDCFLAGS" && test "$GCC" = "yes"; then
-	AC_MSG_RESULT(No \$CFLAGS set... using "-Os -W -Wall" for GCC)
+	AC_MSG_NOTICE(No \$CFLAGS set... using "-Os -W -Wall" for GCC)
 	CFLAGS="-Os -W -Wall"
 fi
 
+# large file support is useful for scp
+AC_SYS_LARGEFILE
+
 # Host specific options
 # this isn't a definitive list of hosts, they are just added as required
 AC_CANONICAL_HOST
@@ -75,7 +78,7 @@
 AC_CHECK_DECL(__UCLIBC__, 
 	[
 	no_loginfunc_check=1
-	AC_MSG_RESULT(Using uClibc - login() and logout() probably don't work, so we won't use them.)
+	AC_MSG_NOTICE([Using uClibc - login() and logout() probably don't work, so we won't use them.])
 	],,,)
 
 # Checks for libraries.
@@ -104,16 +107,16 @@
 	[
 		if test "x$enableval" = "xno"; then
 			AC_DEFINE(DISABLE_ZLIB,, Use zlib)
-			AC_MSG_RESULT(Disabling zlib)
+			AC_MSG_NOTICE(Disabling zlib)
 		else
 			AC_CHECK_LIB(z, deflate, , AC_MSG_ERROR([*** zlib missing - install first or check config.log ***]))
-			AC_MSG_RESULT(Enabling zlib)
+			AC_MSG_NOTICE(Enabling zlib)
 		fi
 	],
 	[
 		# if not disabled, check for zlib
 		AC_CHECK_LIB(z, deflate, , AC_MSG_ERROR([*** zlib missing - install first or check config.log ***]))
-		AC_MSG_RESULT(Enabling zlib)
+		AC_MSG_NOTICE(Enabling zlib)
 	]
 )
 
@@ -141,16 +144,16 @@
 	[
 		if test "x$enableval" = "xyes"; then
 			AC_CHECK_LIB(pam, pam_authenticate, , AC_MSG_ERROR([*** PAM missing - install first or check config.log ***]))
-			AC_MSG_RESULT(Enabling PAM)
+			AC_MSG_NOTICE(Enabling PAM)
 		else
 			AC_DEFINE(DISABLE_PAM,, Use PAM)
-			AC_MSG_RESULT(Disabling PAM)
+			AC_MSG_NOTICE(Disabling PAM)
 		fi
 	],
 	[
 		# disable it by default
 		AC_DEFINE(DISABLE_PAM,, Use PAM)
-		AC_MSG_RESULT(Disabling PAM)
+		AC_MSG_NOTICE(Disabling PAM)
 	]
 )
 
@@ -158,14 +161,14 @@
 	[  --disable-openpty       Don't use openpty, use alternative method],
 	[
 		if test "x$enableval" = "xno"; then
-			AC_MSG_RESULT(Not using openpty)
+			AC_MSG_NOTICE(Not using openpty)
 		else
-			AC_MSG_RESULT(Using openpty if available)
+			AC_MSG_NOTICE(Using openpty if available)
 			AC_SEARCH_LIBS(openpty, util, [AC_DEFINE(HAVE_OPENPTY,,Have openpty() function)])
 		fi
 	],
 	[
-		AC_MSG_RESULT(Using openpty if available)
+		AC_MSG_NOTICE(Using openpty if available)
 		AC_SEARCH_LIBS(openpty, util, [AC_DEFINE(HAVE_OPENPTY)])
 	]
 )
@@ -176,13 +179,13 @@
 	[
 		if test "x$enableval" = "xno"; then
 			AC_DEFINE(DISABLE_SYSLOG,, Using syslog)
-			AC_MSG_RESULT(Disabling syslog)
+			AC_MSG_NOTICE(Disabling syslog)
 		else
-			AC_MSG_RESULT(Enabling syslog)
+			AC_MSG_NOTICE(Enabling syslog)
 		fi
 	],
 	[
-		AC_MSG_RESULT(Enabling syslog)
+		AC_MSG_NOTICE(Enabling syslog)
 	]
 )
 
@@ -190,15 +193,15 @@
 	[  --disable-shadow        Don't use shadow passwords (if available)],
 	[
 		if test "x$enableval" = "xno"; then
-			AC_MSG_RESULT(Not using shadow passwords)
+			AC_MSG_NOTICE(Not using shadow passwords)
 		else
 			AC_CHECK_HEADERS([shadow.h])
-			AC_MSG_RESULT(Using shadow passwords if available)
+			AC_MSG_NOTICE(Using shadow passwords if available)
 		fi
 	],
 	[
 		AC_CHECK_HEADERS([shadow.h])
-		AC_MSG_RESULT(Using shadow passwords if available)
+		AC_MSG_NOTICE(Using shadow passwords if available)
 	]
 )
 			
@@ -339,7 +342,7 @@
 #endif
 ])
 
-AC_CHECK_MEMBERS([struct utmpx.ut_host, struct utmpx.ut_syslen, struct utmpx.ut_type, struct utmpx.ut_id, struct utmpx.ut_addr, struct utmpx.ut_addr_v6, struct utmpx.ut_time, struct utmpx.ut_tv, struct sockaddr_storage.ss_family, struct sockadd_storage.__family],,,[
+AC_CHECK_MEMBERS([struct utmpx.ut_host, struct utmpx.ut_syslen, struct utmpx.ut_type, struct utmpx.ut_id, struct utmpx.ut_addr, struct utmpx.ut_addr_v6, struct utmpx.ut_time, struct utmpx.ut_tv],,,[
 #include <sys/types.h>
 #include <sys/socket.h>
 #if HAVE_UTMPX_H
@@ -347,6 +350,11 @@
 #endif
 ])
 
+AC_CHECK_MEMBERS([struct sockaddr_storage.ss_family],,,[
+#include <sys/types.h>
+#include <sys/socket.h>
+])
+
 AC_CHECK_FUNCS(endutent getutent getutid getutline pututline setutent)
 AC_CHECK_FUNCS(utmpname)
 AC_CHECK_FUNCS(endutxent getutxent getutxid getutxline pututxline )
@@ -379,7 +387,7 @@
 AC_ARG_ENABLE(loginfunc,
 	[  --disable-loginfunc     Disable use of login() etc. [no]],
 	[ no_loginfunc_check=1
-	AC_MSG_RESULT(Not using login() etc) ]
+	AC_MSG_NOTICE(Not using login() etc) ]
 )
 AC_ARG_ENABLE(pututline,
 	[  --disable-pututline     Disable use of pututline() etc. ([uw]tmp) [no]],
@@ -596,7 +604,7 @@
 	if test x"$cross_compiling" = x"no" ; then
 		AC_CHECK_FILE("/dev/ptmx", AC_DEFINE(USE_DEV_PTMX,,Use /dev/ptmx))
 	else
-		AC_MSG_RESULT(Not checking for /dev/ptmx, we're cross-compiling)
+		AC_MSG_NOTICE([Not checking for /dev/ptmx, we're cross-compiling])
 	fi
 fi
 
@@ -604,14 +612,62 @@
 	if test x"$cross_compiling" = x"no" ; then
 		AC_CHECK_FILE("/dev/ptc", AC_DEFINE(HAVE_DEV_PTS_AND_PTC,,Use /dev/ptc & /dev/pts))
 	else
-		AC_MSG_RESULT(Not checking for /dev/ptc & /dev/pts\, we're cross-compiling)
+		AC_MSG_NOTICE([Not checking for /dev/ptc & /dev/pts since we're cross-compiling])
 	fi
 fi
 
 AC_EXEEXT
+
+# XXX there must be a nicer way to do this
+AS_MKDIR_P(libtomcrypt/src/ciphers/aes)
+AS_MKDIR_P(libtomcrypt/src/ciphers/safer)
+AS_MKDIR_P(libtomcrypt/src/ciphers/twofish)
+AS_MKDIR_P(libtomcrypt/src/encauth/ccm)
+AS_MKDIR_P(libtomcrypt/src/encauth/eax)
+AS_MKDIR_P(libtomcrypt/src/encauth/gcm)
+AS_MKDIR_P(libtomcrypt/src/encauth/ocb)
+AS_MKDIR_P(libtomcrypt/src/hashes)
+AS_MKDIR_P(libtomcrypt/src/hashes/chc)
+AS_MKDIR_P(libtomcrypt/src/hashes/helper)
+AS_MKDIR_P(libtomcrypt/src/hashes/sha2)
+AS_MKDIR_P(libtomcrypt/src/hashes/whirl)
+AS_MKDIR_P(libtomcrypt/src/mac/hmac)
+AS_MKDIR_P(libtomcrypt/src/mac/omac)
+AS_MKDIR_P(libtomcrypt/src/mac/pelican)
+AS_MKDIR_P(libtomcrypt/src/mac/pmac)
+AS_MKDIR_P(libtomcrypt/src/mac/f9)
+AS_MKDIR_P(libtomcrypt/src/mac/xcbc)
+AS_MKDIR_P(libtomcrypt/src/math/fp)
+AS_MKDIR_P(libtomcrypt/src/misc/base64)
+AS_MKDIR_P(libtomcrypt/src/misc/crypt)
+AS_MKDIR_P(libtomcrypt/src/misc/mpi)
+AS_MKDIR_P(libtomcrypt/src/misc/pkcs5)
+AS_MKDIR_P(libtomcrypt/src/modes/cbc)
+AS_MKDIR_P(libtomcrypt/src/modes/cfb)
+AS_MKDIR_P(libtomcrypt/src/modes/ctr)
+AS_MKDIR_P(libtomcrypt/src/modes/ecb)
+AS_MKDIR_P(libtomcrypt/src/modes/ofb)
+AS_MKDIR_P(libtomcrypt/src/modes/f8)
+AS_MKDIR_P(libtomcrypt/src/modes/lrw)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/bit)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/choice)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/ia5)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/integer)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/object_identifier)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/octet)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/printable_string)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/sequence)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/short_integer)
+AS_MKDIR_P(libtomcrypt/src/pk/asn1/der/utctime)
+AS_MKDIR_P(libtomcrypt/src/pk/dh)
+AS_MKDIR_P(libtomcrypt/src/pk/dsa)
+AS_MKDIR_P(libtomcrypt/src/pk/ecc)
+AS_MKDIR_P(libtomcrypt/src/pk/pkcs1)
+AS_MKDIR_P(libtomcrypt/src/pk/rsa)
+AS_MKDIR_P(libtomcrypt/src/prng)
 AC_CONFIG_HEADER(config.h)
 AC_OUTPUT(Makefile)
 AC_OUTPUT(libtomcrypt/Makefile)
 AC_OUTPUT(libtommath/Makefile)
-AC_MSG_RESULT()
-AC_MSG_RESULT(Now edit options.h to choose features.)
+AC_MSG_NOTICE()
+AC_MSG_NOTICE(Now edit options.h to choose features.)
--- a/dbclient.1	Mon Oct 02 06:40:51 2006 +0000
+++ b/dbclient.1	Thu Nov 06 13:16:55 2008 +0000
@@ -10,6 +10,13 @@
 .I l\fR:\fIh\fR:\fIr\fR] [\-l
 .IR user ]
 .I host
+.RI [ command ]
+
+.B dbclient
+[
+.I args ]
+.I [user1]@host1[/port1],[user2]@host2[/port2],...
+
 .SH DESCRIPTION
 .B dbclient
 is a SSH 2 client designed to be small enough to be used in small memory
@@ -29,24 +36,23 @@
 .I idfile
 (multiple allowed).
 .TP
-.B \-L \fIlocalport\fR:\fIremotehost\fR:\fIremoteport\fR
+.B \-L \fIlistenport\fR:\fIhost\fR:\fIport\fR
 Local port forwarding.
 Forward the port
-.I localport
-on the local host to port
-.I remoteport
-on the remote host
-.IR remotehost .
+.I listenport
+on the local host through the SSH connection to port
+.I port
+on the host
+.IR host .
 .TP
-.B \-R \fIlocalport\fR:\fIremotehost\fR:\fIremoteport\fR
+.B \-R \fIlistenport\fR:\fIhost\fR:\fIport\fR
 Remote port forwarding.
 Forward the port
-.I remoteport
-on the remote host
-.I remotehost
-to port
-.I localport
-on the local host.
+.I listenport
+on the remote host through the SSH connection to port
+.I port
+on the host
+.IR host .
 .TP
 .B \-l \fIuser
 Username.
@@ -60,13 +66,70 @@
 .B \-T
 Don't allocate a pty.
 .TP
+.B \-N
+Don't request a remote shell or run any commands. Any command arguments are ignored.
+.TP
+.B \-f
+Fork into the background after authentication. A command argument (or -N) is required.
+This is useful when using password authentication.
+.TP
 .B \-g
 Allow non-local hosts to connect to forwarded ports. Applies to -L and -R
 forwarded ports, though remote connections to -R forwarded ports may be limited
 by the ssh server.
+.TP
+.B \-y
+Always accept hostkeys if they are unknown. If a hostkey mismatch occurs the
+connection will abort as normal.
+.TP
+.B \-W \fIwindowsize
+Specify the per-channel receive window buffer size. Increasing this 
+may improve network performance at the expense of memory use. Use -h to see the
+default buffer size.
+.TP
+.B \-K \fItimeout_seconds
+Ensure that traffic is transmitted at a certain interval in seconds. This is
+useful for working around firewalls or routers that drop connections after
+a certain period of inactivity. The trade-off is that a session may be
+closed if there is a temporary lapse of network connectivity. A setting
+if 0 disables keepalives.
+.B \-J \fIproxy_command
+Use the standard input/output of the program \fIproxy_command\fR rather than using
+a normal TCP connection. A hostname should be still be provided, as this is used for
+comparing saved hostkeys.
+.B \B \fIendhost:endport
+"Netcat-alike" mode, where Dropbear will connect to the given host, then create a
+forwarded connection to \fIendhost\fR. This will then be presented as dbclient's
+standard input/output.
+
+Dropbear will also allow multiple "hops" to be specified, separated by commas. In
+this case a connection will be made to the first host, then a TCP forwarded 
+connection will be made through that to the second host, and so on. Hosts other than
+the final destination will not see anything other than the encrypted SSH stream. 
+A port for a host can be specified with a slash (eg [email protected]/44 ).
+This syntax can also be used with scp or rsync (specifying dbclient as the 
+ssh/rsh command). A file can be "bounced" through multiple SSH hops, eg
+
+scp -S dbclient [email protected],[email protected],canyons:/tmp/dump .
+
+.SH ENVIRONMENT
+.TP
+.B DROPBEAR_PASSWORD
+A password to use for remote authentication can be specified in the environment
+variable DROPBEAR_PASSWORD. Care should be taken that the password is not
+exposed to other users on a multi-user system, or stored in accessible files.
+.TP
+.B SSH_ASKPASS
+dbclient can use an external program to request a password from a user.
+SSH_ASKPASS should be set to the path of a program that will return a password
+on standard output. This program will only be used if either DISPLAY is set and
+standard input is not a TTY, or the environment variable SSH_ASKPASS_ALWAYS is
+set.
 .SH AUTHOR
 Matt Johnston ([email protected]).
 .br
+Mihnea Stoenescu wrote initial Dropbear client support
+.br
 Gerrit Pape ([email protected]) wrote this manual page.
 .SH SEE ALSO
 dropbear(8), dropbearkey(8)
--- a/dbutil.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/dbutil.c	Thu Nov 06 13:16:55 2008 +0000
@@ -146,7 +146,7 @@
 	}
 
 	va_start(param, format);
-	fprintf(stderr, "TRACE: ");
+	fprintf(stderr, "TRACE (%d): ", getpid());
 	vfprintf(stderr, format, param);
 	fprintf(stderr, "\n");
 	va_end(param);
@@ -199,10 +199,10 @@
 	hints.ai_family = AF_UNSPEC; /* TODO: let them flag v4 only etc */
 	hints.ai_socktype = SOCK_STREAM;
 
-	// for calling getaddrinfo:
-	// address == NULL and !AI_PASSIVE: local loopback
-	// address == NULL and AI_PASSIVE: all interfaces
-	// address != NULL: whatever the address says
+	/* for calling getaddrinfo:
+	 address == NULL and !AI_PASSIVE: local loopback
+	 address == NULL and AI_PASSIVE: all interfaces
+	 address != NULL: whatever the address says */
 	if (!address) {
 		TRACE(("dropbear_listen: local loopback"))
 	} else {
@@ -286,9 +286,9 @@
 			len = 20 + strlen(strerror(err));
 			*errstring = (char*)m_malloc(len);
 			snprintf(*errstring, len, "Error listening: %s", strerror(err));
-			TRACE(("leave dropbear_listen: failure, %s", strerror(err)))
-			return -1;
 		}
+		TRACE(("leave dropbear_listen: failure, %s", strerror(err)))
+		return -1;
 	}
 
 	TRACE(("leave dropbear_listen: success, %d socks bound", nsock))
@@ -321,9 +321,10 @@
 	if (err) {
 		if (errstring != NULL && *errstring == NULL) {
 			int len;
-			len = 20 + strlen(gai_strerror(err));
+			len = 100 + strlen(gai_strerror(err));
 			*errstring = (char*)m_malloc(len);
-			snprintf(*errstring, len, "Error resolving: %s", gai_strerror(err));
+			snprintf(*errstring, len, "Error resolving '%s' port '%s'. %s", 
+					remotehost, remoteport, gai_strerror(err));
 		}
 		TRACE(("Error resolving: %s", gai_strerror(err)))
 		return -1;
@@ -389,6 +390,141 @@
 	return sock;
 }
 
+/* Sets up a pipe for a, returning three non-blocking file descriptors
+ * and the pid. exec_fn is the function that will actually execute the child process,
+ * it will be run after the child has fork()ed, and is passed exec_data.
+ * If ret_errfd == NULL then stderr will not be captured.
+ * ret_pid can be passed as  NULL to discard the pid. */
+int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
+		int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
+	int infds[2];
+	int outfds[2];
+	int errfds[2];
+	pid_t pid;
+
+	const int FDIN = 0;
+	const int FDOUT = 1;
+
+	/* redirect stdin/stdout/stderr */
+	if (pipe(infds) != 0) {
+		return DROPBEAR_FAILURE;
+	}
+	if (pipe(outfds) != 0) {
+		return DROPBEAR_FAILURE;
+	}
+	if (ret_errfd && pipe(errfds) != 0) {
+		return DROPBEAR_FAILURE;
+	}
+
+#ifdef __uClinux__
+	pid = vfork();
+#else
+	pid = fork();
+#endif
+
+	if (pid < 0) {
+		return DROPBEAR_FAILURE;
+	}
+
+	if (!pid) {
+		/* child */
+
+		TRACE(("back to normal sigchld"))
+		/* Revert to normal sigchld handling */
+		if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
+			dropbear_exit("signal() error");
+		}
+
+		/* redirect stdin/stdout */
+
+		if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
+			(dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
+			(ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
+			TRACE(("leave noptycommand: error redirecting FDs"))
+			dropbear_exit("child dup2() failure");
+		}
+
+		close(infds[FDOUT]);
+		close(infds[FDIN]);
+		close(outfds[FDIN]);
+		close(outfds[FDOUT]);
+		if (ret_errfd)
+		{
+			close(errfds[FDIN]);
+			close(errfds[FDOUT]);
+		}
+
+		exec_fn(exec_data);
+		/* not reached */
+		return DROPBEAR_FAILURE;
+	} else {
+		/* parent */
+		close(infds[FDIN]);
+		close(outfds[FDOUT]);
+
+		setnonblocking(outfds[FDIN]);
+		setnonblocking(infds[FDOUT]);
+
+		if (ret_errfd) {
+			close(errfds[FDOUT]);
+			setnonblocking(errfds[FDIN]);
+		}
+
+		if (ret_pid) {
+			*ret_pid = pid;
+		}
+
+		*ret_writefd = infds[FDOUT];
+		*ret_readfd = outfds[FDIN];
+		if (ret_errfd) {
+			*ret_errfd = errfds[FDIN];
+		}
+		return DROPBEAR_SUCCESS;
+	}
+}
+
+/* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
+ * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
+ */
+void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
+	char * argv[4];
+	char * baseshell = NULL;
+	unsigned int i;
+
+	baseshell = basename(usershell);
+
+	if (cmd != NULL) {
+		argv[0] = baseshell;
+	} else {
+		/* a login shell should be "-bash" for "/bin/bash" etc */
+		int len = strlen(baseshell) + 2; /* 2 for "-" */
+		argv[0] = (char*)m_malloc(len);
+		snprintf(argv[0], len, "-%s", baseshell);
+	}
+
+	if (cmd != NULL) {
+		argv[1] = "-c";
+		argv[2] = (char*)cmd;
+		argv[3] = NULL;
+	} else {
+		/* construct a shell of the form "-bash" etc */
+		argv[1] = NULL;
+	}
+
+	/* Re-enable SIGPIPE for the executed process */
+	if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
+		dropbear_exit("signal() error");
+	}
+
+	/* close file descriptors except stdin/stdout/stderr
+	 * Need to be sure FDs are closed here to avoid reading files as root */
+	for (i = 3; i <= maxfd; i++) {
+		m_close(i);
+	}
+
+	execv(usershell, argv);
+}
+
 /* Return a string representation of the socket address passed. The return
  * value is allocated with malloc() */
 unsigned char * getaddrstring(struct sockaddr_storage* addr, int withport) {
@@ -400,7 +536,10 @@
 
 	len = sizeof(struct sockaddr_storage);
 	/* Some platforms such as Solaris 8 require that len is the length
-	 * of the specific structure. */
+	 * of the specific structure. Some older linux systems (glibc 2.1.3
+	 * such as debian potato) have sockaddr_storage.__ss_family instead
+	 * but we'll ignore them */
+#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
 	if (addr->ss_family == AF_INET) {
 		len = sizeof(struct sockaddr_in);
 	}
@@ -409,6 +548,7 @@
 		len = sizeof(struct sockaddr_in6);
 	}
 #endif
+#endif
 
 	ret = getnameinfo((struct sockaddr*)addr, len, hbuf, sizeof(hbuf), 
 			sbuf, sizeof(sbuf), NI_NUMERICSERV | NI_NUMERICHOST);
@@ -448,6 +588,7 @@
 	len = sizeof(struct sockaddr_storage);
 	/* Some platforms such as Solaris 8 require that len is the length
 	 * of the specific structure. */
+#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
 	if (addr->ss_family == AF_INET) {
 		len = sizeof(struct sockaddr_in);
 	}
@@ -456,6 +597,7 @@
 		len = sizeof(struct sockaddr_in6);
 	}
 #endif
+#endif
 
 
 	ret = getnameinfo((struct sockaddr*)addr, len, hbuf, sizeof(hbuf),
@@ -521,26 +663,36 @@
  * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
 int buf_readfile(buffer* buf, const char* filename) {
 
-	int fd;
+	int fd = -1;
 	int len;
 	int maxlen;
+	int ret = DROPBEAR_FAILURE;
 
 	fd = open(filename, O_RDONLY);
 
 	if (fd < 0) {
-		close(fd);
-		return DROPBEAR_FAILURE;
+		goto out;
 	}
 	
 	do {
 		maxlen = buf->size - buf->pos;
-		len = read(fd, buf_getwriteptr(buf, maxlen),
-				maxlen);
+		len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
+		if (len < 0) {
+			if (errno == EINTR || errno == EAGAIN) {
+				continue;
+			}
+			goto out;
+		}
 		buf_incrwritepos(buf, len);
 	} while (len < maxlen && len > 0);
 
-	close(fd);
-	return DROPBEAR_SUCCESS;
+	ret = DROPBEAR_SUCCESS;
+
+out:
+	if (fd >= 0) {
+		m_close(fd);
+	}
+	return ret;
 }
 
 /* get a line from the file into buffer in the style expected for an
@@ -677,3 +829,23 @@
 	}
 	TRACE(("leave setnonblocking"))
 }
+
+void disallow_core() {
+	struct rlimit lim;
+	lim.rlim_cur = lim.rlim_max = 0;
+	setrlimit(RLIMIT_CORE, &lim);
+}
+
+/* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
+int m_str_to_uint(const char* str, unsigned int *val) {
+	errno = 0;
+	*val = strtoul(str, NULL, 10);
+	/* The c99 spec doesn't actually seem to define EINVAL, but most platforms
+	 * I've looked at mention it in their manpage */
+	if ((*val == 0 && errno == EINVAL)
+		|| (*val == ULONG_MAX && errno == ERANGE)) {
+		return DROPBEAR_FAILURE;
+	} else {
+		return DROPBEAR_SUCCESS;
+	}
+}
--- a/dbutil.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/dbutil.h	Thu Nov 06 13:16:55 2008 +0000
@@ -49,6 +49,9 @@
 unsigned char * getaddrstring(struct sockaddr_storage* addr, int withport);
 int dropbear_listen(const char* address, const char* port,
 		int *socks, unsigned int sockcount, char **errstring, int *maxfd);
+int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
+		int *writefd, int *readfd, int *errfd, pid_t *pid);
+void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell);
 int connect_remote(const char* remotehost, const char* remoteport,
 		int nonblocking, char ** errstring);
 char* getaddrhostname(struct sockaddr_storage * addr);
@@ -63,6 +66,8 @@
 void __m_free(void* ptr);
 void m_burn(void* data, unsigned int len);
 void setnonblocking(int fd);
+void disallow_core();
+int m_str_to_uint(const char* str, unsigned int *val);
 
 /* Used to force mp_ints to be initialised */
 #define DEF_MP_INT(X) mp_int X = {0, 0, 0, NULL}
--- a/debian/README.runit	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/README.runit	Thu Nov 06 13:16:55 2008 +0000
@@ -31,16 +31,16 @@
 
  # vi /etc/dropbear/run
 
-Finally enable the service by linking dropbear's service directory to
-/var/service/.  The service will be started within five seconds, and
-automatically at boot time.  The sysv init script is disabled; see the
-runsvctrl(8) program for information on how to control services handled by
-runit.  See the svlogd(8) program on how to configure the log service.
+Finally enable the service through runit's update-service(8) program, the
+service will be started within five seconds, and automatically at boot
+time, and the sysv init script will automatically be disabled; see the
+sv(8) program for information on how to control services handled by runit.
+See the svlogd(8) program on how to configure the log service.
 
- # ln -s /etc/dropbear /var/service/
+ # update-service --add /etc/dropbear
 
 Optionally check the status of the service a few seconds later
 
- # runsvstat -l /var/service/dropbear
+ # sv status dropbear
 
- -- Gerrit Pape <[email protected]>, Sun, 16 May 2004 15:52:34 +0000
+ -- Gerrit Pape <[email protected]>, Fri, 02 Mar 2007 20:41:08 +0000
--- a/debian/changelog	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/changelog	Thu Nov 06 13:16:55 2008 +0000
@@ -1,14 +1,105 @@
-dropbear (0.48-0.1) unstable; urgency=high
+dropbear (0.51-0.1) unstable; urgency=low
 
   * New upstream release.
-  * SECURITY: Improve handling of denial of service attempts from a single IP.
+
+ -- Matt Johnston <[email protected]>  Thu, 27 Mar 2008 19:14:00 +0900
+
+dropbear (0.50-4) unstable; urgency=low
+
+  * debian/dropbear.init: apply patch from Petter Reinholdtsen: add LSB
+    formatted dependency info in init.d script (closes: #466257).
+  * debian/rules: no longer include symlinks for ./supervise/ subdirectories.
+  * debian/dropbear.postinst: upgrade from << 0.50-4: if dropbear is managed
+    by runit, remove service, and re-add using update-service(8).
+  * debian/control: Standards-Version: 3.7.3.0.
+  * debian/rules: target clean: don't ignore errors but check for readable
+    ./Makefile.
+
+ -- Gerrit Pape <[email protected]>  Thu, 06 Mar 2008 19:06:58 +0000
+
+dropbear (0.50-3) unstable; urgency=low
+
+  * debian/dropbear.init: use the update-service(8) program from the runit
+    package instead of directly checking for the symlink in /var/service/.
+  * debian/README.runit: talk about update-service(8) instead of symlinks
+    in /var/service/.
+
+ -- Gerrit Pape <[email protected]>  Fri, 15 Feb 2008 00:32:37 +0000
+
+dropbear (0.50-2) unstable; urgency=low
+
+  * debian/dropbear.README.Debian: no longer talk about entropy from
+    /dev/random, /dev/urandom is now used by default (thx Joey Hess,
+    closes: #441515).
+
+ -- Gerrit Pape <[email protected]>  Mon, 24 Sep 2007 16:49:17 +0000
+
+dropbear (0.50-1) unstable; urgency=low
+
+  * debian/README.runit: minor.
+  * new upstream version.
+  * debian/diff/0001-options.h-use-dev-urandom-instead-of-dev-random-a.diff:
+    remove; fixed upstream.
 
- -- Matt Johnston <[email protected]>  Thu, 8 Mar 2006 19:20:21 +0800
+ -- Gerrit Pape <[email protected]>  Thu, 09 Aug 2007 23:01:01 +0000
+
+dropbear (0.49-2) unstable; urgency=low
+
+  * debian/rules: apply diffs from debian/diff/ with patch -p1 instead of
+    -p0.
+  * debian/diff/0001-options.h-use-dev-urandom-instead-of-dev-random-a.diff:
+    new; options.h: use /dev/urandom instead of /dev/random as
+    DROPBEAR_RANDOM_DEV (closes: #386976).
+  * debian/rules: target clean: remove libtomcrypt/Makefile,
+    libtommath/Makefile.
+
+ -- Gerrit Pape <[email protected]>  Sat, 09 Jun 2007 08:59:59 +0000
+
+dropbear (0.49-1) unstable; urgency=high
 
-dropbear (0.47-0.1) unstable; urgency=high
+  * new upstream release, fixes
+    * CVE-2007-1099: dropbear dbclient insufficient warning on hostkey
+      mismatch (closes: #412899).
+    * dbclient uses static "Password:" prompt instead of using the server's
+      prompt (closes: #394996).
+  * debian/control: Suggests: openssh-client, not ssh (closes: #405686);
+    Standards-Version: 3.7.2.2.
+  * debian/README.Debian: ssh -> openssh-server, openssh-client; remove
+    'Replacing OpenSSH "sshd" with Dropbear' part, this is simply done by not
+    installing the openssh-server package.
+  * debian/README.runit: runsvstat -> sv status.
+
+ -- Gerrit Pape <[email protected]>  Fri,  2 Mar 2007 20:48:18 +0000
+
+dropbear (0.48.1-1) unstable; urgency=medium
+
+  * new upstream point release.
+    * Compile fix for scp
+  * debian/diff/dbclient.1.diff: new: document -R option to dbclient
+    accurately (thx Markus Schaber; closes: #351882).
+  * debian/dropbear.README.Debian: document a workaround for systems with
+    possibly blocking /dev/random device (closes: #355414)..
+
+ -- Gerrit Pape <[email protected]>  Sun, 16 Apr 2006 16:16:40 +0000
+
+dropbear (0.48-1) unstable; urgency=medium
 
   * New upstream release.
-  * SECURITY: Fix incorrect buffer sizing.
+  * SECURITY: Improve handling of denial of service attempts from a single
+    IP.
+
+  * debian/implicit: update to revision 1.11.
+  * new upstream release updates to scp from OpenSSH 4.3p2 - fixes a
+    security issue where use of system() could cause users to execute
+    arbitrary code through malformed filenames; CVE-2006-0225 (see also
+    #349645); the scp binary is not provided by this package though.
+
+ -- Gerrit Pape <[email protected]>  Fri, 10 Mar 2006 22:00:32 +0000
+
+dropbear (0.47-1) unstable; urgency=high
+
+  * New upstream release.
+  * SECURITY: Fix incorrect buffer sizing; CVE-2005-4178.
 
  -- Matt Johnston <[email protected]>  Thu, 8 Dec 2005 19:20:21 +0800
 
--- a/debian/control	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/control	Thu Nov 06 13:16:55 2008 +0000
@@ -3,12 +3,12 @@
 Priority: optional
 Maintainer: Gerrit Pape <[email protected]>
 Build-Depends: libz-dev
-Standards-Version: 3.6.2.1
+Standards-Version: 3.7.3.0
 
 Package: dropbear
 Architecture: any
 Depends: ${shlibs:Depends}
-Suggests: ssh, runit
+Suggests: openssh-client, runit
 Description: lightweight SSH2 server and client
  dropbear is a SSH 2 server and client designed to be small enough to
  be used in small memory environments, while still being functional and
--- a/debian/dropbear.README.Debian	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/dropbear.README.Debian	Thu Nov 06 13:16:55 2008 +0000
@@ -1,41 +1,19 @@
 Dropbear for Debian
 -------------------
 
-This package will attempt to listen on port 22. If the OpenSSH 
-package ("ssh") is installed, the file /etc/default/dropbear 
-will be set up so that the server does not start by default.
-
-You can run Dropbear concurrently with OpenSSH 'sshd' by 
-modifying /etc/default/dropbear so that "NO_START" is set to 
-"0" and changing the port number that Dropbear runs on. Follow 
-the instructions in the file.
-
-This package suggests you install the "ssh" package. This package 
-provides the "ssh" client program, as well as the "/usr/bin/scp" 
-binary you will need to be able to retrieve files from a server 
-running Dropbear via SCP.
-
-Replacing OpenSSH "sshd" with Dropbear
---------------------------------------
+This package will attempt to setup the Dropbear ssh server to listen on
+port 22.  If the OpenSSH server package ("openssh-server") is installed,
+the file /etc/default/dropbear will be set up so that the server does not
+start by default.
 
-You will still want to have the "ssh" package installed, as it 
-provides the "ssh" and "scp" binaries. When you install this 
-package, it checks for existing OpenSSH host keys and if found, 
-converts them to the Dropbear format.
-
-If this appears to have worked, you should be able to change over 
-by following these steps:
+You can run Dropbear concurrently with OpenSSH 'sshd' by modifying
+/etc/default/dropbear so that "NO_START" is set to "0", and changing the
+port number that Dropbear runs on.  Follow the instructions in the file.
 
-1. Stop the OpenSSH server
-   % /etc/init.d/ssh stop
-2. Prevent the OpenSSH server from starting in the future
-   % touch /etc/ssh/sshd_not_to_be_run
-3. Modify the Dropbear defaults file, set NO_START to 0 and 
-   ensure DROPBEAR_PORT is set to 22.
-   % editor /etc/default/dropbear
-4. Restart the Dropbear server.
-   % /etc/init.d/dropbear restart
+This package suggests you install the "openssh-client" package, which
+provides the "ssh" client program, as well as the "/usr/bin/scp" binary
+you will need to be able to retrieve files via SCP from a server running
+Dropbear.
 
 See the Dropbear homepage for more information:
   http://matt.ucc.asn.au/dropbear/dropbear.html
-
--- a/debian/dropbear.init	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/dropbear.init	Thu Nov 06 13:16:55 2008 +0000
@@ -1,4 +1,11 @@
 #!/bin/sh
+### BEGIN INIT INFO
+# Provides:          dropbear
+# Required-Start:    $remote_fs $syslog
+# Required-Stop:     $remote_fs $syslog
+# Default-Start:     2 3 4 5
+# Default-Stop:      0 1 6
+### END INIT INFO
 #
 # Do not configure this file. Edit /etc/default/dropbear instead!
 #
@@ -17,8 +24,8 @@
 cancel() { echo "$1" >&2; exit 0; };
 test ! -r /etc/default/dropbear || . /etc/default/dropbear
 test -x "$DAEMON" || cancel "$DAEMON does not exist or is not executable."
-test ! -h /var/service/dropbear || \
-  cancel '/var/service/dropbear exists, service is controlled through runit.'
+test ! -x /usr/sbin/update-service || ! update-service --check dropbear ||
+  cancel 'The dropbear service is controlled through runit, use the sv(8) program'
 
 test -z "$DROPBEAR_BANNER" || \
   DROPBEAR_EXTRA_ARGS="$DROPBEAR_EXTRA_ARGS -b $DROPBEAR_BANNER"
@@ -26,6 +33,8 @@
   DROPBEAR_RSAKEY="/etc/dropbear/dropbear_rsa_host_key"
 test -n "$DROPBEAR_DSSKEY" || \
   DROPBEAR_DSSKEY="/etc/dropbear/dropbear_dss_host_key"
+test -n "$DROPBEAR_RECEIVE_WINDOW" || \
+  DROPBEAR_RECEIVE_WINDOW="65536"
 
 case "$1" in
   start)
@@ -33,7 +42,7 @@
 	echo -n "Starting $DESC: "
 	start-stop-daemon --start --quiet --pidfile /var/run/"$NAME".pid \
 	  --exec "$DAEMON" -- -d "$DROPBEAR_DSSKEY" -r "$DROPBEAR_RSAKEY" \
-	    -p "$DROPBEAR_PORT" $DROPBEAR_EXTRA_ARGS
+	    -p "$DROPBEAR_PORT" -W "$DROPBEAR_RECEIVE_WINDOW" $DROPBEAR_EXTRA_ARGS
 	echo "$NAME."
 	;;
   stop)
@@ -48,7 +57,7 @@
 	sleep 1
 	start-stop-daemon --start --quiet --pidfile /var/run/"$NAME".pid \
 	  --exec "$DAEMON" -- -d "$DROPBEAR_DSSKEY" -r "$DROPBEAR_RSAKEY" \
-	    -p "$DROPBEAR_PORT" $DROPBEAR_EXTRA_ARGS
+	    -p "$DROPBEAR_PORT" -W "$DROPBEAR_RECEIVE_WINDOW" $DROPBEAR_EXTRA_ARGS
 	echo "$NAME."
 	;;
   *)
--- a/debian/dropbear.postinst	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/dropbear.postinst	Thu Nov 06 13:16:55 2008 +0000
@@ -54,6 +54,10 @@
 
 # DSS hostkey file (default: /etc/dropbear/dropbear_dss_host_key)
 #DROPBEAR_DSSKEY="/etc/dropbear/dropbear_dss_host_key"
+
+# Receive window size - this is a tradeoff between memory and
+# network performance
+DROPBEAR_RECEIVE_WINDOW=65536
 EOT
 fi
 
@@ -65,3 +69,11 @@
     /etc/init.d/dropbear restart
   fi
 fi
+
+if test -n "$2" && dpkg --compare-versions "$2" lt '0.50-4' &&
+update-service --check dropbear; then
+  update-service --remove /etc/dropbear 2>/dev/null || :
+  sleep 6
+  rm -rf /var/run/dropbear /var/run/dropbear.log
+  update-service --add /etc/dropbear || :
+fi
--- a/debian/implicit	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/implicit	Thu Nov 06 13:16:55 2008 +0000
@@ -1,4 +1,4 @@
-# $Id: implicit,v 1.10 2004/07/03 15:20:00 pape Exp $
+# $Id: implicit,v 1.11 2005/11/29 21:57:55 pape Exp $
 
 .PHONY: deb-checkdir deb-checkuid
 
@@ -38,6 +38,14 @@
 	@gzip -9 debian/$*/usr/share/doc/$*/changelog*
 %.deb-docs-docs:
 	@for i in `cat debian/$*.docs 2>/dev/null || :`; do \
+	  if test -d $$i; then \
+	    sh -cx "install -d -m0755 debian/$*/usr/share/doc/$*/$${i##*/}" && \
+	    for j in $$i/*; do \
+	      sh -cx "install -m0644 $$j \
+	        debian/$*/usr/share/doc/$*/$${i##*/}/" || exit 1; \
+	    done || exit 1; \
+	    continue; \
+	  fi; \
 	  sh -cx "install -m0644 $$i debian/$*/usr/share/doc/$*/" || exit 1; \
 	done
 	@test ! -r debian/$*.README.Debian || \
--- a/debian/rules	Mon Oct 02 06:40:51 2006 +0000
+++ b/debian/rules	Thu Nov 06 13:16:55 2008 +0000
@@ -28,7 +28,7 @@
 patch: deb-checkdir patch-stamp
 patch-stamp:
 	for i in `ls -1 debian/diff/*.diff || :`; do \
-	  patch -p0 <$$i || exit 1; \
+	  patch -p1 <$$i || exit 1; \
 	done
 	touch patch-stamp
 
@@ -46,10 +46,11 @@
 	touch build-stamp
 
 clean: deb-checkdir deb-checkuid
-	-$(MAKE) distclean
+	test ! -r Makefile || $(MAKE) distclean
+	rm -f libtomcrypt/Makefile libtommath/Makefile
 	test ! -e patch-stamp || \
 	  for i in `ls -1r debian/diff/*.diff || :`; do \
-	    patch -p0 -R <$$i; \
+	    patch -p1 -R <$$i; \
 	  done
 	rm -f patch-stamp build-stamp config.log config.status
 	rm -rf '$(DIR)'
@@ -76,8 +77,6 @@
 	install -d -m0755 '$(DIR)'/etc/dropbear/log
 	install -m0755 debian/service/log '$(DIR)'/etc/dropbear/log/run
 	ln -s /var/log/dropbear '$(DIR)'/etc/dropbear/log/main
-	ln -s /var/run/dropbear '$(DIR)'/etc/dropbear/supervise
-	ln -s /var/run/dropbear.log '$(DIR)'/etc/dropbear/log/supervise
 	# man pages
 	install -d -m0755 '$(DIR)'/usr/share/man/man8
 	for i in dropbear.8 dropbearkey.8; do \
--- a/debug.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/debug.h	Thu Nov 06 13:16:55 2008 +0000
@@ -39,13 +39,15 @@
  * Caution: Don't use this in an unfriendly environment (ie unfirewalled),
  * since the printing may not sanitise strings etc. This will add a reasonable
  * amount to your executable size. */
-/*#define DEBUG_TRACE */
+#define DEBUG_TRACE
 
 /* All functions writing to the cleartext payload buffer call
  * CHECKCLEARTOWRITE() before writing. This is only really useful if you're
  * attempting to track down a problem */
-#define CHECKCLEARTOWRITE() assert(ses.writepayload->len == 0 && \
-		ses.writepayload->pos == 0)
+/*#define CHECKCLEARTOWRITE() assert(ses.writepayload->len == 0 && \
+		ses.writepayload->pos == 0)*/
+
+#define CHECKCLEARTOWRITE()
 
 /* Define this, compile with -pg and set GMON_OUT_PREFIX=gmon to get gmon
  * output when Dropbear forks. This will allow it gprof to be used.
@@ -65,6 +67,11 @@
 #define TRACE(X)
 #endif /*DEBUG_TRACE*/
 
+/* To debug with GDB it is easier to run with no forking of child processes.
+   You will need to pass "-F" as well. */
+/* #define DEBUG_NOFORK */
+
+
 /* For testing as non-root on shadowed systems, include the crypt of a password
  * here. You can then log in as any user with this password. Ensure that you
  * make your own password, and are careful about using this. This will also
--- a/dropbear.8	Mon Oct 02 06:40:51 2006 +0000
+++ b/dropbear.8	Thu Nov 06 13:16:55 2008 +0000
@@ -60,9 +60,13 @@
 .B \-k
 Disable remote port forwarding.
 .TP
-.B \-p \fIport
-Listen on specified tcp port
-.IR port ;
+.B \-p \fI[address:]port
+Listen on specified 
+.I address
+and TCP
+.I port.
+If just a port is given listen
+on all addresses.
 up to 10 can be specified (default 22 if none specified).
 .TP
 .B \-i
@@ -72,8 +76,78 @@
 under TCP/IP servers like inetd, tcpsvd, or tcpserver.
 In program mode the \-F option is implied, and \-p options are ignored.
 .TP
+.B \-P \fIpidfile
+Specify a pidfile to create when running as a daemon. If not specified, the 
+default is /var/run/dropbear.pid
+.TP
 .B \-a
 Allow remote hosts to connect to forwarded ports.
+.TP
+.B \-W \fIwindowsize
+Specify the per-channel receive window buffer size. Increasing this 
+may improve network performance at the expense of memory use. Use -h to see the
+default buffer size.
+.TP
+.B \-K \fItimeout_seconds
+Ensure that traffic is transmitted at a certain interval in seconds. This is
+useful for working around firewalls or routers that drop connections after
+a certain period of inactivity. The trade-off is that a session may be
+closed if there is a temporary lapse of network connectivity. A setting
+if 0 disables keepalives.
+.SH FILES
+
+.TP
+Authorized Keys
+
+~/.ssh/authorized_keys can be set up to allow remote login with a RSA or DSS
+key. Each line is of the form
+.TP
+[restrictions] ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIgAsp... [comment]
+
+and can be extracted from a Dropbear private host key with "dropbearkey -y". This is the same format as used by OpenSSH, though the restrictions are a subset (keys with unknown restrictions are ignored).
+Restrictions are comma separated, with double quotes around spaces in arguments.
+Available restrictions are:
+
+.TP
+.B no-port-forwarding
+Don't allow port forwarding for this connection
+
+.TP
+.B no-agent-forwarding
+Don't allow agent forwarding for this connection
+
+.TP
+.B no-X11-forwarding
+Don't allow X11 forwarding for this connection
+
+.TP
+.B no-pty
+Disable PTY allocation. Note that a user can still obtain most of the
+same functionality with other means even if no-pty is set.
+
+.TP
+.B command="\fIforced_command\fR"
+Disregard the command provided by the user and always run \fIforced_command\fR.
+
+The authorized_keys file and its containing ~/.ssh directory must only be
+writable by the user, otherwise Dropbear will not allow a login using public
+key authentication.
+
+.TP
+Host Key Files
+
+Host key files are read at startup from a standard location, by default
+/etc/dropbear/dropbear_dss_host_key and /etc/dropbear/dropbear_rsa_host_key
+or specified on the commandline with -d or -r. These are of the form generated
+by dropbearkey.
+
+.TP
+Message Of The Day
+
+By default the file /etc/motd will be printed for any login shell (unless 
+disabled at compile-time). This can also be disabled per-user
+by creating a file ~/.hushlogin .
+
 .SH AUTHOR
 Matt Johnston ([email protected]).
 .br
--- a/dropbearkey.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/dropbearkey.c	Thu Nov 06 13:16:55 2008 +0000
@@ -75,6 +75,7 @@
 #endif
 					"-f filename	Use filename for the secret key\n"
 					"-s bits	Key size in bits, should be a multiple of 8 (optional)\n"
+					"           (DSS has a fixed size of 1024 bits)\n"
 					"-y		Just print the publickey and fingerprint for the\n		private key in <filename>.\n"
 #ifdef DEBUG_TRACE
 					"-v		verbose\n"
@@ -187,8 +188,11 @@
 			fprintf(stderr, "Bits must be an integer\n");
 			exit(EXIT_FAILURE);
 		}
-	
-		if (bits < 512 || bits > 4096 || (bits % 8 != 0)) {
+		
+		if (keytype == DROPBEAR_SIGNKEY_DSS && bits != 1024) {
+			fprintf(stderr, "DSS keys have a fixed size of 1024 bits\n");
+			exit(EXIT_FAILURE);			
+		} else if (bits < 512 || bits > 4096 || (bits % 8 != 0)) {
 			fprintf(stderr, "Bits must satisfy 512 <= bits <= 4096, and be a"
 					" multiple of 8\n");
 			exit(EXIT_FAILURE);
@@ -283,8 +287,10 @@
 	buf_burn(buf);
 	buf_free(buf);
 	buf = NULL;
-	sign_key_free(key);
-	key = NULL;
+	if (key) {
+		sign_key_free(key);
+		key = NULL;
+	}
 	exit(err);
 }
 
@@ -297,6 +303,9 @@
 	const char * typestring = NULL;
 	char *fp = NULL;
 	int len;
+	struct passwd * pw = NULL;
+	char * username = NULL;
+	char hostname[100];
 
 	buf = buf_new(MAX_PUBKEY_SIZE);
 	buf_put_pub_key(buf, key, keytype);
@@ -315,8 +324,18 @@
 
 	fp = sign_key_fingerprint(buf_getptr(buf, len), len);
 
-	printf("Public key portion is:\n%s %s\nFingerprint: %s\n",
-			typestring, base64key, fp);
+	/* a [email protected] comment is informative */
+	username = "";
+	pw = getpwuid(getuid());
+	if (pw) {
+		username = pw->pw_name;
+	}
+
+	gethostname(hostname, sizeof(hostname));
+	hostname[sizeof(hostname)-1] = '\0';
+
+	printf("Public key portion is:\n%s %s %[email protected]%s\nFingerprint: %s\n",
+			typestring, base64key, username, hostname, fp);
 
 	m_free(fp);
 	buf_free(buf);
--- a/dss.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/dss.c	Thu Nov 06 13:16:55 2008 +0000
@@ -90,6 +90,9 @@
 	key->x = m_malloc(sizeof(mp_int));
 	m_mp_init(key->x);
 	ret = buf_getmpint(buf, key->x);
+	if (ret == DROPBEAR_FAILURE) {
+		m_free(key->x);
+	}
 
 	return ret;
 }
@@ -338,7 +341,9 @@
 	/* generate k */
 	m_mp_init(&dss_protok);
 	bytes_to_mp(&dss_protok, proto_k, SHA512_HASH_SIZE);
-	mp_mod(&dss_protok, key->q, &dss_k);
+	if (mp_mod(&dss_protok, key->q, &dss_k) != MP_OKAY) {
+		dropbear_exit("dss error");
+	}
 	mp_clear(&dss_protok);
 	m_burn(proto_k, SHA512_HASH_SIZE);
 #else /* DSS_PROTOK not defined*/
--- a/genrsa.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/genrsa.c	Thu Nov 06 13:16:55 2008 +0000
@@ -62,17 +62,13 @@
 		exit(1);
 	}
 
-	/* PuTTY doesn't like it if the modulus isn't a multiple of 8 bits,
-	 * so we just generate them until we get one which is OK */
 	getrsaprime(key->p, &pminus, key->e, size/2);
-	do {
-		getrsaprime(key->q, &qminus, key->e, size/2);
+	getrsaprime(key->q, &qminus, key->e, size/2);
 
-		if (mp_mul(key->p, key->q, key->n) != MP_OKAY) {
-			fprintf(stderr, "rsa generation failed\n");
-			exit(1);
-		}
-	} while (mp_count_bits(key->n) % 8 != 0);
+	if (mp_mul(key->p, key->q, key->n) != MP_OKAY) {
+		fprintf(stderr, "rsa generation failed\n");
+		exit(1);
+	}
 
 	/* lcm(p-1, q-1) */
 	if (mp_lcm(&pminus, &qminus, &lcm) != MP_OKAY) {
--- a/includes.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/includes.h	Thu Nov 06 13:16:55 2008 +0000
@@ -38,6 +38,7 @@
 #include <sys/time.h>
 #include <sys/un.h>
 #include <sys/wait.h>
+#include <sys/resource.h>
 
 #include <stdio.h>
 #include <errno.h>
@@ -55,6 +56,7 @@
 #include <ctype.h>
 #include <stdarg.h>
 #include <dirent.h>
+#include <time.h>
 
 #ifdef HAVE_UTMP_H
 #include <utmp.h>
@@ -72,12 +74,12 @@
 #include <lastlog.h>
 #endif
 
-#include <arpa/inet.h>
-
 #ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
 #endif
 
+#include <arpa/inet.h>
+
 /* netbsd 1.6 needs this to be included before netinet/ip.h for some
  * undocumented reason */
 #ifdef HAVE_NETINET_IN_SYSTM_H
@@ -135,13 +137,6 @@
 #define LOG_AUTHPRIV LOG_AUTH
 #endif
 
-/* glibc 2.1.3 systems have sockaddr_storage.__ss_family rather than
- * sockaddr_storage.ss_family */
-#if !defined(HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
-    && defined(HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY)
-#define ss_family __ss_family
-#endif
-
 /* so we can avoid warnings about unused params (ie in signal handlers etc) */
 #ifdef UNUSED 
 #elif defined(__GNUC__) 
--- a/kex.h	Mon Oct 02 06:40:51 2006 +0000
+++ b/kex.h	Thu Nov 06 13:16:55 2008 +0000
@@ -37,6 +37,11 @@
 void kexdh_comb_key(mp_int *dh_pub_us, mp_int *dh_priv, mp_int *dh_pub_them,
 		sign_key *hostkey);
 
+#ifndef DISABLE_ZLIB
+int is_compress_trans();
+int is_compress_recv();
+#endif
+
 void recv_msg_kexdh_init(); /* server */
 
 void send_msg_kexdh_init(); /* client */
@@ -53,7 +58,7 @@
 	unsigned donefirstkex : 1; /* Set to 1 after the first kex has completed,
 								  ie the transport layer has been set up */
 
-	long lastkextime; /* time of the last kex */
+	time_t lastkextime; /* time of the last kex */
 	unsigned int datatrans; /* data transmitted since last kex */
 	unsigned int datarecv; /* data received since last kex */
 
--- a/keyimport.c	Mon Oct 02 06:40:51 2006 +0000
+++ b/keyimport.c	Thu Nov 06 13:16:55 2008 +0000
@@ -361,7 +361,7 @@
 static struct openssh_key *load_openssh_key(const char *filename)
 {
 	struct openssh_key *ret;
-	FILE *fp;
+	FILE *fp = NULL;
 	char buffer[256];
 	char *errmsg = NULL, *p = NULL;
 	int headers_done;
@@ -482,6 +482,9 @@
 		memset(&ret, 0, sizeof(ret));
 		m_free(ret);
 	}
+	if (fp) {
+		fclose(fp);
+	}
 	if (errmsg) {
 		fprintf(stderr, "Error: %s\n", errmsg);
 	}
@@ -698,7 +701,6 @@
 	int nnumbers = -1, pos, len, seqlen, i;
 	char *header = NULL, *footer = NULL;
 	char zero[1];
-	unsigned char iv[8];
 	int ret = 0;
 	FILE *fp;
 	int keytype = -1;
@@ -926,40 +928,6 @@
 	if (passphrase) {
 		fprintf(stderr, "Encrypted keys aren't supported currently\n");
 		goto error;
-#if 0
-		/*
-		 * Invent an iv. Then derive encryption key from passphrase
-		 * and iv/salt:
-		 * 
-		 *  - let block A equal MD5(passphrase || iv)
-		 *  - let block B equal MD5(A || passphrase || iv)
-		 *  - block C would be MD5(B || passphrase || iv) and so on
-		 *  - encryption key is the first N bytes of A || B
-		 */
-		struct MD5Context md5c;
-		unsigned char keybuf[32];
-
-		for (i = 0; i < 8; i++) iv[i] = random_byte();
-
-		MD5Init(&md5c);
-		MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
-		MD5Update(&md5c, iv, 8);
-		MD5Final(keybuf, &md5c);
-
-		MD5Init(&md5c);
-		MD5Update(&md5c, keybuf, 16);
-		MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
-		MD5Update(&md5c, iv, 8);
-		MD5Final(keybuf+16, &md5c);
-
-		/*
-		 * Now encrypt the key blob.
-		 */
-		des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
-
-		memset(&md5c, 0, sizeof(md5c));
-		memset(keybuf, 0, sizeof(keybuf));
-#endif
 	}
 
 	/*
@@ -976,12 +944,6 @@
 		goto error;
 	}
 	fputs(header, fp);
-	if (passphrase) {
-		fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
-		for (i = 0; i < 8; i++)
-			fprintf(fp, "%02X", iv[i]);
-		fprintf(fp, "\n\n");
-	}
 	base64_encode_fp(fp, outblob, outlen, 64);
 	fputs(footer, fp);
 	fclose(fp);
--- a/libtomcrypt/Doxyfile	Mon Oct 02 06:40:51 2006 +0000
+++ b/libtomcrypt/Doxyfile	Thu Nov 06 13:16:55 2008 +0000
@@ -23,7 +23,7 @@
 # This could be handy for archiving the generated documentation or 
 # if some version control system is used.
 
-PROJECT_NUMBER         = 1.05
+PROJECT_NUMBER         = 1.16
 
 # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) 
 # base path where the generated documentation will be put. 
@@ -1028,14 +1028,14 @@
 # inheritance and usage relations if the target is undocumented 
 # or is not a class.
 
-HIDE_UNDOC_RELATIONS   = YES
+HIDE_UNDOC_RELATIONS   = NO
 
 # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is 
 # available from the path. This tool is part of Graphviz, a graph visualization 
 # toolkit from AT&T and Lucent Bell Labs. The other options in this section 
 # have no effect if this option is set to NO (the default)
 
-HAVE_DOT               = YES
+HAVE_DOT               = NO
 
 # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen 
 # will generate a graph for each documented class showing the direct and 
--- a/libtomcrypt/Makefile.in	Mon Oct 02 06:40:51 2006 +0000
+++ b/libtomcrypt/Makefile.in	Thu Nov 06 13:16:55 2008 +0000
@@ -4,7 +4,7 @@
 # Modified by Clay Culver
 
 # The version
-VERSION=1.05
+VERSION=1.16
 
 [email protected]@
 [email protected]@
@@ -22,8 +22,12 @@
 CFLAGS += -c -I$(srcdir)/src/headers/ -I$(srcdir)/../
 
 # additional warnings (newer GCC 3.4 and higher)
-#CFLAGS += -Wsystem-headers -Wdeclaration-after-statement -Wbad-function-cast -Wcast-align -Wstrict-prototypes -Wmissing-prototypes \
-#		  -Wmissing-declarations -Wpointer-arith 
+ifdef GCC_34
+CFLAGS += -Wsystem-headers -Wdeclaration-after-statement -Wbad-function-cast -Wcast-align -Wstrict-prototypes -Wmissing-prototypes \
+		  -Wmissing-declarations -Wpointer-arith 
+endif
+
+ifndef IGNORE_SPEED
 
 # optimize for SPEED
 #CFLAGS += -O3 -funroll-loops
@@ -34,6 +38,8 @@
 # optimize for SIZE
 #CFLAGS += -Os -DLTC_SMALL_CODE
 
+endif
+
 # older GCCs can't handle the "rotate with immediate" ROLc/RORc/etc macros
 # define this to help
 #CFLAGS += -DLTC_NO_ROLC
@@ -42,8 +48,14 @@
 #CFLAGS += -g3 -DLTC_NO_ASM
 
 #Output filenames for various targets.
-LIBNAME=libtomcrypt.a
-LIBTEST=testprof/libtomcrypt_prof.a
+ifndef LIBNAME
+   LIBNAME=libtomcrypt.a
+endif
+ifndef LIBTEST
+   LIBTEST=libtomcrypt_prof.a
+endif
+LIBTEST_S=$(LIBTEST)
+
 HASH=hashsum
 CRYPT=encrypt
 SMALL=small
@@ -56,10 +68,19 @@
 #LIBPATH-The directory for libtomcrypt to be installed to.
 #INCPATH-The directory to install the header files for libtomcrypt.
 #DATAPATH-The directory to install the pdf docs.
-DESTDIR=
-LIBPATH=/usr/lib
-INCPATH=/usr/include
-DATAPATH=/usr/share/doc/libtomcrypt/pdf
+ifndef DESTDIR
+   DESTDIR=
+endif
+
+ifndef LIBPATH
+   LIBPATH=/usr/lib
+endif
+ifndef INCPATH
+   INCPATH=/usr/include
+endif
+ifndef DATAPATH
+   DATAPATH=/usr/share/doc/libtomcrypt/pdf
+endif
 
 #Who do we install as?
 ifdef INSTALL_USER
@@ -75,15 +96,10 @@
 endif
 
 #List of objects to compile.
-
-#Leave MPI built-in or force developer to link against libtommath?
-#MPIOBJECT=src/misc/mpi/mpi.o
-#Dropbear uses libtommath
-MPIOBJECT=
-
-OBJECTS=src/ciphers/aes/aes_enc.o $(MPIOBJECT) src/ciphers/aes/aes.o src/ciphers/anubis.o \
-src/ciphers/blowfish.o src/ciphers/cast5.o src/ciphers/des.o src/ciphers/khazad.o src/ciphers/noekeon.o \
-src/ciphers/rc2.o src/ciphers/rc5.o src/ciphers/rc6.o src/ciphers/safer/safer.o \
+#START_INS
+OBJECTS=src/ciphers/aes/aes_enc.o src/ciphers/aes/aes.o src/ciphers/anubis.o src/ciphers/blowfish.o \
+src/ciphers/cast5.o src/ciphers/des.o src/ciphers/kasumi.o src/ciphers/khazad.o src/ciphers/kseed.o \
+src/ciphers/noekeon.o src/ciphers/rc2.o src/ciphers/rc5.o src/ciphers/rc6.o src/ciphers/safer/safer.o \
 src/ciphers/safer/safer_tab.o src/ciphers/safer/saferp.o src/ciphers/skipjack.o \
 src/ciphers/twofish/twofish.o src/ciphers/xtea.o src/encauth/ccm/ccm_memory.o \
 src/encauth/ccm/ccm_test.o src/encauth/eax/eax_addheader.o src/encauth/eax/eax_decrypt.o \
@@ -91,52 +107,65 @@
 src/encauth/eax/eax_encrypt_authenticate_memory.o src/encauth/eax/eax_init.o \
 src/encauth/eax/eax_test.o src/encauth/gcm/gcm_add_aad.o src/encauth/gcm/gcm_add_iv.o \
 src/encauth/gcm/gcm_done.o src/encauth/gcm/gcm_gf_mult.o src/encauth/gcm/gcm_init.o \
-src/encauth/gcm/gcm_memory.o src/encauth/gcm/gcm_process.o src/encauth/gcm/gcm_reset.o \
-src/encauth/gcm/gcm_test.o src/encauth/ocb/ocb_decrypt.o src/encauth/ocb/ocb_decrypt_verify_memory.o \
-src/encauth/ocb/ocb_done_decrypt.o src/encauth/ocb/ocb_done_encrypt.o src/encauth/ocb/ocb_encrypt.o \
+src/encauth/gcm/gcm_memory.o src/encauth/gcm/gcm_mult_h.o src/encauth/gcm/gcm_process.o \
+src/encauth/gcm/gcm_reset.o src/encauth/gcm/gcm_test.o src/encauth/ocb/ocb_decrypt.o \
+src/encauth/ocb/ocb_decrypt_verify_memory.o src/encauth/ocb/ocb_done_decrypt.o \
+src/encauth/ocb/ocb_done_encrypt.o src/encauth/ocb/ocb_encrypt.o \
 src/encauth/ocb/ocb_encrypt_authenticate_memory.o src/encauth/ocb/ocb_init.o src/encauth/ocb/ocb_ntz.o \
 src/encauth/ocb/ocb_shift_xor.o src/encauth/ocb/ocb_test.o src/encauth/ocb/s_ocb_done.o \
 src/hashes/chc/chc.o src/hashes/helper/hash_file.o src/hashes/helper/hash_filehandle.o \
 src/hashes/helper/hash_memory.o src/hashes/helper/hash_memory_multi.o src/hashes/md2.o src/hashes/md4.o \
-src/hashes/md5.o src/hashes/rmd128.o src/hashes/rmd160.o src/hashes/sha1.o src/hashes/sha2/sha256.o \
-src/hashes/sha2/sha512.o src/hashes/tiger.o src/hashes/whirl/whirl.o src/mac/hmac/hmac_done.o \
-src/mac/hmac/hmac_file.o src/mac/hmac/hmac_init.o src/mac/hmac/hmac_memory.o \
+src/hashes/md5.o src/hashes/rmd128.o src/hashes/rmd160.o src/hashes/rmd256.o src/hashes/rmd320.o \
+src/hashes/sha1.o src/hashes/sha2/sha256.o src/hashes/sha2/sha512.o src/hashes/tiger.o \
+src/hashes/whirl/whirl.o src/mac/f9/f9_done.o src/mac/f9/f9_file.o src/mac/f9/f9_init.o \
+src/mac/f9/f9_memory.o src/mac/f9/f9_memory_multi.o src/mac/f9/f9_process.o src/mac/f9/f9_test.o \
+src/mac/hmac/hmac_done.o src/mac/hmac/hmac_file.o src/mac/hmac/hmac_init.o src/mac/hmac/hmac_memory.o \
 src/mac/hmac/hmac_memory_multi.o src/mac/hmac/hmac_process.o src/mac/hmac/hmac_test.o \
 src/mac/omac/omac_done.o src/mac/omac/omac_file.o src/mac/omac/omac_init.o src/mac/omac/omac_memory.o \
 src/mac/omac/omac_memory_multi.o src/mac/omac/omac_process.o src/mac/omac/omac_test.o \
 src/mac/pelican/pelican.o src/mac/pelican/pelican_memory.o src/mac/pelican/pelican_test.o \
 src/mac/pmac/pmac_done.o src/mac/pmac/pmac_file.o src/mac/pmac/pmac_init.o src/mac/pmac/pmac_memory.o \
 src/mac/pmac/pmac_memory_multi.o src/mac/pmac/pmac_ntz.o src/mac/pmac/pmac_process.o \
-src/mac/pmac/pmac_shift_xor.o src/mac/pmac/pmac_test.o src/misc/base64/base64_decode.o \
+src/mac/pmac/pmac_shift_xor.o src/mac/pmac/pmac_test.o src/mac/xcbc/xcbc_done.o \
+src/mac/xcbc/xcbc_file.o src/mac/xcbc/xcbc_init.o src/mac/xcbc/xcbc_memory.o \
+src/mac/xcbc/xcbc_memory_multi.o src/mac/xcbc/xcbc_process.o src/mac/xcbc/xcbc_test.o \
+src/math/fp/ltc_ecc_fp_mulmod.o src/math/gmp_desc.o src/math/ltm_desc.o src/math/multi.o \
+src/math/rand_prime.o src/math/tfm_desc.o src/misc/base64/base64_decode.o \
 src/misc/base64/base64_encode.o src/misc/burn_stack.o src/misc/crypt/crypt.o \
 src/misc/crypt/crypt_argchk.o src/misc/crypt/crypt_cipher_descriptor.o \
 src/misc/crypt/crypt_cipher_is_valid.o src/misc/crypt/crypt_find_cipher.o \
 src/misc/crypt/crypt_find_cipher_any.o src/misc/crypt/crypt_find_cipher_id.o \
 src/misc/crypt/crypt_find_hash.o src/misc/crypt/crypt_find_hash_any.o \
-src/misc/crypt/crypt_find_hash_id.o src/misc/crypt/crypt_find_prng.o \
-src/misc/crypt/crypt_hash_descriptor.o src/misc/crypt/crypt_hash_is_valid.o \
+src/misc/crypt/crypt_find_hash_id.o src/misc/crypt/crypt_find_hash_oid.o \
+src/misc/crypt/crypt_find_prng.o src/misc/crypt/crypt_fsa.o src/misc/crypt/crypt_hash_descriptor.o \
+src/misc/crypt/crypt_hash_is_valid.o src/misc/crypt/crypt_ltc_mp_descriptor.o \
 src/misc/crypt/crypt_prng_descriptor.o src/misc/crypt/crypt_prng_is_valid.o \
 src/misc/crypt/crypt_register_cipher.o src/misc/crypt/crypt_register_hash.o \
 src/misc/crypt/crypt_register_prng.o src/misc/crypt/crypt_unregister_cipher.o \
 src/misc/crypt/crypt_unregister_hash.o src/misc/crypt/crypt_unregister_prng.o \
-src/misc/error_to_string.o src/misc/mpi/is_prime.o src/misc/mpi/mpi_to_ltc_error.o \
-src/misc/mpi/rand_prime.o src/misc/pkcs5/pkcs_5_1.o src/misc/pkcs5/pkcs_5_2.o src/misc/zeromem.o \
+src/misc/error_to_string.o src/misc/pkcs5/pkcs_5_1.o src/misc/pkcs5/pkcs_5_2.o src/misc/zeromem.o \
 src/modes/cbc/cbc_decrypt.o src/modes/cbc/cbc_done.o src/modes/cbc/cbc_encrypt.o \
 src/modes/cbc/cbc_getiv.o src/modes/cbc/cbc_setiv.o src/modes/cbc/cbc_start.o \
 src/modes/cfb/cfb_decrypt.o src/modes/cfb/cfb_done.o src/modes/cfb/cfb_encrypt.o \
 src/modes/cfb/cfb_getiv.o src/modes/cfb/cfb_setiv.o src/modes/cfb/cfb_start.o \
 src/modes/ctr/ctr_decrypt.o src/modes/ctr/ctr_done.o src/modes/ctr/ctr_encrypt.o \
-src/modes/ctr/ctr_getiv.o src/modes/ctr/ctr_setiv.o src/modes/ctr/ctr_start.o \
+src/modes/ctr/ctr_getiv.o src/modes/ctr/ctr_setiv.o src/modes/ctr/ctr_start.o src/modes/ctr/ctr_test.o \
 src/modes/ecb/ecb_decrypt.o src/modes/ecb/ecb_done.o src/modes/ecb/ecb_encrypt.o \
-src/modes/ecb/ecb_start.o src/modes/ofb/ofb_decrypt.o src/modes/ofb/ofb_done.o \
+src/modes/ecb/ecb_start.o src/modes/f8/f8_decrypt.o src/modes/f8/f8_done.o src/modes/f8/f8_encrypt.o \
+src/modes/f8/f8_getiv.o src/modes/f8/f8_setiv.o src/modes/f8/f8_start.o src/modes/f8/f8_test_mode.o \
+src/modes/lrw/lrw_decrypt.o src/modes/lrw/lrw_done.o src/modes/lrw/lrw_encrypt.o \
+src/modes/lrw/lrw_getiv.o src/modes/lrw/lrw_process.o src/modes/lrw/lrw_setiv.o \
+src/modes/lrw/lrw_start.o src/modes/lrw/lrw_test.o src/modes/ofb/ofb_decrypt.o src/modes/ofb/ofb_done.o \
 src/modes/ofb/ofb_encrypt.o src/modes/ofb/ofb_getiv.o src/modes/ofb/ofb_setiv.o \
 src/modes/ofb/ofb_start.o 
 
-HEADERS=src/headers/tommath_superclass.h src/headers/tomcrypt_cfg.h src/headers/tomcrypt_mac.h \
-src/headers/tomcrypt_macros.h src/headers/tomcrypt_custom.h src/headers/tomcrypt_argchk.h \
-src/headers/tomcrypt_cipher.h src/headers/tomcrypt_pk.h src/headers/tommath_class.h \
-src/headers/ltc_tommath.h src/headers/tomcrypt_hash.h src/headers/tomcrypt_misc.h \
-src/headers/tomcrypt.h src/headers/tomcrypt_pkcs.h src/headers/tomcrypt_prng.h testprof/tomcrypt_test.h
+HEADERS=src/headers/tomcrypt_cfg.h src/headers/tomcrypt_mac.h src/headers/tomcrypt_macros.h \
+src/headers/tomcrypt_custom.h src/headers/tomcrypt_argchk.h src/headers/tomcrypt_cipher.h \
+src/headers/tomcrypt_pk.h src/headers/tomcrypt_hash.h src/headers/tomcrypt_math.h \
+src/headers/tomcrypt_misc.h src/headers/tomcrypt.h src/headers/tomcrypt_pkcs.h \
+src/headers/tomcrypt_prng.h testprof/tomcrypt_test.h
+
+#END_INS
 
 TESTOBJECTS=demos/test.o
 HASHOBJECTS=demos/hashsum.o
@@ -158,73 +187,76 @@
 
 #ciphers come in two flavours... enc+dec and enc 
 src/ciphers/aes/aes_enc.o: src/ciphers/aes/aes.c src/ciphers/aes/aes_tab.c
-	$(CC) $(CFLAGS) -DENCRYPT_ONLY -c src/ciphers/aes/aes.c -o src/ciphers/aes/aes_enc.o
+	$(CC) $(CFLAGS) -DENCRYPT_ONLY -c $< -o src/ciphers/aes/aes_enc.o
 
 #These are the rules to make certain object files.
 src/ciphers/aes/aes.o: src/ciphers/aes/aes.c src/ciphers/aes/aes_tab.c
 src/ciphers/twofish/twofish.o: src/ciphers/twofish/twofish.c src/ciphers/twofish/twofish_tab.c
 src/hashes/whirl/whirl.o: src/hashes/whirl/whirl.c src/hashes/whirl/whirltab.c
-src/pk/ecc/ecc.o: src/pk/ecc/ecc.c src/pk/ecc/ecc_sys.c
-src/pk/dh/dh.o: src/pk/dh/dh.c src/pk/dh/dh_sys.c
 src/hashes/sha2/sha512.o: src/hashes/sha2/sha512.c src/hashes/sha2/sha384.c
 src/hashes/sha2/sha256.o: src/hashes/sha2/sha256.c src/hashes/sha2/sha224.c
 
 #This rule makes the libtomcrypt library.
 library: $(LIBNAME)
 
-$(LIBTEST): 
-	cd testprof ; CFLAGS="$(CFLAGS)" make 
+testprof/$(LIBTEST): 
+	cd testprof ; CFLAGS="$(CFLAGS)" LIBTEST_S=$(LIBTEST_S) $(MAKE) 
 
 $(LIBNAME): $(OBJECTS)
 	$(AR) $(ARFLAGS) [email protected] $(OBJECTS) 
-	$(RANLIB) $(LIBNAME)
+	$(RANLIB) [email protected]
 
 #This rule makes the hash program included with libtomcrypt
 hashsum: library $(HASHOBJECTS)
-	$(CC) $(HASHOBJECTS) $(LIBNAME) -o $(HASH) $(WARN)
+	$(CC) $(HASHOBJECTS) $(LIBNAME) $(EXTRALIBS) -o $(HASH) $(WARN)
 
 #makes the crypt program
 crypt: library $(CRYPTOBJECTS)
-	$(CC) $(CRYPTOBJECTS) $(LIBNAME) -o $(CRYPT) $(WARN)
+	$(CC) $(CRYPTOBJECTS) $(LIBNAME) $(EXTRALIBS) -o $(CRYPT) $(WARN)
 
 #makes the small program
 small: library $(SMALLOBJECTS)
-	$(CC) $(SMALLOBJECTS) $(LIBNAME) -o $(SMALL) $(WARN)
+	$(CC) $(SMALLOBJECTS) $(LIBNAME) $(EXTRALIBS) -o $(SMALL) $(WARN)
 	
 tv_gen: library $(TVS)
-	$(CC) $(TVS) $(LIBNAME) -o $(TV)
+	$(CC) $(LDFLAGS) $(TVS) $(LIBNAME) $(EXTRALIBS) -o $(TV)
 
 multi: library $(MULTIS)
-	$(CC) $(MULTIS) $(LIBNAME) -o $(MULTI)
+	$(CC) $(MULTIS) $(LIBNAME) $(EXTRALIBS) -o $(MULTI)
 
-timing: library $(LIBTEST) $(TIMINGS)
-	$(CC) $(TIMINGS) $(LIBTEST) $(LIBNAME) $(EXTRALIBS) -o $(TIMING)
+timing: library testprof/$(LIBTEST) $(TIMINGS)
+	$(CC) $(LDFLAGS) $(TIMINGS) testprof/$(LIBTEST) $(LIBNAME) $(EXTRALIBS) -o $(TIMING)
 
-test: library $(LIBTEST) $(TESTS)
-	$(CC) $(TESTS) $(LIBTEST) $(LIBNAME) -o $(TEST)
-
+test: library testprof/$(LIBTEST) $(TESTS)
+	$(CC) $(LDFLAGS) $(TESTS) testprof/$(LIBTEST) $(LIBNAME) $(EXTRALIBS) -o $(TEST)
 
 #This rule installs the library and the header files. This must be run
 #as root in order to have a high enough permission to write to the correct
 #directories and to set the owner and group to root.
+ifndef NODOCS
 install: library docs
+else
+install: library
+endif
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(LIBPATH)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(INCPATH)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(DATAPATH)
 	install -g $(GROUP) -o $(USER) $(LIBNAME) $(DESTDIR)$(LIBPATH)
 	install -g $(GROUP) -o $(USER) $(HEADERS) $(DESTDIR)$(INCPATH)
+ifndef NODOCS
 	install -g $(GROUP) -o $(USER) doc/crypt.pdf $(DESTDIR)$(DATAPATH)
+endif
 
-install_test: $(LIBTEST)
+install_test: testprof/$(LIBTEST)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(LIBPATH)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(INCPATH)
-	install -g $(GROUP) -o $(USER) $(LIBTEST) $(DESTDIR)$(LIBPATH)
+	install -g $(GROUP) -o $(USER) testprof/$(LIBTEST) $(DESTDIR)$(LIBPATH)
 
 profile:
-	CFLAGS="$(CFLAGS) -fprofile-generate" make timing EXTRALIBS=-lgcov
+	CFLAGS="$(CFLAGS) -fprofile-generate" $(MAKE) timing EXTRALIBS="$(EXTRALIBS) -lgcov"
 	./timing
 	rm -f timing `find . -type f | grep [.][ao] | xargs`
-	CFLAGS="$(CFLAGS) -fprofile-use" make timing EXTRALIBS=-lgcov
+	CFLAGS="$(CFLAGS) -fprofile-use" $(MAKE) timing EXTRALIBS="$(EXTRALIBS) -lgcov"
 
 
 #This rule cleans the source tree of all compiled code, not including the pdf
@@ -236,7 +268,7 @@
 #build the doxy files (requires Doxygen, tetex and patience)
 doxy:
 	doxygen
-	cd doc/doxygen/latex ; make ; mv -f refman.pdf ../../.
+	cd doc/doxygen/latex ; ${MAKE} ; mv -f refman.pdf ../../.
 	echo The huge doxygen PDF should be available as doc/refman.pdf
 	
 #This builds the crypt.pdf file. Note that the rm -f *.pdf has been removed
@@ -249,6 +281,7 @@
 	latex crypt > /dev/null
 	latex crypt > /dev/null
 	makeindex crypt.idx > /dev/null
+	perl fixupind.pl
 	latex crypt > /dev/null
 	dvipdf crypt
 	mv -ivf crypt.pdf doc/crypt.pdf
@@ -259,6 +292,8 @@
 	latex crypt > /dev/null
 	latex crypt > /dev/null
 	makeindex crypt.idx
+	perl fixupind.pl
+	latex crypt > /dev/null
 	latex crypt > /dev/null
 
 #zipup the project (take that!)
@@ -278,5 +313,5 @@
 
 
 # $Source: /cvs/libtom/libtomcrypt/makefile,v $ 
-# $Revision: 1.70 $ 
-# $Date: 2005/06/19 18:03:24 $ 
+# $Revision: 1.145 $ 
+# $Date: 2006/12/02 19:23:21 $ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libtomcrypt/README	Thu Nov 06 13:16:55 2008 +0000
@@ -0,0 +1,3 @@
+See doc/crypt.pdf
+
+
--- a/libtomcrypt/TODO	Mon Oct 02 06:40:51 2006 +0000
+++ b/libtomcrypt/TODO	Thu Nov 06 13:16:55 2008 +0000
@@ -1,10 +1,11 @@
-For 1.06
+stopped at ch12
+-- needs examples for ecc/dsa!!! (and for asn.1)
 
-1. export ECC functions globally [e.g. mulmod and the sets]
-   - goal is tv_gen module and test vectors
-2. ASN.1 SET and T61String
-3. phase out DH code [RSA/ECC/DSA is enough]
-4. Some ASN.1 demo programs [for now read the source code!]
-5. Start working towards making the bignum code plugable
-6. Look into other ECC point muls and consider a "precomp" interface 
-7. Add OID for ciphers and PRNGs to their descriptors
+must have for v1.16
+- document PK build flags
+- document makefile flags [INSTALL_* for instance]
+- prepare manual for printing (both soft and hard cover)
+
+Nice to have [in order of precedence]
+- add X9.63 IES
+- add CPP macros like OpenSSL has for ASN1 (e.g. encode/decode functions, etc) shameless ripoff :-)
--- a/libtomcrypt/build.sh	Mon Oct 02 06:40:51 2006 +0000
+++ b/libtomcrypt/build.sh	Thu Nov 06 13:16:55 2008 +0000
@@ -2,12 +2,12 @@
 echo "$1 ($2, $3)..."
 make clean 1>/dev/null 2>/dev/null
 echo -n "building..."
-CFLAGS="$2 $CFLAGS" make -j3 -f $3 test tv_gen 1>gcc_1.txt 2>gcc_2.txt || (echo "build $1 failed see gcc_2.txt for more information" && cat gcc_2.txt && exit 1)
+CFLAGS="$2 $CFLAGS $4" EXTRALIBS="$5" make -j4 -f $3 test tv_gen 1>gcc_1.txt 2>gcc_2.txt || (echo "build $1 failed see gcc_2.txt for more information" && cat gcc_2.txt && exit 1)
 echo -n "testing..."
 if [ -a test ] && [ -f test ] && [ -x test ]; then
    ((./test >test_std.txt 2>test_err.txt && ./tv_gen > tv.txt) && echo "$1 test passed." && echo "y" > testok.txt) || (echo "$1 test failed" && cat test_err.txt && exit 1)
    if find *_tv.txt -type f 1>/dev/null 2>/dev/null ; then
-      for f in *_tv.txt; do if (diff $f notes/$f) then true; else (echo "tv_gen $f failed" && rm -f testok.txt && exit 1); fi; done
+      for f in *_tv.txt; do if (diff --ignore-case $f notes/$f) then true; else (echo "tv_gen $f failed" && rm -f testok.txt && exit 1); fi; done
    fi
 fi
 if [ -a testok.txt ] && [ -f testok.txt ]; then
@@ -16,5 +16,5 @@
 exit 1
 
 # $Source: /cvs/libtom/libtomcrypt/build.sh,v $   
-# $Revision: 1.5 $   
-# $Date: 2005/06/27 13:04:05 $ 
+# $Revision: 1.9 $   
+# $Date: 2006/03/18 14:10:55 $ 
--- a/libtomcrypt/changes	Mon Oct 02 06:40:51 2006 +0000
+++ b/libtomcrypt/changes	Thu Nov 06 13:16:55 2008 +0000
@@ -1,3 +1,233 @@
+December 16th, 2006
+v1.16 -- Brian Gladman pointed out that a recent change to GCM broke how the IV was handled.  Currently the code complies against his test vectors
+         so the code should be considered frozen now.
+      -- Trevor from Cryptography Research Inc. submitted patches to convert the ECC code to be generic allowing curve parameters to be submitted
+         at runtime.  
+      -- Fixed various doxygen comments
+      -- Added UTF8 support to the ASN1 code
+      -- Fixed STOREXXH macros for x86 platforms (Fix found at Elliptic Inc.)
+      -- Added makefile.unix which is BSD compatible, you have to manually tweak it since well I don't use it normally
+      -- removed a few lingering memcpy's
+      -- Fixed memory free errors in ecc_sign_hash() that can arise if the mp_init_multi() fails
+      -- Fixed incorrect return value in pkcs_1_pss_decode() which would correctly set res to 0 (indicating an incorrect signature) but 
+         would return CRYPT_OK to the caller
+      -- ltc_ecc_mulmod() could leak memory if mp_init(&mu) failed, fixed.  Would you believe that ltc_ecc_mulmod_timing() had the same
+         bug?  Also fixed.  :-)
+      -- Added Shamir's trick to the ECC side (defined as LTC_ECC_SHAMIR, enabled by default), gets ~1.34x to ~1.40x faster ECC verifications
+      -- Added Brian's vector #46 to the GCM code.  It catches the ctr counter error from v1.15.  Originally I was going to add all of his vectors,
+         but they're not as easy to parse and I got a lot of other things to do.  Regression!
+      -- Various other small fixes to the ECC code to clean up error handling (I think most of that was from the move in 1.06 to the plugins)
+         All of the errors were in cleaning up from heap failures.  So they were not likely to be triggered in normal usage
+         Made similar fixes to the RSA and DSA code (my bad)
+      -- Cryptography Research Inc. contributed a bunch of fixes to silence warnings (with MSVC) w.r.t. assigned data to unsigned char types.
+      -- Martin Marko suggested some fixes to make the RNG build with WinCE.
+      -- Updates to the manual for print (some fixes thanks to Martin Marko)
+      
+
+November 17th, 2006
+v1.15 -- Andreas Lange found that if sha256_init DID fail in fortuna it wouldn't clean up the state correctly.  Thanks.
+         Fortunately sha256_init cannot fail (as of v1.14) :-)
+      -- Andreas Lange contributed RMD-256 and RMD-320 code.
+      -- Removed mutex locks from fortuna_import as they create a deadlock and aren't required anyways [Avi Zelmanovich]
+      -- Added LTC_NO_PROTOTYPES to avoid prototyping functions like memset/memcpy.  Required for fans of GCC 3.3.x
+      -- David Eder caught a off by one overrun bug in pmac_done() which can be exploited if your output tag buffer is 
+         smaller than the block size of the cipher, e.g. if you have a 4-byte buffer and you tell pmac_done that you want
+         a 4-byte TAG it will store 4 bytes but return an outlen of 5.
+      -- Added signatures to the ECC and RSA benchmarks
+      -- Added LTC_PROFILE to run the PK tests only once in the timing demo (so you can capture events properly)
+      -- Andreas contributed PKCS #1 v1.5 code that merged cleanly with the existing PKCS code.  w00t.
+         (update: I had to fix it to include the digestInfo and what not.  Bad Andreas, bad! hehehe)
+      -- Fixed a signed variable error in gcm_process() (hard to trigger bug fortunately)
+      -- Removed all memcmp/memset/memcpy from the source (replaced with X macros)
+      -- Renamed macros HMAC/OMAC/PMAC to have a LTC_ prefix.  If you pass these on the command line please update your makefiles
+      -- Added XCBC-MAC support [RFC 3566]
+      -- fixed LOAD32H and LOAD64H to stop putting out that darn warning :-)
+      -- Added the Korean SEED block cipher [RFC 4269]
+      -- Added LTC_VALGRIND define which makes SOBER-128 and RC4 a pure PRNG (and not a stream cipher).  Useful if you use 
+         Valgrind to debug your code (reported by Andreas Lange)
+      -- Made SOBER-128 more portable by removing the ASCII key in the test function (my bad, sorry).
+      -- Martin Mocko pointed out that if you have no PRNGs defined the lib won't build.  Fixed, also fixed for if you have no
+         hashes defined.
+      -- Sped up F8 mode with LTC_FAST
+      -- Made CTR mode RFC 3686 compliant (increment counter first), to enable, OR the value LTC_CTR_RFC3686 to the "mode"
+         parameter you pass to ctr_start(), otherwise it will be LTC compliant (e.g. encrypt then increment)
+      -- Added ctr_test() to test CTR mode against RFC 3686
+      -- Added crypt_fsa() ... O_o
+      -- Fixed LTC_ECC_TIMING_RESISTANT so it once again builds properly (pt add/dbl are through the plugin now)
+      -- Added ANSI X9.63 (sec 4.3.6) import/export of public keys (cannot export to compressed formats but will import 
+         hybrid compressed)
+      -- Added SECP curves for 112, 128, and 160 bits (only the 'r1' curves)
+      -- Added 3GPP-F9 MAC (thanks to Greg Rose for the test vectors)
+      -- Added the KASUMI block cipher
+      -- Added F9/XCBC/OMAC callbacks to the cipher plugin
+      -- Added RSA PKCS #1 v1.5 signature/encrypt tests to rsa_test.c
+      -- Fix to yarrow_test() to not call yarrow_done() which is invalid in that context (thanks Valgrind)
+      -- Christophe Devine pointed out that Anubis would fail on various 64-bit UNIX boxes when "x>>24" was used as an index, we needed 
+         to mask it with 0xFF.  Thanks.  Fixed.
+
+August 0x1E, 0x07D6
+v1.14 -- Renamed the chaining mode macros from XXX to LTC_XXX_MODE.  Should help avoid polluting the macro name space.
+      -- clean up of SHA-256
+      -- Chris Colman pointed out that der_decode_sequence_* allows LTC_ASN1_SETOF to accept SEQUENCEs and vice versa.
+         Decoder [non-flexi decoder that is] is more strict now and requires a match.
+      -- Steffen Jaeckel pointed out a typo in the user manual (re: rsa_exptmod).  Fixed.  This disproves the notion that
+         nobody reads it.  :-)
+      -- Made GCM a bit more portable w.r.t. handling the CTR IV (e.g. & with 255)
+      -- Add LTC_VERBOSE if you really want to see what test is doing :-)
+      -- Added SSE2 support to GCM [use GCM_TABLES_SSE2 to enable], shaves 2 cycles per byte on Opteron processors
+         Shaved 4 cycles on a Prescott (Intel P4)
+         Requires you align your gcm_state on a 16 byte boundary, see gcm_memory() for more info
+      -- Added missing prototype for f8_test_mode()
+      -- two fixes to CCM for corner cases [L+noncelen > 15] and fixing the CTR pad to encrypt the CBC-MAC tag
+      -- Franz Glasner pointed out the ARGTYPE=4 is not actually valid.  Fixed.
+      -- Fixed bug in f8_start() if your key < saltkey unspecified behaviour occurs.  :-(
+      -- Documented F8 mode.  Yeah, because you read the manual.  
+      -- Minor updates to the technotes.
+
+
+June 17th, 2006
+v1.13 -- Fixed to fortuna_start() to clean up state if an error occurs.  Not really useful at this stage (sha256 can't fail) but useful
+         if I ever make fortuna pluggable
+      -- Mike Marin submitted a whole bunch of patches for fixing up the libs on traditional UNIX platforms.  Go AIX!  Thanks!
+      -- One of bugs found in the multi demo highlights that at least with gcc you need to pass integers with a UL prefix to ensure
+         they're unsigned long
+      -- Updated the FP ECC code to use affine points.  It's teh fast.
+      -- Made it so many functions which return CRYPT_BUFFER_OVERFLOW now also indicate the required buffer size, note that not all functions
+         do this (most do though).
+      -- Added F8 chaining mode.  It's super neato.
+
+May 29th, 2006
+v1.12 -- Fixed OID encoder/decoder/length to properly handle the first two parts of an OID, matches 2002 X.690 now.
+      -- [Wesley Shields] Allows both GMP/LTM and TFM to be defined now.  
+      -- [Wesley Shields] GMP pluggin is cleaner now and doesn't use deprecated symbols. Yipee
+      -- Added count_lsb_bits to get the number of leading LSB zero bits there are.
+      -- Fixed a bug in the INTEGER encoders for values of -(256**k)/2
+      -- Added BOOLEAN type to ASN.1 thingy-ma-do-hicky
+      -- Testprof doesn't strictly require GMP ... oops [Nils Durner]
+      -- Added LTC_CALL and LTC_EXPORT macros in tomcrypt_cfg.h to support various calling and linker conventions
+         (Thanks to John Kirk from Demonware)
+      -- In what has to be the best thing since sliced bread I bring you MECC_FP which is the fixed point
+         ECC point multiplier.  It's fast, it's sexy and what's more it's hella fast [did I mention it's fast?]
+         You can tune it somewhat with FP_LUT (default to 8) for look-up width.
+         Read section 8.2 of the manual for more info.
+         It is disabled by default, you'll have to build LTC with it defined to get it.  
+      -- Fixed bug in ecc_test.c (from testprof) to include the 521 [not 512] bit curve.  :-)
+
+April 4th, 2006
+v1.11 -- Removed printf's from lrw_test ... whoops
+      -- lrw_process now checks the return of the cipher ecb encrypt/decrypt calls
+      -- lrw_start was not using num_rounds ...
+      -- Adam Miller reported a bug in the flexi decoder with elements past the end of a sequence.  Fixed.
+      -- Bruce Guenter suggested I use --tag=CC for libtool builds where the compiler may think it's C++.  (I applied this to LTM and TFM)
+      -- Optimized the ECC for TFM a bit by removing the useless "if" statements (most TFM functions don't return error codes)
+         Actually shaved a good chunk of time off and made the code smaller.  By default with TFM the stock LTC point add/dbl functions 
+         will be totally omitted (ECC-256 make key times on a Prescott for old vs. new are 11.03M vs. 9.59M cycles)
+      -- added missing CVS tags to ltc_ecc_mulmod.c
+      -- corrected typo in tomcrypt_cfg.h about what the file has been called 
+      -- corrected my address in the user manual.  A "bit" out of date.
+      -- added lrw_gen to tv_gen
+      -- added GMP plugin, only tested on a AMD64 and x86_32 Gentoo Linux box so be aware
+      -- made testme.sh runs diff case insensitivityly [whatever...] cuz GMP outputs lowercase satan text
+      -- added LDFLAGS to the makefile to allow cross porting linking options
+      -- added lrw_test() to the header file ... whoops
+      -- changed libtomcrypt.org to libtomcrypt.com .... mumble mumble
+      -- Updates to detect __STRICT_ANSI__ which is defined in --std=c99 modes (note -ansi is not supported as it lacks long long) so you can
+         build LTC out of the box with c99 (note: it'll be slower as there is no asm in this case)
+      -- Updated pelican.c and aes_tab.c to undef tables not-required.  The tables are static so both AES and Pelican MAC would have copies.  Save a few KB in the final binary.
+      -- Added LTC_NO_FAST to the makefile.icc to compensate for the fact ICC v9 can't handle it (Pelican MAC fails for instance)
+
+February 11th, 2006
+v1.10 -- Free ecb/cbc/ctr/lrw structures in timing code by calling the "done" function
+      -- fixed bug in lrw_process() which would always use the slow update ...
+      -- vastly sped up gcm_gf_mult() when LTC_FAST is defined.  This speeds up LRW and GCM state creation, useful for servers with GCM
+      -- Removed NLS since there are some attacks against it.  
+      -- fixed memory leak in rsa_import reported by John Kuhns
+      ++ re-released as the rsa fix was incorrect (bad John bad ... hehehe) and I missed some NULLs in the static descriptor entry for ciphers 
+
+January 26th, 2006
+v1.09 -- Added missing doxygen comments to some of the ASN.1 routines
+      -- Added "easy button" define LTC_EASY and LTC will build with a subset of all the algos.  Reduces build times for typical
+         configurations.  Tunable [see tomcrypt_custom.h]
+      -- Added some error detection to reg_algs() of the testprof.a library to detect when the PRNG is not setup correctly (took me 10 mins to figure out, PITA!)
+      -- Similar fixes to timing demo (MD5 not defined when EASY is defined)
+      -- Added the NLS enc+mac stream cipher from QUALCOMM, disabled for this release, waiting on test vectors
+      -- Finally added an auto-update script for the makefiles.  So when I add new files/dirs it can automatically fix up the makefiles [all four of them...]
+      -- Added LRW to the list of cipher modes supported
+      -- cleaned up ciphers definitions to remove cbc/cfb/ofb/ctr/etc from the namespace when not used.
+
+November 24th, 2005
+v1.08 -- Added SET and SET OF support to the ASN.1 side
+      -- Fixed up X macros, added QSORT to the mix [thanks SET/SETOF]
+      -- Added XMEMCMP to the list of X macros
+      -- In der_decode_sequence() the SHORT_INTEGER type was not being handled correctly [oddly enough it worked just enough to make RSA work ... go figure!]
+      -- Fixed bug in math descriptors where if you hadn't defined MECC (ECC support) you would get linker errors
+      -- Added RSA accelerators to the math descriptors to make it possible to not include the stock routines if you supply your own.
+      -- dsa_decrypt_key() was erroneously dependent on MECC not MDSA ... whoops
+      -- Moved DSA size limits to tomcrypt_pk.h so they're defined with LTC_NO_PK+MDSA
+      -- cleaned up tomcrypt_custom.h to make customizable PK easier (and also cleaned up the error traps so they're correctly reported)
+
+November 18th, 2005
+v1.07 -- Craig Schlenter pointed out the "encrypt" demo doesn't call ctr_start() correctly.  That's because as of a few releases ago
+         I added support to set the mode of the counter at init time
+      -- Fixed some "testprof" make issues
+      -- Added RSA keygen to the math descriptors
+      -- Fixed install_test target ... oops
+      -- made the "ranlib" program renamable useful for cross-compiling
+      -- Made the cipher accelerators return error codes.  :-)
+      -- Made CCM accept a pre-scheduled key to speed it up if you use the same key for multiple packets
+      -- Added "Katja" public key crypto.  It's based on the recent N = p^2q work by Katja.  I added OAEP padding
+         to it.  Note this code has been disabled not because it doesn't work but because it hasn't been thoroughly
+         analyzed.   It does carry some advantages over RSA (slightly smaller public key, faster decrypt) but also
+         some annoying "setup" issues like the primes are smaller which makes ECM factoring more plausible.
+      -- Made makefile accept a NODOCS flag to disable the requirement of tetex to install LTC for you no tetex people... all 3 of ya  :-)
+      -- Cleaned up rsa_export() since "zero" was handled with a SHORT_INTEGER
+      -- Cleaned up the LIBTEST_S definitions in both GNU makefiles.  A few minor touchups as well.
+      -- Made the cipher ecb encrypt/decrypt return an int as well, changed ALL dependent code to check for this.  
+      -- der_decode_choice() would fail to mark a NULL as "used" when decoding.  Fixed
+      -- ecc_decrypt_key() now uses find_hash_oid() to clean up the code ;-)
+      -- Added mp_neg() to the math descriptors.
+      -- Swapped arguments for the pkcs_1_mgf1() function so the hash_idx is the first param (to be more consistent)
+      -- Made the math descriptors buildable when RSA has been undefined
+      -- ECC timing demo now capable of detecting which curves have been defined
+      -- Refactored the ECC code so it's easier to maintain.  (note: the form of this code hasn't really changed since I first added ECC ... :-/)
+      -- Updated the documentation w.r.t. ECC and the accelerators to keep it current
+      -- Fixed bug in ltc_init_multi() which would fail to free all allocated memory on error.
+      -- Fixed bug in ecc_decrypt_key() which could possibly lead to overflows (if MAXBLOCKSIZE > ECC_BUF_SIZE and you have a hash that emits MAXBLOCKSIZE bytes)
+      -- Added encrypt/decrypt to the DSA side (basically DH with DSA parameters)
+      -- Updated makefiles to remove references to the old DH object files and the ecc_sys.o crap ... clean code ahead!
+      -- ecc_import() now checks if the point it reads in lies on the curve (to prevent degenerative points from being used)
+      -- ECC code now ALWAYS uses the accelerator interface.  This allows people who use the accelerators to not have the stock
+         ECC point add/dbl/mul code linked in.  Yeah space savings! Rah Rah Rah.
+      -- Added LTC_MUTEX_* support to Yarrow and Fortuna allowing you to use respective prng_state as a global PRNG state [e.g. thread-safe] if you define one of the LTC_* defines at
+         build time (e.g. LTC_PTHREAD == pthreads)
+      -- Added PPC32 support to the rotate macros (tested on an IBM PPC 405) and LTC_FAST macros (it aint fast but it's faster than stock)
+      -- Added ltc_mp checks in all *_make_key() and *_import() which will help catch newbs who don't register their bignum first :-)
+      -- the UTCTIME type was missing from der_length_sequence() [oops, oh like you've never done that]
+      -- the main makefile allows you to rename the make command [e.g. MAKE=gmake gmake install] so you can build LTC on platforms where the default make command sucks [e.g. BSD]
+      -- Added DER flexi decoder which allows the decoding of arbitrary DER encoded packets without knowing
+         their structure in advance (thanks to MSVC for finding 3 bugs in it just prior to release! ... don't ask)
+
+August 1st, 2005
+v1.06 -- Fixed rand_prime() to accept negative inputs as a signal for BBS primes. [Fredrik Olsson]
+      -- Added fourth ARGCHK type which outputs to stderr and continues.  Useful if you trap sigsegv.   [Valient Gough]
+      -- Removed the DH code from the tree
+      -- Made the ECC code fully public (you can access ecc_mulmod directly now) useful for debuging
+      -- Added ecc test to tv_gen
+      -- Added hmac callback to hash descriptors.
+      -- Fixed two doxy comment errors in the UTCTIME functions
+      -- rsa_import() can now read OpenSSL format DER public keys as well as the PKCS #1 RSAPublicKey format.
+         Note that rsa_export()  **ONLY** writes PKCS #1 formats
+      -- Changed MIN/MAX to only define if not already present.  -- Kirk J from Demonware ... 
+      -- Ported tv_gen to new framework (and yes, I made ecc vectors BEFORE changing the API and YES they match now :-))
+      -- ported testing scripts to support pluggable math.  yipee!
+      -- Wrote a TFM descriptor ... yipee
+      -- Cleaned up LTC_FAST in CBC mode a bit 
+      -- Merged in patches from Michael Brown for the sparc/sparc64 targets
+      -- Added find_hash_oid() to search for a hash by its OID
+      -- Cleaned up a few stray CLEAN_STACKs that should have been LTC_CLEAN_STACK
+      -- Added timing resistant ECC, enable by defining LTC_ECC_TIMING_RESISTANT then use ECC API as normal 
+      -- Updated the ECC documentation as it was a bit out of date
+
 June 27th, 2005
 v1.05
       -- Added Technote #6 which covers the current PK compliance.  
@@ -213,7 +443,7 @@
 v0.99  -- Merged in the latest version of LTM which includes all of the recent bug fixes
        -- Deprecated LTMSSE and removed it (to be replaced with TFM later on)
        -- Stefan Arentz pointed out that mp_s_rmap should be extern
-       -- Kristian Gjøsteen pointed out that there are typos in the 
+       -- Kristian Gj?steen pointed out that there are typos in the 
           "test" makefile and minor issues in Yarrow and Sober [just cosmetics really]
        -- Matthew P. Cashdollar pointed out that "export" is a C++ keyword 
           so changed the PRNG api to use "pexport" and "pimport"
@@ -592,7 +822,7 @@
           as much as possible.  This sped the routine up quite a bit.
        -- Fixed a huge flaw in ecc_verify_hash() where it would return CRYPT_OK on error... Now fixed.
        -- Fixed up config.pl by fixing an invalid query and the file is saved in non-windows [e.g. not CR/LF] format
-          (fix due to Mika Boström)
+          (fix due to Mika Bostr?m)
        -- Merged in LibTomMath for kicks
        -- Changed the build process so that by default "mycrypt_custom.h" is included and provided
           The makefile doesn't include any build options anymore
@@ -1321,6 +1551,6 @@
 v0.01  -- We will call this the first version.
 
 /* $Source: /cvs/libtom/libtomcrypt/changes,v $ */
-/* $Revision: 1.106 $ */
-/* $Date: 2005/06/27 12:37:06 $ */
+/* $Revision: 1.274 $ */
+/* $Date: 2006/12/16 19:08:17 $ */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libtomcrypt/crypt.lof	Thu Nov 06 13:16:55 2008 +0000
@@ -0,0 +1,24 @@
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {2.1}{\ignorespaces Load And Store Macros}}{9}{figure.2.1}
+\contentsline {figure}{\numberline {2.2}{\ignorespaces Rotate Macros}}{9}{figure.2.2}
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {3.1}{\ignorespaces Built--In Software Ciphers}}{19}{figure.3.1}
+\contentsline {figure}{\numberline {3.2}{\ignorespaces Twofish Build Options}}{21}{figure.3.2}
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {4.1}{\ignorespaces Built--In Software Hashes}}{57}{figure.4.1}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {6.1}{\ignorespaces List of Provided PRNGs}}{82}{figure.6.1}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {9.1}{\ignorespaces DSA Key Sizes}}{119}{figure.9.1}
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {10.1}{\ignorespaces List of ASN.1 Supported Types}}{127}{figure.10.1}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {12.1}{\ignorespaces RSA/DH Key Strength}}{149}{figure.12.1}
+\contentsline {figure}{\numberline {12.2}{\ignorespaces ECC Key Strength}}{149}{figure.12.2}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
--- a/libtomcrypt/crypt.tex	Mon Oct 02 06:40:51 2006 +0000
+++ b/libtomcrypt/crypt.tex	Thu Nov 06 13:16:55 2008 +0000
@@ -1,4 +1,5 @@
-\documentclass[a4paper]{book}
+\documentclass[synpaper]{book}
+\usepackage[dvips]{geometry}
 \usepackage{hyperref}
 \usepackage{makeidx}
 \usepackage{amssymb}
@@ -6,6 +7,7 @@
 \usepackage{alltt}
 \usepackage{graphicx}
 \usepackage{layout}
+\usepackage{fancyhdr}
 \def\union{\cup}
 \def\intersect{\cap}
 \def\getsrandom{\stackrel{\rm R}{\gets}}
@@ -29,7 +31,7 @@
 \def\And{{\rm\ and\ }}
 \def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
 \def\implies{\Rightarrow}
-\def\undefined{{\rm ``undefined"}}
+\def\undefined{{\rm \textit{undefined}}}
 \def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
 \let\oldphi\phi
 \def\phi{\varphi}
@@ -41,63 +43,97 @@
 \def\R{{\mathbb R}}
 \def\C{{\mathbb C}}
 \def\Q{{\mathbb Q}}
-
+\definecolor{DGray}{gray}{0.5}
+\newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
 \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
-
 \def\gap{\vspace{0.5ex}}
 \makeindex
+\newcommand{\mysection}[1]    % Re-define the chaptering command to use
+	{                   % THESE headers.
+	\section{#1}
+   \markboth{\textsf{www.libtom.org}}{\thesection ~ {#1}}
+	}
+
+\newcommand{\mystarsection}[1]    % Re-define the chaptering command to use
+	{                   % THESE headers.
+	\section*{#1}
+   \markboth{\textsf{www.libtom.org}}{{#1}}
+	}
+\pagestyle{empty}
 \begin{document}
-\title{LibTomCrypt \\ Version 1.05}
-\author{Tom St Denis \\
-\\
[email protected] \\
-http://libtomcrypt.org
-}
-\maketitle
-This text and source code library are both hereby placed in the public domain.  This book has been 
-formatted for A4 paper using the \LaTeX{} {\em book} macro package.
-
-\vspace{15cm}
-
-\begin{flushright}Open Source.  Open Academia.  Open Minds.
-
-\mbox{ }
-
-Tom St Denis,
-
-Phone: 1-613-836-3160
-
-111 Banning Rd 
-
-Kanata, Ontario 
-
-K2L 1C3 
+\frontmatter
+\pagestyle{empty}
+
+~
+
+\vspace{2in}
+
+~
+
+\begin{center}
+\begin{Huge}LibTomCrypt\end{Huge}
+
+~
+
+\begin{large}Developer Manual\end{large}
+
+~
+
+\vspace{15mm}
+
+
+\begin{tabular}{c}
+Tom St Denis \\
+LibTom Projects
+\end{tabular}
+\end{center}
+\vfil
+\newpage
+This document is part of the LibTomCrypt package and is hereby released into the public domain.
+
+~
+
+Open Source.  Open Academia.  Open Minds.
+
+~
+
+\begin{flushright}
+Tom St Denis
+~
+
+Ottawa, Ontario
+~
 
 Canada
+~
+\vfil
 \end{flushright}
 \newpage
+
 \tableofcontents
+\listoffigures
+\pagestyle{myheadings}
+\mainmatter
 \chapter{Introduction}
-\section{What is the LibTomCrypt?}
-LibTomCrypt is a portable ISO C cryptographic library that is meant to be a toolset for cryptographers who are 
-designing a cryptosystem.  It supports symmetric ciphers, one-way hashes, pseudo-random number generators, 
-public key cryptography (via PKCS \#1 RSA, DH or ECCDH) and a plethora of support 
-routines.  
-
-The library was designed such that new ciphers/hashes/PRNGs can be added at runtime and the existing API 
+\mysection{What is the LibTomCrypt?}
+LibTomCrypt is a portable ISO C cryptographic library meant to be a tool set for cryptographers who are 
+designing cryptosystems.  It supports symmetric ciphers, one-way hashes, pseudo-random number generators, 
+public key cryptography (via PKCS \#1 RSA, DH or ECCDH), and a plethora of support routines.  
+
+The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API 
 (and helper API functions) are able to use the new designs automatically.  There exists self-check functions for each 
 block cipher and hash function to ensure that they compile and execute to the published design specifications.  The library 
-also performs extensive parameter error checking to prevent any number of runtime exploits or errors.
+also performs extensive parameter error checking to prevent any number of run-time exploits or errors.
 
 \subsection{What the library IS for?}
 
 The library serves as a toolkit for developers who have to solve cryptographic problems.  Out of the box LibTomCrypt
-does not process SSL or OpenPGP messages, it doesn't read x.591 certificates or write PEM encoded data.  It does, however,
+does not process SSL or OpenPGP messages, it doesn't read X.509 certificates, or write PEM encoded data.  It does, however,
 provide all of the tools required to build such functionality.  LibTomCrypt was designed to be a flexible library that 
 was not tied to any particular cryptographic problem.  
 
-\section{Why did I write it?}
-You may be wondering, ``Tom, why did you write a crypto library.  I already have one.''.  Well the reason falls into
+\mysection{Why did I write it?}
+You may be wondering, \textit{Tom, why did you write a crypto library.  I already have one.}  Well the reason falls into
 two categories:
 \begin{enumerate}
     \item I am too lazy to figure out someone else's API.  I'd rather invent my own simpler API and use that.
@@ -107,27 +143,27 @@
 The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc.  I'm trying to write my 
 {\bf own} crypto library and hopefully along the way others will appreciate the work.
 
-With this library all core functions (ciphers, hashes, prngs) have the {\bf exact} same prototype definition.  They all load
+With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition.  They all load
 and store data in a format independent of the platform.  This means if you encrypt with Blowfish on a PPC it should decrypt
-on an x86 with zero problems.  The consistent API also means that if you learn how to use Blowfish with my library you 
-know how to use Safer+ or RC6 or Serpent or ... as well.  With all of the core functions there are central descriptor tables 
-that can be used to make a program automatically pick between ciphers, hashes and PRNGs at runtime.  That means your 
-application can support all ciphers/hashes/prngs without changing the source code.
-
-Not only did I strive to make a consistent and simple API to work with but I also strived to make the library
+on an x86 with zero problems.  The consistent API also means that if you learn how to use Blowfish with the library you 
+know how to use Safer+, RC6, or Serpent as well.  With all of the core functions there are central descriptor tables 
+that can be used to make a program automatically pick between ciphers, hashes and PRNGs at run-time.  That means your 
+application can support all ciphers/hashes/prngs/bignum without changing the source code.
+
+Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
 configurable in terms of its build options.  Out of the box the library will build with any modern version of GCC
 without having to use configure scripts.  This means that the library will work with platforms where development
 tools may be limited (e.g. no autoconf).
 
-On top of making the build simple and the API approachable I've also strived for a reasonably high level of
+On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
 robustness and efficiency.  LibTomCrypt traps and returns a series of errors ranging from invalid
 arguments to buffer overflows/overruns.  It is mostly thread safe and has been clocked on various platforms
-with ``cycles per byte'' timings that are comparable (and often favourable) to other libraries such as OpenSSL and
+with \textit{cycles per byte} timings that are comparable (and often favourable) to other libraries such as OpenSSL and
 Crypto++.
 
 \subsection{Modular}
-The LibTomCrypt package has also been written to be very modular.  The block ciphers, one--way hashes and
-pseudo--random number generators (PRNG) are all used within the API through ``descriptor'' tables which 
+The LibTomCrypt package has also been written to be very modular.  The block ciphers, one--way hashes,
+pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit{descriptor} tables which 
 are essentially structures with pointers to functions.  While you can still call particular functions
 directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
 usage of the library.
@@ -135,7 +171,7 @@
 For example, consider a hardware platform with a specialized RNG device.  Obviously one would like to tap
 that for the PRNG needs within the library (\textit{e.g. making a RSA key}).  All the developer has to do
 is write a descriptor and the few support routines required for the device.  After that the rest of the 
-API can make use of it without change.  Similiarly imagine a few years down the road when AES2 
+API can make use of it without change.  Similarly imagine a few years down the road when AES2 
 (\textit{or whatever they call it}) has been invented.  It can be added to the library and used within applications 
 with zero modifications to the end applications provided they are written properly.
 
@@ -147,33 +183,21 @@
 the key setup, ECB decrypt and encrypt and test vector routines.  After that all five chaining mode routines
 can make use of the cipher right away.
 
-\section{License}
-
-All of the source code except for the following files have been written by the author or donated to the project
-under a public domain license:
-
-\begin{enumerate}
-   \item rc2.c
-\end{enumerate}
-
-`mpi.c'' was originally written by Michael Fromberger ([email protected]) but has since been replaced with 
-my LibTomMath library which is public domain.
-
-``rc2.c'' is based on publicly available code that is not attributed to a person from the given source.  
+\mysection{License}
 
 The project is hereby released as public domain.
 
-\section{Patent Disclosure}
+\mysection{Patent Disclosure}
 
 The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice.  To the best
 of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.  
-They can be removed from a build by simply commenting out the two appropriate lines in ``tomcrypt\_custom.h''.  The rest
+They can be removed from a build by simply commenting out the two appropriate lines in \textit{tomcrypt\_custom.h}.  The rest
 of the ciphers and hashes are patent free or under patents that have since expired.
 
 The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations.  This means you can use 
 the ciphers you just can't advertise that you are doing so.  
 
-\section{Thanks}
+\mysection{Thanks}
 I would like to give thanks to the following people (in no particular order) for helping me develop this project from
 early on:
 \begin{enumerate}
@@ -196,11 +220,11 @@
 time to time.
 
 \chapter{The Application Programming Interface (API)}
-\section{Introduction}
+\mysection{Introduction}
 \index{CRYPT\_ERROR} \index{CRYPT\_OK}
 
 In general the API is very simple to memorize and use.  Most of the functions return either {\bf void} or {\bf int}.  Functions
-that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful or one of the many error codes 
+that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful, or one of the many error codes 
 if it failed.  Certain functions that return int will return $-1$ to indicate an error.  These functions will be explicitly
 commented upon.  When a function does return a CRYPT error code it can be translated into a string with
 
@@ -210,6 +234,7 @@
 \end{verbatim}
 
 An example of handling an error is:
+\begin{small}
 \begin{verbatim}
 void somefunc(void)
 {
@@ -217,34 +242,38 @@
    
    /* call a cryptographic function */
    if ((err = some_crypto_function(...)) != CRYPT_OK) {
-      printf("A crypto error occured, %s\n", error_to_string(err));
+      printf("A crypto error occurred, %s\n", error_to_string(err));
       /* perform error handling */
    }
-   /* continue on if no error occured */
+   /* continue on if no error occurred */
 }
 \end{verbatim}
+\end{small}
 
 There is no initialization routine for the library and for the most part the code is thread safe.  The only thread
 related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads.  Normally
 that is not an issue.
 
-To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``tomcrypt.h'' like so:
+To include the prototypes for \textit{LibTomCrypt.a} into your own program simply include \textit{tomcrypt.h} like so:
+\begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
 int main(void) {
     return 0;
 }
 \end{verbatim}
-
-The header file ``tomcrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'', ``ctype.h'' and 
-``ltc\_tommath.h'' (the bignum library routines).
-
-\section{Macros}
+\end{small}
+
+The header file \textit{tomcrypt.h} also includes \textit{stdio.h}, \textit{string.h}, \textit{stdlib.h}, \textit{time.h} and \textit{ctype.h}.
+
+\mysection{Macros}
 
 There are a few helper macros to make the coding process a bit easier.  The first set are related to loading and storing
 32/64-bit words in little/big endian format.  The macros are:
 
 \index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
+\newpage
+\begin{figure}[hpbt]
 \begin{small}
 \begin{center}
 \begin{tabular}{|c|c|c|}
@@ -256,14 +285,18 @@
      \hline STORE64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
      \hline LOAD32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
      \hline LOAD64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
-     \hline BSWAP(x) & {\bf unsigned long} x & Swaps byte order (32--bits only) \\
+     \hline BSWAP(x) & {\bf unsigned long} x & Swap bytes \\
      \hline
 \end{tabular}
+\caption{Load And Store Macros}
 \end{center}
 \end{small}
+\end{figure}
 
 There are 32 and 64-bit cyclic rotations as well:
 \index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c} 
+\begin{figure}[hpbt]
+\begin{small}
 \begin{center}
 \begin{tabular}{|c|c|c|}
      \hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 31$ \\
@@ -277,12 +310,15 @@
      \hline ROR64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 63$ \\
      \hline
 \end{tabular}
+\caption{Rotate Macros}
 \end{center}
-
-\section{Functions with Variable Length Output}
-Certain functions such as (for example) ``rsa\_export()'' give an output that is variable length.  To prevent buffer overflows you
-must pass it the length of the buffer\footnote{Extensive error checking is not in place but it will be in future releases so it is a good idea to follow through with these guidelines.} where
-the output will be stored.  For example:
+\end{small}
+\end{figure}
+
+\mysection{Functions with Variable Length Output}
+Certain functions such as (for example) \textit{rsa\_export()} give an output that is variable length.  To prevent buffer overflows you
+must pass it the length of the buffer where the output will be stored.  For example:
+\index{rsa\_export()} \index{error\_to\_string()} \index{variable length output}
 \begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
@@ -294,14 +330,16 @@
 
     /* ... Make up the RSA key somehow ... */
 
-    /* lets export the key, set x to the size of the output buffer */
+    /* lets export the key, set x to the size of the 
+     * output buffer */
     x = sizeof(buffer);
     if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
        printf("Export error: %s\n", error_to_string(err));
        return -1;
     }
     
-    /* if rsa_export() was successful then x will have the size of the output */
+    /* if rsa_export() was successful then x will have 
+     * the size of the output */
     printf("RSA exported key takes %d bytes\n", x);
 
     /* ... do something with the buffer */
@@ -311,69 +349,103 @@
 \end{verbatim}
 \end{small}
 In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
-indicating a buffer overflow would have occurred.  If the function succeeds it stores the length of the output
-back into ``x'' so that the calling application will know how many bytes were used.
-
-\section{Functions that need a PRNG}
+indicating a buffer overflow would have occurred.  If the function succeeds, it stores the length of the output back into 
+\textit{x} so that the calling application will know how many bytes were used.
+
+As of v1.13, most functions will update your length on failure to indicate the size required by the function.  Not all functions
+support this so please check the source before you rely on it doing that.
+
+\mysection{Functions that need a PRNG}
 \index{Pseudo Random Number Generator} \index{PRNG}
-Certain functions such as ``rsa\_make\_key()'' require a Pseudo Random Number Generator (PRNG).  These functions do not setup 
+Certain functions such as \textit{rsa\_make\_key()} require a Pseudo Random Number Generator (PRNG).  These functions do not setup 
 the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
 
-Certain PRNG algorithms do not require a ``prng\_state'' argument (sprng for example).  The ``prng\_state'' argument
+Certain PRNG algorithms do not require a \textit{prng\_state} argument (sprng for example).  The \textit{prng\_state} argument
 may be passed as \textbf{NULL} in such situations.
 
-\section{Functions that use Arrays of Octets}
-Most functions require inputs that are arrays of the data type ``unsigned char''.  Whether it is a symmetric key, IV
-for a chaining mode or public key packet it is assumed that regardless of the actual size of ``unsigned char'' only the
-lower eight bits contain data.  For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine
-you must pass it in (a pointer to) an array of 32 ``unsigned char'' variables.  Certain routines 
-(such as SAFER+) take special care to work properly on platforms where an ``unsigned char'' is not eight bits.
-
-For the purposes of this library the term ``byte'' will refer to an octet or eight bit word.  Typically an array of
-type ``byte'' will be synonymous with an array of type ``unsigned char''.
+\index{register\_prng()} \index{rsa\_make\_key()}
+\begin{small}
+\begin{verbatim}
+#include <tomcrypt.h>
+int main(void) {
+    rsa_key key;
+    int     err;
+
+    /* register the system RNG */
+    register_prng(&sprng_desc) 
+
+    /* make a 1024-bit RSA key with the system RNG */
+    if ((err = rsa_make_key(NULL, find_prng("sprng"), 1024/8, 65537, &key)) 
+        != CRYPT_OK) {
+       printf("make_key error: %s\n", error_to_string(err));
+       return -1;
+    }
+
+    /* use the key ... */
+
+    return 0;
+}
+\end{verbatim}
+\end{small}
+
+\mysection{Functions that use Arrays of Octets}
+Most functions require inputs that are arrays of the data type \textit{unsigned char}.  Whether it is a symmetric key, IV
+for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit{unsigned char} only the
+lower eight bits contain data.  For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine, you 
+must pass in (a pointer to) an array of 32 \textit{unsigned char} variables.  Certain routines (such as SAFER+) take 
+special care to work properly on platforms where an \textit{unsigned char} is not eight bits.
+
+For the purposes of this library, the term \textit{byte} will refer to an octet or eight bit word.  Typically an array of
+type \textit{byte} will be synonymous with an array of type \textit{unsigned char.}
 
 \chapter{Symmetric Block Ciphers}
-\section{Core Functions}
-
-LibTomCrypt provides several block ciphers with an ECB block mode interface.  It's important to first note that you 
-should never use the ECB modes directly to encrypt data.  Instead you should use the ECB functions to make a chaining mode
+\mysection{Core Functions}
+LibTomCrypt provides several block ciphers with an ECB block mode interface.  It is important to first note that you 
+should never use the ECB modes directly to encrypt data.  Instead you should use the ECB functions to make a chaining mode,
 or use one of the provided chaining modes.  All of the ciphers are written as ECB interfaces since it allows the rest of
 the API to grow in a modular fashion.
 
 \subsection{Key Scheduling}
-All ciphers store their scheduled keys in a single data type called ``symmetric\_key''.  This allows all ciphers to 
+All ciphers store their scheduled keys in a single data type called \textit{symmetric\_key}.  This allows all ciphers to 
 have the same prototype and store their keys as naturally as possible.  This also removes the need for dynamic memory
-allocation and allows you to allocate a fixed sized buffer for storing scheduled keys.  All ciphers provide five visible 
-functions which are (given that XXX is the name of the cipher):
+allocation, and allows you to allocate a fixed sized buffer for storing scheduled keys.  All ciphers must provide six visible 
+functions which are (given that XXX is the name of the cipher) the following:
 \index{Cipher Setup}
 \begin{verbatim}
-int XXX_setup(const unsigned char *key, int keylen, int rounds,
-              symmetric_key *skey);
+int XXX_setup(const unsigned char *key, 
+                              int  keylen, 
+                              int  rounds,
+                    symmetric_key *skey);
 \end{verbatim}
 
 The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
 The number of rounds can be set to zero to use the default, which is generally a good idea.
 
-If the function returns successfully the variable ``skey'' will have a scheduled key stored in it.  It's important to note
-that you should only used this scheduled key with the intended cipher.  For example, if you call ``blowfish\_setup()'' do not 
-pass the scheduled key onto ``rc5\_ecb\_encrypt()''.  All setup functions do not allocate memory off the heap so when you are 
-done with a key you can simply discard it (e.g. they can be on the stack).
+If the function returns successfully the variable \textit{skey} will have a scheduled key stored in it.  It's important to note
+that you should only used this scheduled key with the intended cipher.  For example, if you call \textit{blowfish\_setup()} do not 
+pass the scheduled key onto \textit{rc5\_ecb\_encrypt()}.  All built--in setup functions do not allocate memory off the heap so 
+when you are done with a key you can simply discard it (e.g. they can be on the stack).  However, to maintain proper coding
+practices you should always call the respective XXX\_done() function.  This allows for quicker porting to applications with
+externally supplied plugins.
 
 \subsection{ECB Encryption and Decryption}
-To encrypt or decrypt a block in ECB mode there are these two function classes
+To encrypt or decrypt a block in ECB mode there are these two functions per cipher:
 \index{Cipher Encrypt} \index{Cipher Decrypt}
 \begin{verbatim}
-void XXX_ecb_encrypt(const unsigned char *pt, unsigned char *ct,
-                     symmetric_key *skey);
-
-void XXX_ecb_decrypt(const unsigned char *ct, unsigned char *pt,
-                     symmetric_key *skey);
+int XXX_ecb_encrypt(const unsigned char *pt, 
+                          unsigned char *ct,
+                          symmetric_key *skey);
+
+int XXX_ecb_decrypt(const unsigned char *ct, 
+                          unsigned char *pt,
+                          symmetric_key *skey);
 \end{verbatim}
 These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
-which cipher you are using.} and store the result where you want it.  It is possible that the input and output buffer are 
-the same buffer.  For the encrypt function ``pt''\footnote{pt stands for plaintext.} is the input and 
-``ct''\footnote{ct stands for ciphertext.} is the output.  For the decryption function it's the opposite.  To test a particular 
-cipher against test vectors\footnote{As published in their design papers.} call the self-test function
+which cipher you are using.}, storing the result in the \textit{ct} buffer (\textit{pt} resp.).  It is possible that the input and output buffer are 
+the same buffer.  For the encrypt function \textit{pt}\footnote{pt stands for plaintext.} is the input and 
+\textit{ct}\footnote{ct stands for ciphertext.} is the output.  For the decryption function it's the opposite.  They both
+return \textbf{CRYPT\_OK} on success.  To test a particular cipher against test vectors\footnote{As published in their design papers.} 
+call the following self-test function.
  
 \subsection{Self--Testing}
 \index{Cipher Testing}
@@ -384,12 +456,13 @@
 based upon.  
 
 \subsection{Key Sizing}
-For each cipher there is a function which will help find a desired key size:
+For each cipher there is a function which will help find a desired key size.  It is specified as follows:
+\index{Key Sizing}
 \begin{verbatim}
 int XXX_keysize(int *keysize);
 \end{verbatim}
-Essentially it will round the input keysize in ``keysize'' down to the next appropriate key size.  This function
-return {\bf CRYPT\_OK} if the key size specified is acceptable.  For example:
+Essentially, it will round the input keysize in \textit{keysize} down to the next appropriate key size.  This function
+will return {\bf CRYPT\_OK} if the key size specified is acceptable.  For example:
 \begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
@@ -408,20 +481,21 @@
 }
 \end{verbatim}
 \end{small}
-This should indicate a keysize of sixteen bytes is suggested.  
+This should indicate a keysize of sixteen bytes is suggested by storing 16 in \textit{keysize.}
 
 \subsection{Cipher Termination}
 When you are finished with a cipher you can de--initialize it with the done function.
 \begin{verbatim}
 void XXX_done(symmetric_key *skey);
 \end{verbatim}
-For the software based ciphers within LibTomCrypt this function will not do anything.  However, user supplied
-cipher descriptors may require calls to it for resource management.  To be compliant all functions which call a cipher
+For the software based ciphers within LibTomCrypt, these functions will not do anything.  However, user supplied
+cipher descriptors may require to be called for resource management purposes.  To be compliant, all functions which call a cipher
 setup function must also call the respective cipher done function when finished.
 
 \subsection{Simple Encryption Demonstration}
-An example snippet that encodes a block with Blowfish in ECB mode is below.
-
+An example snippet that encodes a block with Blowfish in ECB mode.
+
+\index{blowfish\_setup()} \index{blowfish\_ecb\_encrypt()} \index{blowfish\_ecb\_decrypt()} \index{blowfish\_done()}
 \begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
@@ -431,30 +505,30 @@
    symmetric_key skey;
    int err;
 
-   /* ... key is loaded appropriately in ``key'' ... */
-   /* ... load a block of plaintext in ``pt'' ... */
+   /* ... key is loaded appropriately in key ... */
+   /* ... load a block of plaintext in pt ... */
 
    /* schedule the key */
-   if ((err = blowfish_setup(key,     /* the key we will use */
-                               8,     /* key is 8 bytes (64-bits) long */
-                               0,     /* 0 == use default # of rounds */
-                           &skey)     /* where to put the scheduled key */
+   if ((err = blowfish_setup(key, /* the key we will use */
+                               8, /* key is 8 bytes (64-bits) long */
+                               0, /* 0 == use default # of rounds */
+                           &skey) /* where to put the scheduled key */
        ) != CRYPT_OK) {
       printf("Setup error: %s\n", error_to_string(err));
       return -1;
    }
 
    /* encrypt the block */
-   blowfish_ecb_encrypt(pt,             /* encrypt this 8-byte array */
-                        ct,             /* store encrypted data here */ 
-                        &skey);         /* our previously scheduled key */
+   blowfish_ecb_encrypt(pt,       /* encrypt this 8-byte array */
+                        ct,       /* store encrypted data here */ 
+                        &skey);   /* our previously scheduled key */
                         
    /* now ct holds the encrypted version of pt */                        
 
    /* decrypt the block */
-   blowfish_ecb_decrypt(ct,             /* decrypt this 8-byte array */
-                        pt,             /* store decrypted data here */
-                        &skey);         /* our previously scheduled key */
+   blowfish_ecb_decrypt(ct,       /* decrypt this 8-byte array */
+                        pt,       /* store decrypted data here */
+                        &skey);   /* our previously scheduled key */
 
    /* now we have decrypted ct to the original plaintext in pt */                        
 
@@ -466,11 +540,11 @@
 \end{verbatim}
 \end{small}
 
-\section{Key Sizes and Number of Rounds}
+\mysection{Key Sizes and Number of Rounds}
 \index{Symmetric Keys}
-As a general rule of thumb do not use symmetric keys under 80 bits if you can.  Only a few of the ciphers support smaller
-keys (mainly for test vectors anyways).  Ideally your application should be making at least 256 bit keys.  This is not
-because you're supposed to be paranoid.  It's because if your PRNG has a bias of any sort the more bits the better.  For
+As a general rule of thumb, do not use symmetric keys under 80 bits if you can help it.  Only a few of the ciphers support smaller
+keys (mainly for test vectors anyways).  Ideally, your application should be making at least 256 bit keys.  This is not
+because you are to be paranoid.  It is because if your PRNG has a bias of any sort the more bits the better.  For
 example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
 total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$.  So if $\gamma$
 were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
@@ -481,74 +555,58 @@
 ciphers are configured such that the default number of rounds provide adequate security for the given block and key 
 size.
 
-\section{The Cipher Descriptors}
+\mysection{The Cipher Descriptors}
 \index{Cipher Descriptor}
-To facilitate automatic routines an array of cipher descriptors is provided in the array ``cipher\_descriptor''.  An element
-of this array has the following format:
+To facilitate automatic routines an array of cipher descriptors is provided in the array \textit{cipher\_descriptor}.  An element
+of this array has the following (partial) format (See Section \ref{sec:cipherdesc}):
 
 \begin{small}
 \begin{verbatim}
 struct _cipher_descriptor {
+   /** name of cipher */
    char *name;
+
+   /** internal ID */
    unsigned char ID;
+
+   /** min keysize (octets) */
    int  min_key_length, 
+
+   /** max keysize (octets) */
         max_key_length, 
+
+   /** block size (octets) */
         block_length, 
+
+   /** default number of rounds */
         default_rounds;
-   int  (*setup)(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
-   void (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
-   void (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
-   int (*test)(void);
-   void (*done)(symmetric_key *skey);      
-   int  (*keysize)(int *keysize);
-
-   void (*accel_ecb_encrypt)(const unsigned char *pt, 
-                                   unsigned char *ct, 
-                                   unsigned long blocks, symmetric_key *skey);
-   void (*accel_ecb_decrypt)(const unsigned char *ct, 
-                                   unsigned char *pt, 
-                                   unsigned long blocks, symmetric_key *skey);
-   void (*accel_cbc_encrypt)(const unsigned char *pt, 
-                                   unsigned char *ct, 
-                                   unsigned long blocks, unsigned char *IV, 
-                                   symmetric_key *skey);
-   void (*accel_cbc_decrypt)(const unsigned char *ct, 
-                                   unsigned char *pt, 
-                                   unsigned long blocks, unsigned char *IV, 
-                                   symmetric_key *skey);
-   void (*accel_ctr_encrypt)(const unsigned char *pt, 
-                                   unsigned char *ct, 
-                                   unsigned long blocks, unsigned char *IV, 
-                                   int mode, symmetric_key *skey);
-   void (*accel_ccm_memory)(
-       const unsigned char *key,    unsigned long keylen,
-       const unsigned char *nonce,  unsigned long noncelen,
-       const unsigned char *header, unsigned long headerlen,
-             unsigned char *pt,     unsigned long ptlen,
-             unsigned char *ct,
-             unsigned char *tag,    unsigned long *taglen,
-                       int  direction);
-
+...<snip>...
 };
 \end{verbatim}
 \end{small}
 
-Where ``name'' is the lower case ASCII version of the name.  The fields ``min\_key\_length'' and ``max\_key\_length'' 
-are the minimum and maximum key sizes in bytes.  The ``block\_length'' member is the block size of the cipher
+Where \textit{name} is the lower case ASCII version of the name.  The fields \textit{min\_key\_length} and \textit{max\_key\_length} 
+are the minimum and maximum key sizes in bytes.  The \textit{block\_length} member is the block size of the cipher
 in bytes.  As a good rule of thumb it is assumed that the cipher supports
-the min and max key lengths but not always everything in between.  The ``default\_rounds'' field is the default number
+the min and max key lengths but not always everything in between.  The \textit{default\_rounds} field is the default number
 of rounds that will be used.
 
+For a plugin to be compliant it must provide at least each function listed before the accelerators begin.  Accelerators are optional,
+and if missing will be emulated in software.
+
 The remaining fields are all pointers to the core functions for each cipher.  The end of the cipher\_descriptor array is
-marked when ``name'' equals {\bf NULL}.
-
-As of this release the current cipher\_descriptors elements are
-
+marked when \textit{name} equals {\bf NULL}.
+
+As of this release the current cipher\_descriptors elements are the following:
+\vfil
 \index{Cipher descriptor table}
+\index{blowfish\_desc} \index{xtea\_desc} \index{rc2\_desc} \index{rc5\_desc} \index{rc6\_desc} \index{saferp\_desc} \index{aes\_desc} \index{twofish\_desc}
+\index{des\_desc} \index{des3\_desc} \index{noekeon\_desc} \index{skipjack\_desc} \index{anubis\_desc} \index{khazad\_desc} \index{kseed\_desc} \index{kasumi\_desc}
+\begin{figure}[hpbt]
 \begin{small}
 \begin{center}
 \begin{tabular}{|c|c|c|c|c|c|}
-     \hline Name & Descriptor Name & Block Size & Key Range & Rounds \\
+     \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Block Size} & \textbf{Key Range} & \textbf{Rounds} \\
      \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
      \hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
      \hline RC2 & rc2\_desc & 8 & 8 $\ldots$ 128 & 16 \\
@@ -565,56 +623,63 @@
      \hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
      \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
      \hline Khazad & khazad\_desc & 8 & 16 & 8 \\
+     \hline SEED   & kseed\_desc & 16 & 16 & 16 \\
+     \hline KASUMI & kasumi\_desc & 8 & 16 & 8 \\
      \hline
 \end{tabular}
 \end{center}
 \end{small}
+\caption{Built--In Software Ciphers}
+\end{figure}
 
 \subsection{Notes}
 \begin{small}
 \begin{enumerate}
 \item
-For AES (also known as Rijndael) there are four descriptors which complicate issues a little.  The descriptors 
-rijndael\_desc and rijndael\_enc\_desc provide the cipher named ``rijndael''.  The descriptors aes\_desc and 
-aes\_enc\_desc provide the cipher name ``aes''.  Functionally both ``rijndael'' and ``aes'' are the same cipher.  The
-only difference is when you call find\_cipher() you have to pass the correct name.  The cipher descriptors with ``enc'' 
+For AES, (also known as Rijndael) there are four descriptors which complicate issues a little.  The descriptors 
+rijndael\_desc and rijndael\_enc\_desc provide the cipher named \textit{rijndael}.  The descriptors aes\_desc and 
+aes\_enc\_desc provide the cipher name \textit{aes}.  Functionally both \textit{rijndael} and \textit{aes} are the same cipher.  The
+only difference is when you call find\_cipher() you have to pass the correct name.  The cipher descriptors with \textit{enc} 
 in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
-and tables.  The decryption and self--test function pointers of both ``encrypt only'' descriptors are set to \textbf{NULL} and 
+and tables.  The decryption and self--test function pointers of both \textit{encrypt only} descriptors are set to \textbf{NULL} and 
 should not be called.
 
-The ``encrypt only'' descriptors are useful for applications that only use the encryption function of the cipher.  Algorithms such
-as EAX, PMAC and OMAC only require the encryption function.  So far this ``encrypt only'' functionality has only been implemented for
+The \textit{encrypt only} descriptors are useful for applications that only use the encryption function of the cipher.  Algorithms such
+as EAX, PMAC and OMAC only require the encryption function.  So far this \textit{encrypt only} functionality has only been implemented for
 Rijndael as it makes the most sense for this cipher.
 
 \item
-Note that for ``DES'' and ``3DES'' they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
+Note that for \textit{DES} and \textit{3DES} they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
 fact used for the purposes of encryption.  My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
 byte string from the real 7/21 byte key.
 
 \item
-Note that ``Twofish'' has additional configuration options that take place at build time.  These options are found in
-the file ``tomcrypt\_cfg.h''.  The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
-to not pre-compute the Twofish ``$g(X)$'' function as a set of four $8 \times 32$ s-boxes.  This means that a scheduled
-key will require less ram but the resulting cipher will be slower.  The second option is ``TWOFISH\_TABLES'' which when
+Note that \textit{Twofish} has additional configuration options (Figure \ref{fig:twofishopts}) that take place at build time.  These options are found in
+the file \textit{tomcrypt\_cfg.h}.  The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
+to not pre-compute the Twofish \textit{$g(X)$} function as a set of four $8 \times 32$ s-boxes.  This means that a scheduled
+key will require less ram but the resulting cipher will be slower.  The second option is \textit{TWOFISH\_TABLES} which when
 defined will force the Twofish code to use pre-computed tables for the two s-boxes $q_0, q_1$ as well as the multiplication
 by the polynomials 5B and EF used in the MDS multiplication.  As a result the code is faster and slightly larger.  The
-speed increase is useful when ``TWOFISH\_SMALL'' is defined since the s-boxes and MDS multiply form the heart of the
+speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
 Twofish round function.
 
-\index{Twofish build options}
+\begin{figure}[hpbt]
+\index{Twofish build options} \index{TWOFISH\_SMALL} \index{TWOFISH\_TABLES}
 \begin{small}
 \begin{center}
 \begin{tabular}{|l|l|l|}
-\hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\
+\hline \textbf{TWOFISH\_SMALL} & \textbf{TWOFISH\_TABLES} & \textbf{Speed and Memory (per key)} \\
 \hline undefined & undefined & Very fast, 4.2KB of ram. \\
-\hline undefined & defined & Faster keysetup, larger code. \\
+\hline undefined & defined & Faster key setup, larger code. \\
 \hline defined & undefined & Very slow, 0.2KB of ram. \\
 \hline defined & defined & Faster, 0.2KB of ram, larger code. \\
 \hline
 \end{tabular}
 \end{center}
 \end{small}
-
+\caption{Twofish Build Options}
+\label{fig:twofishopts}
+\end{figure}
 \end{enumerate}
 \end{small}
 
@@ -623,9 +688,10 @@
 \begin{verbatim}
 int find_cipher(char *name)
 \end{verbatim}
-Which will search for a given name in the array.  It returns negative one if the cipher is not found, otherwise it returns
+Which will search for a given name in the array.  It returns $-1$ if the cipher is not found, otherwise it returns
 the location in the array where the cipher was found.  For example, to indirectly setup Blowfish you can also use:
 \begin{small}
+\index{register\_cipher()} \index{find\_cipher()} \index{error\_to\_string()}
 \begin{verbatim}
 #include <tomcrypt.h>
 int main(void)
@@ -640,9 +706,11 @@
       return -1;
    }
 
-   /* generic call to function (assuming the key in key[] was already setup) */
-   if ((err = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) != 
-       CRYPT_OK) {
+   /* generic call to function (assuming the key 
+    * in key[] was already setup) */
+   if ((err = 
+        cipher_descriptor[find_cipher("blowfish")].
+          setup(key, 8, 0, &skey)) != CRYPT_OK) {
       printf("Error setting up Blowfish: %s\n", error_to_string(err));
       return -1;
    }
@@ -652,7 +720,7 @@
 \end{verbatim}
 \end{small}
 
-A good safety would be to check the return value of ``find\_cipher()'' before accessing the desired function.  In order
+A good safety would be to check the return value of \textit{find\_cipher()} before accessing the desired function.  In order
 to use a cipher with the descriptor table you must register it first using:
 \index{register\_cipher()}
 \begin{verbatim}
@@ -665,7 +733,7 @@
 \begin{verbatim}
 int unregister_cipher(const struct _cipher_descriptor *cipher);
 \end{verbatim}
-Which returns {\bf CRYPT\_OK} if it removes it otherwise it returns {\bf CRYPT\_ERROR}.  Consider:
+Which returns {\bf CRYPT\_OK} if it removes the cipher, otherwise it returns {\bf CRYPT\_ERROR}.  
 \begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
@@ -691,9 +759,9 @@
 }
 \end{verbatim}
 \end{small}
-This snippet is a small program that registers only Rijndael only.  
-
-\section{Symmetric Modes of Operations}
+This snippet is a small program that registers Rijndael.  
+
+\mysection{Symmetric Modes of Operations}
 \subsection{Background}
 A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
 size of the cipher.  Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
@@ -763,84 +831,116 @@
 accomplish this by buffering the data required to complete a block.  This allows you to encrypt or decrypt any size 
 block of memory with either of the three modes.
 
-The ECB and CBC modes process blocks of the same size as the cipher at a time.  Therefore they are less flexible than the
+The ECB and CBC modes process blocks of the same size as the cipher at a time.  Therefore, they are less flexible than the
 other modes.
 
+\subsection{Ciphertext Stealing}
+\index{Ciphertext stealing}
+Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length.  This is accomplished
+by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext.  LibTomCrypt does not
+support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_encrypt() callback function.  
+
+The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.  
+
 \subsection{Initialization}
 \index{CBC Mode} \index{CTR Mode}
 \index{OFB Mode} \index{CFB Mode}
 The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages.  Assuming the mode 
-you want is XXX there is a structure called ``symmetric\_XXX'' that will contain the information required to
+you want is XXX there is a structure called \textit{symmetric\_XXX} that will contain the information required to
 use that mode.  They have identical setup routines (except CTR and ECB mode):
 \index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
 \begin{verbatim}
-int XXX_start(int cipher, const unsigned char *IV, 
-              const unsigned char *key, int keylen, 
-              int num_rounds, symmetric_XXX *XXX);
-
-int ctr_start(               int   cipher,
+int XXX_start(                int  cipher, 
+              const unsigned char *IV, 
+              const unsigned char *key, 
+                              int  keylen, 
+                              int  num_rounds, 
+                    symmetric_XXX *XXX);
+
+int ctr_start(                int  cipher,
               const unsigned char *IV,
-              const unsigned char *key,       int keylen,
-                             int  num_rounds, int ctr_mode,
-                   symmetric_CTR *ctr);
-
-int ecb_start(int cipher, const unsigned char *key, int keylen, 
-              int num_rounds, symmetric_ECB *ecb);
-\end{verbatim}
-
-In each case ``cipher'' is the index into the cipher\_descriptor array of the cipher you want to use.  The ``IV'' value is 
+              const unsigned char *key, 
+                              int  keylen,
+                              int  num_rounds, 
+                              int  ctr_mode,
+                    symmetric_CTR *ctr);
+
+int ecb_start(                int  cipher, 
+              const unsigned char *key, 
+                              int  keylen, 
+                              int  num_rounds, 
+                    symmetric_ECB *ecb);
+\end{verbatim}
+
+In each case, \textit{cipher} is the index into the cipher\_descriptor array of the cipher you want to use.  The \textit{IV} value is 
 the initialization vector to be used with the cipher.  You must fill the IV yourself and it is assumed they are the same 
-length as the block size\footnote{In otherwords the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.} 
+length as the block size\footnote{In other words the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.} 
 of the cipher you choose.  It is important that the IV  be random for each unique message you want to encrypt.  The 
-parameters ``key'', ``keylen'' and ``num\_rounds'' are the same as in the XXX\_setup() function call.  The final parameter 
+parameters \textit{key}, \textit{keylen} and \textit{num\_rounds} are the same as in the XXX\_setup() function call.  The final parameter 
 is a pointer to the structure you want to hold the information for the mode of operation.
 
 
-In the case of CTR mode there is an additional parameter ``ctr\_mode'' which specifies the mode that the counter is to be used in.
-If \textbf{CTR\_COUNTER\_LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value.  Otherwise, if 
-\textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value.
-
-The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code.  
+In the case of CTR mode there is an additional parameter \textit{ctr\_mode} which specifies the mode that the counter is to be used in.
+If \textbf{CTR\_COUNTER\_ LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value.  Otherwise, if 
+\textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value.  As of v1.15 the RFC 3686 style of
+increment then encrypt is also supported.  By OR'ing \textbf{LTC\_CTR\_RFC3686} with the CTR \textit{mode} value, ctr\_start() will increment
+the counter before encrypting it for the first time.
+
+The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise, they return an error code.  
 
 \subsection{Encryption and Decryption}
 To actually encrypt or decrypt the following routines are provided:
 \index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()} 
 \index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
 \begin{verbatim}
-int XXX_encrypt(const unsigned char *pt, unsigned char *ct, 
-                unsigned long len, symmetric_YYY *YYY);
-int XXX_decrypt(const unsigned char *ct, unsigned char *pt, 
-                unsigned long len, symmetric_YYY *YYY);
-\end{verbatim}
-Where ``XXX'' is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.  
-
-In all cases ``len'' is the size of the buffer (as number of octets) to encrypt or decrypt.  The CTR, OFB and CFB modes are order sensitive but not
-chunk sensitive.  That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F''
-and end up with the same ciphertext.  However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts.  All
+int XXX_encrypt(const unsigned char *pt, 
+                      unsigned char *ct, 
+                      unsigned long  len, 
+                      symmetric_YYY *YYY);
+
+int XXX_decrypt(const unsigned char *ct, 
+                      unsigned char *pt, 
+                      unsigned long  len, 
+                      symmetric_YYY *YYY);
+\end{verbatim}
+Where \textit{XXX} is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.  
+
+In all cases, \textit{len} is the size of the buffer (as number of octets) to encrypt or decrypt.  The CTR, OFB and CFB modes are order sensitive but not
+chunk sensitive.  That is you can encrypt \textit{ABCDEF} in three calls like \textit{AB}, \textit{CD}, \textit{EF} or two like \textit{ABCDE} and \textit{F}
+and end up with the same ciphertext.  However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts.  All
 five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
 
-In the ECB and CBC cases ``len'' must be a multiple of the ciphers block size.  In the CBC case you must manually pad the end of your message (either with
+In the ECB and CBC cases, \textit{len} must be a multiple of the ciphers block size.  In the CBC case, you must manually pad the end of your message (either with
 zeroes or with whatever your protocol requires).
 
-To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used)
-and use the decrypt routine on all of the blocks.
+To decrypt in either mode, perform the setup like before (recall you have to fetch the IV value you used), and use the decrypt routine on all of the blocks.
 
 \subsection{IV Manipulation}
 To change or read the IV of a previously initialized chaining mode use the following two functions.
-
 \index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
 \index{ctr\_setiv()} \index{ctr\_getiv()}
 \begin{verbatim}
-int XXX_getiv(unsigned char *IV, unsigned long *len, symmetric_XXX *XXX);
-int XXX_setiv(const unsigned char *IV, unsigned long len, symmetric_XXX *XXX);
-\end{verbatim}
-
-The XXX\_getiv() functions will read the IV out of the chaining mode and store it into ``IV'' along with the length of the IV 
-stored in ``len''.  The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified.  The length
+int XXX_getiv(unsigned char *IV, 
+              unsigned long *len, 
+              symmetric_XXX *XXX);
+
+int XXX_setiv(const unsigned char *IV, 
+                    unsigned long  len, 
+                    symmetric_XXX *XXX);
+\end{verbatim}
+
+The XXX\_getiv() functions will read the IV out of the chaining mode and store it into \textit{IV} along with the length of the IV 
+stored in \textit{len}.  The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified.  The length
 of the IV passed in must be the size of the ciphers block size.
 
 The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.  
 
+What the \textit{setiv} function will do depends on the mode being changed.  In CBC mode, the new IV replaces the existing IV as if it 
+were the last ciphertext block.  In CFB mode, the IV is encrypted as if it were the prior encrypted pad.  In CTR mode, the IV is encrypted without
+first incrementing it (regardless of the LTC\_RFC\_3686 flag presence).  In F8 mode, the IV is encrypted and becomes the new pad.  It does not change
+the salted IV, and is only meant to allow seeking within a session.  In LRW, it changes the tweak, forcing a computation of the tweak pad, allowing for
+seeking within the session.  In OFB mode, the IV is encrypted and becomes the new pad.
+
 \subsection{Stream Termination}
 To terminate an open stream call the done function.
 
@@ -851,9 +951,8 @@
 
 This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
 
+\newpage
 \subsection{Examples}
-
-\newpage
 \begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
@@ -876,10 +975,10 @@
         find_cipher("twofish"), /* index of desired cipher */
                             IV, /* the initial vector */
                            key, /* the secret key */
-                            16, /* length of secret key (16 bytes, 128 bits) */
+                            16, /* length of secret key (16 bytes) */
                              0, /* 0 == default # of rounds */
      CTR_COUNTER_LITTLE_ENDIAN, /* Little endian counter */
-                         &ctr)  /* where to store initialized CTR state */
+                         &ctr)  /* where to store the CTR state */
       ) != CRYPT_OK) {
       printf("ctr_start error: %s\n", error_to_string(err));
       return -1;
@@ -888,8 +987,8 @@
    /* somehow fill buffer than encrypt it */
    if ((err = ctr_encrypt(        buffer, /* plaintext */
                                   buffer, /* ciphertext */
-                          sizeof(buffer), /* length of data to encrypt */
-                                   &ctr)  /* previously initialized CTR state */
+                          sizeof(buffer), /* length of plaintext pt */
+                                   &ctr)  /* CTR state */
       ) != CRYPT_OK) {
       printf("ctr_encrypt error: %s\n", error_to_string(err));
       return -1;
@@ -908,8 +1007,8 @@
 
    if ((err = ctr_decrypt(        buffer, /* ciphertext */
                                   buffer, /* plaintext */
-                          sizeof(buffer), /* length of data to encrypt */
-                                   &ctr)  /* previously initialized CTR state */
+                          sizeof(buffer), /* length of plaintext */
+                                   &ctr)  /* CTR state */
       ) != CRYPT_OK) {
       printf("ctr_decrypt error: %s\n", error_to_string(err));
       return -1;
@@ -930,82 +1029,213 @@
 \end{verbatim}
 \end{small}
 
-\section{Encrypt and Authenticate Modes}
+\subsection{LRW Mode}
+LRW mode is a cipher mode which is meant for indexed encryption like used to handle storage media.  It is meant to have efficient seeking and overcome the 
+security problems of ECB mode while not increasing the storage requirements.  It is used much like any other chaining mode except with two key differences.
+
+The key is specified as two strings the first key $K_1$ is the (normally AES) key and can be any length (typically 16, 24 or 32 octets long).  The second key 
+$K_2$ is the \textit{tweak} key and is always 16 octets long.  The tweak value is \textbf{NOT} a nonce or IV value it must be random and secret.  
+
+To initialize LRW mode use:
+
+\index{lrw\_start()}
+\begin{verbatim}
+int lrw_start(                int  cipher,
+              const unsigned char *IV,
+              const unsigned char *key,       
+                              int  keylen,
+              const unsigned char *tweak,
+                              int  num_rounds, 
+                    symmetric_LRW *lrw);
+\end{verbatim}
+
+This will initialize the LRW context with the given (16 octet) \textit{IV}, cipher $K_1$ \textit{key} of length \textit{keylen} octets and the (16 octet) $K_2$ \textit{tweak}.  
+While LRW was specified to be used only with AES, LibTomCrypt will allow any 128--bit block cipher to be specified as indexed by \textit{cipher}.  The
+number of rounds for the block cipher \textit{num\_rounds} can be 0 to use the default number of rounds for the given cipher.
+
+To process data use the following functions:
+
+\index{lrw\_encrypt()} \index{lrw\_decrypt()}
+\begin{verbatim}
+int lrw_encrypt(const unsigned char *pt, 
+                      unsigned char *ct, 
+                      unsigned long  len, 
+                      symmetric_LRW *lrw);
+
+int lrw_decrypt(const unsigned char *ct, 
+                      unsigned char *pt, 
+                      unsigned long  len, 
+                      symmetric_LRW *lrw);
+\end{verbatim}
+
+These will encrypt (or decrypt) the plaintext to the ciphertext buffer (or vice versa).  The length is specified by \textit{len} in octets but must be a multiple
+of 16.  The LRW code uses a fast tweak update such that consecutive blocks are encrypted faster than if random seeking where used.  
+
+To manipulate the IV use the following functions:
+
+\index{lrw\_getiv()} \index{lrw\_setiv()} 
+\begin{verbatim}
+int lrw_getiv(unsigned char *IV, 
+              unsigned long *len, 
+              symmetric_LRW *lrw);
+
+int lrw_setiv(const unsigned char *IV, 
+                    unsigned long  len, 
+                    symmetric_LRW *lrw);
+\end{verbatim}
+These will get or set the 16--octet IV.  Note that setting the IV is the same as \textit{seeking} and unlike other modes is not a free operation.  It requires
+updating the entire tweak which is slower than sequential use.  Avoid seeking excessively in performance constrained code.
+
+To terminate the LRW state use the following:
+
+\index{lrw\_done()}
+\begin{verbatim}
+int lrw_done(symmetric_LRW *lrw);
+\end{verbatim}
+
+\subsection{F8 Mode}
+\index{F8 Mode}
+The F8 Chaining mode (see RFC 3711 for instance) is yet another chaining mode for block ciphers.  It behaves much like CTR mode in that it XORs a keystream
+against the plaintext to encrypt.  F8 mode comes with the additional twist that the counter value is secret, encrypted by a \textit{salt key}.  We
+initialize F8 mode with the following function call:
+
+\index{f8\_start()}
+\begin{verbatim}
+int f8_start(                int  cipher, 
+             const unsigned char *IV, 
+             const unsigned char *key,     
+                             int  keylen, 
+             const unsigned char *salt_key,               
+                             int  skeylen,
+                             int  num_rounds,   
+                    symmetric_F8 *f8);
+\end{verbatim}
+This will start the F8 mode state using \textit{key} as the secret key, \textit{IV} as the counter.  It uses the \textit{salt\_key} as IV encryption key 
+(\textit{m} in the RFC 3711).  The salt\_key can be shorter than the secret key but it should not be longer.  
+
+To encrypt or decrypt data we use the following two functions:
+
+\index{f8\_encrypt()} \index{f8\_decrypt()}
+\begin{verbatim}
+int f8_encrypt(const unsigned char *pt, 
+                     unsigned char *ct, 
+                     unsigned long  len, 
+                      symmetric_F8 *f8);
+
+int f8_decrypt(const unsigned char *ct, 
+                     unsigned char *pt, 
+                     unsigned long  len, 
+                      symmetric_F8 *f8);
+\end{verbatim}
+These will encrypt or decrypt a variable length array of bytes using the F8 mode state specified.  The length is specified in bytes and does not have to be a multiple 
+of the ciphers block size.
+
+To change or retrieve the current counter IV value use the following functions:
+\index{f8\_getiv()} \index{f8\_setiv()}
+\begin{verbatim}
+int f8_getiv(unsigned char *IV, 
+             unsigned long *len, 
+              symmetric_F8 *f8);
+
+int f8_setiv(const unsigned char *IV, 
+                   unsigned long  len, 
+                    symmetric_F8 *f8);
+\end{verbatim}
+These work with the current IV value only and not the encrypted IV value specified during the call to f8\_start().  The purpose of these two functions is to be
+able to seek within a current session only.  If you want to change the session IV you will have to call f8\_done() and then start a new state with
+f8\_start().
+
+To terminate an F8 state call the following function:
+
+\index{f8\_done()}
+\begin{verbatim}
+int f8_done(symmetric_F8 *f8);
+\end{verbatim}
+
+\vfil
+\mysection{Encrypt and Authenticate Modes}
 
 \subsection{EAX Mode}
 LibTomCrypt provides support for a mode called EAX\footnote{See 
-M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the
-way it was intended to be used by the designers.  First a short description of what EAX mode is before I explain how to use it.  
-EAX is a mode that requires a cipher, CTR and OMAC support and provides encryption and authentication\footnote{Note that since EAX only requires OMAC and CTR you may use ``encrypt only'' cipher descriptors with this mode.}.  
-It is initialized with a random ``nonce'' that can be shared publicly as well as a ``header'' which can be fixed and public as well as a random 
-secret symmetric key.
-
-The ``header'' data is meant to be meta-data associated with a stream that isn't private (e.g. protocol messages).  It can
-be added at anytime during an EAX stream and is part of the authentication tag.  That is, changes in the meta-data can
-be detected by changes in the output tag.
+M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the way it was intended to be used 
+by the designers.  First, a short description of what EAX mode is before we explain how to use it.  EAX is a mode that requires a cipher, 
+CTR and OMAC support and provides encryption and 
+authentication\footnote{Note that since EAX only requires OMAC and CTR you may use \textit{encrypt only} cipher descriptors with this mode.}.  
+It is initialized with a random \textit{nonce} that can be shared publicly, a \textit{header} which can be fixed and public, and a random secret symmetric key.
+
+The \textit{header} data is meant to be meta--data associated with a stream that isn't private (e.g., protocol messages).  It can
+be added at anytime during an EAX stream, and is part of the authentication tag.  That is, changes in the meta-data can be detected by changes in the output tag.
 
 The mode can then process plaintext producing ciphertext as well as compute a partial checksum.  The actual checksum
-called a ``tag'' is only emitted when the message is finished.  In the interim though the user can process any arbitrary
+called a \textit{tag} is only emitted when the message is finished.  In the interim, the user can process any arbitrary
 sized message block to send to the recipient as ciphertext.  This makes the EAX mode especially suited for streaming modes
 of operation.
 
 The mode is initialized with the following function.
 \index{eax\_init()}
 \begin{verbatim}
-int eax_init(eax_state *eax, int cipher, 
-             const unsigned char *key, unsigned long keylen,
-             const unsigned char *nonce, unsigned long noncelen,
-             const unsigned char *header, unsigned long headerlen);
-\end{verbatim}
-
-Where ``eax'' is the EAX state.  ``cipher'' is the index of the desired cipher in the descriptor table.  
-``key'' is the shared secret symmetric key of length ``keylen''.  ``nonce'' is the random public string of
-length ``noncelen''.  ``header'' is the random (or fixed or \textbf{NULL}) header for the message of length
-``headerlen''.
-
-When this function completes ``eax'' will be initialized such that you can now either have data decrypted or 
-encrypted in EAX mode.  Note that if ``headerlen'' is zero you may pass ``header'' as \textbf{NULL} to indicate
-there is no initial header data.
+int eax_init(          eax_state *eax, 
+                             int  cipher, 
+             const unsigned char *key, 
+                   unsigned long  keylen,
+             const unsigned char *nonce, 
+                   unsigned long  noncelen,
+             const unsigned char *header, 
+                   unsigned long  headerlen);
+\end{verbatim}
+
+Where \textit{eax} is the EAX state.  The \textit{cipher} parameter is the index of the desired cipher in the descriptor table.  
+The \textit{key} parameter is the shared secret symmetric key of length \textit{keylen} octets.  The \textit{nonce}