changeset 478:d4f32c3443ac dbclient-netcat-alike

propagate from branch 'au.asn.ucc.matt.dropbear' (head f21045c791002d81fc6b8dde6537ea481e513eb2) to branch 'au.asn.ucc.matt.dropbear.dbclient-netcat-alike' (head d1f69334581dc4c35f9ca16aa5355074c9dd315d)
author Matt Johnston <matt@ucc.asn.au>
date Sun, 14 Sep 2008 06:47:51 +0000
parents 6b41e2cbf071 (current diff) 657c045054ab (diff)
children 12d845ab7b5f
files cli-chansession.c cli-session.c debug.h 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
diffstat 593 files changed, 30036 insertions(+), 12501 deletions(-) [+]
line wrap: on
line diff
--- a/CHANGES	Tue Mar 21 16:16:41 2006 +0000
+++ b/CHANGES	Sun Sep 14 06:47:51 2008 +0000
@@ -1,3 +1,97 @@
+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	Tue Mar 21 16:16:41 2006 +0000
+++ b/INSTALL	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/LICENSE	Sun Sep 14 06:47:51 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-2006 Matt Johnston
 Portions copyright (c) 2004 Mihnea Stoenescu
 All rights reserved.
 
--- a/Makefile.in	Tue Mar 21 16:16:41 2006 +0000
+++ b/Makefile.in	Sun Sep 14 06:47:51 2008 +0000
@@ -64,12 +64,12 @@
 sbindir=${exec_prefix}/sbin
 
 CC=@CC@
-LD=@LD@
 AR=@AR@
 RANLIB=@RANLIB@
 STRIP=@STRIP@
 INSTALL=@INSTALL@
-CFLAGS=-I. -I$(srcdir)/libtomcrypt/src/headers/ @CFLAGS@
+CPPFLAGS=@CPPFLAGS@
+CFLAGS=-I. -I$(srcdir) -I$(srcdir)/libtomcrypt/src/headers/ $(CPPFLAGS) @CFLAGS@
 LIBS=$(LTC) $(LTM) @LIBS@
 LDFLAGS=@LDFLAGS@
 
@@ -155,11 +155,11 @@
 
 dropbear dbclient dropbearkey dropbearconvert: $(HEADERS)  $(LTC) $(LTM) \
 													Makefile
-	$(LD) $(LDFLAGS) -o $@$(EXEEXT) $($@objs) $(LIBS)
+	$(CC) $(LDFLAGS) -o $@$(EXEEXT) $($@objs) $(LIBS)
 
 # scp doesn't use the libs so is special.
 scp: $(SCPOBJS)  $(HEADERS) Makefile
-	$(LD) $(LDFLAGS) -o $@$(EXEEXT) $(SCPOBJS)
+	$(CC) $(LDFLAGS) -o $@$(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/auth.h	Tue Mar 21 16:16:41 2006 +0000
+++ b/auth.h	Sun Sep 14 06:47:51 2008 +0000
@@ -52,7 +52,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,9 +91,12 @@
 							   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;
 };
 
 struct SignKeyList;
--- a/channel.h	Tue Mar 21 16:16:41 2006 +0000
+++ b/channel.h	Sun Sep 14 06:47:51 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/cli-auth.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-auth.c	Sun Sep 14 06:47:51 2008 +0000
@@ -236,8 +236,8 @@
 
 void cli_auth_try() {
 
+	int finished = 0;
 	TRACE(("enter cli_auth_try"))
-	int finished = 0;
 
 	CHECKCLEARTOWRITE();
 	
@@ -281,11 +281,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	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-authinteract.c	Sun Sep 14 06:47:51 2008 +0000
@@ -99,13 +99,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	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-authpasswd.c	Sun Sep 14 06:47:51 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), "%s@%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	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-authpubkey.c	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-channel.c	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-chansession.c	Sun Sep 14 06:47:51 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 */
@@ -349,7 +350,7 @@
 	channel->errfd = STDERR_FILENO;
 	setnonblocking(STDERR_FILENO);
 
-	channel->extrabuf = cbuf_new(RECV_MAXWINDOW);
+	channel->extrabuf = cbuf_new(opts.recv_window);
 
 	if (cli_opts.wantpty) {
 		send_chansess_pty_req(channel);
--- a/cli-kex.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-kex.c	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-main.c	Sun Sep 14 06:47:51 2008 +0000
@@ -47,6 +47,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,
--- a/cli-runopts.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-runopts.c	Sun Sep 14 06:47:51 2008 +0000
@@ -44,12 +44,15 @@
 static void printhelp() {
 
 	fprintf(stderr, "Dropbear client v%s\n"
-					"Usage: %s [options] [user@]host\n"
+					"Usage: %s [options] [user@]host [command]\n"
 					"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"
 #ifdef ENABLE_CLI_PUBKEY_AUTH
 					"-i <identityfile>   (multiple allowed)\n"
 #endif
@@ -60,10 +63,14 @@
 #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 DEBUG_TRACE
 					"-v    verbose\n"
 #endif
-					,DROPBEAR_VERSION, cli_opts.progname);
+					,DROPBEAR_VERSION, cli_opts.progname,
+					DEFAULT_RECV_WINDOW, DEFAULT_KEEPALIVE);
+					
 }
 
 void cli_getopts(int argc, char ** argv) {
@@ -82,13 +89,19 @@
 #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;
 #ifdef ENABLE_CLI_PUBKEY_AUTH
 	cli_opts.privkeys = NULL;
 #endif
@@ -103,6 +116,7 @@
 	opts.ipv4 = 1;
 	opts.ipv6 = 1;
 	*/
+	opts.recv_window = DEFAULT_RECV_WINDOW;
 
 	/* Iterate all the arguments */
 	for (i = 1; i < (unsigned int)argc; i++) {
@@ -144,6 +158,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 +180,12 @@
 				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;
 #ifdef ENABLE_CLI_LOCALTCPFWD
 				case 'L':
 					nextislocal = 1;
@@ -183,6 +206,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;
@@ -269,6 +301,28 @@
 			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) {
+		opts.keepalive_secs = strtoul(keepalive_arg, NULL, 10);
+		if (opts.keepalive_secs == 0 && errno == EINVAL)
+		{
+			dropbear_exit("Bad keepalive '%s'", keepalive_arg);
+		}
+	}
+	
 }
 
 #ifdef ENABLE_CLI_PUBKEY_AUTH
@@ -348,7 +402,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 +413,7 @@
 		TRACE(("connectaddr == NULL"))
 		goto fail;
 	}
-
-	connectaddr[0] = '\0';
+	*connectaddr = '\0';
 	connectaddr++;
 
 	connectport = strchr(connectaddr, ':');
@@ -367,8 +421,7 @@
 		TRACE(("connectport == NULL"))
 		goto fail;
 	}
-
-	connectport[0] = '\0';
+	*connectport = '\0';
 	connectport++;
 
 	newfwd = (struct TCPFwdList*)m_malloc(sizeof(struct TCPFwdList));
--- a/cli-service.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-service.c	Sun Sep 14 06:47:51 2008 +0000
@@ -82,6 +82,4 @@
 	}
 
 	dropbear_exit("unrecognised service accept");
-	/* m_free(servicename); not reached */
-
 }
--- a/cli-session.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/cli-session.c	Sun Sep 14 06:47:51 2008 +0000
@@ -212,19 +212,38 @@
 			*/
 
 		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"))
+			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();
 			}
 
--- a/common-algo.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/common-algo.c	Sun Sep 14 06:47:51 2008 +0000
@@ -31,6 +31,8 @@
 
 /* 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
 static const struct dropbear_cipher dropbear_aes256 = 
--- a/common-channel.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/common-channel.c	Sun Sep 14 06:47:51 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,10 +571,6 @@
 	TRACE(("enter recv_msg_channel_request"))
 	
 	channel = getchannel();
-	if (channel == NULL) {
-		/* disconnect ? */
-		dropbear_exit("Unknown channel");
-	}
 
 	if (channel->type->reqhandler) {
 		channel->type->reqhandler(channel);
@@ -562,26 +587,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 +611,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 +666,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 +682,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 +722,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 +736,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 +762,6 @@
 }
 	
 /* Handle a new channel request, performing any channel-type-specific setup */
-/* XXX server */
 void recv_msg_channel_open() {
 
 	unsigned char *type;
@@ -755,9 +781,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 +818,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 +908,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 +982,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 +999,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 +1016,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 +1031,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	Tue Mar 21 16:16:41 2006 +0000
+++ b/common-kex.c	Sun Sep 14 06:47:51 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,17 +292,20 @@
 	hashkeys(C2S_key, C2S_keysize, &hs, 'C');
 	hashkeys(S2C_key, S2C_keysize, &hs, 'D');
 
-	if (cbc_start(
-		find_cipher(ses.newkeys->recv_algo_crypt->cipherdesc->name),
-			recv_IV, recv_key, 
+	recv_cipher = find_cipher(ses.newkeys->recv_algo_crypt->cipherdesc->name);
+	if (recv_cipher < 0)
+	    dropbear_exit("crypto error");
+		
+	if (cbc_start(recv_cipher, recv_IV, recv_key, 
 			ses.newkeys->recv_algo_crypt->keysize, 0, 
 			&ses.newkeys->recv_symmetric_struct) != CRYPT_OK) {
 		dropbear_exit("crypto error");
 	}
-
-	if (cbc_start(
-		find_cipher(ses.newkeys->trans_algo_crypt->cipherdesc->name),
-			trans_IV, trans_key, 
+	trans_cipher = find_cipher(ses.newkeys->trans_algo_crypt->cipherdesc->name);
+	if (trans_cipher < 0)
+	    dropbear_exit("crypto error");
+		
+	if (cbc_start(trans_cipher, trans_IV, trans_key, 
 			ses.newkeys->trans_algo_crypt->keysize, 0, 
 			&ses.newkeys->trans_symmetric_struct) != CRYPT_OK) {
 		dropbear_exit("crypto error");
@@ -517,7 +514,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] */
--- a/common-session.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/common-session.c	Sun Sep 14 06:47:51 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 */
@@ -59,11 +61,18 @@
 	ses.sock = sock;
 	ses.maxfd = sock;
 
-	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,9 +83,12 @@
 	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));
@@ -108,7 +120,6 @@
 
 	ses.allowprivport = 0;
 
-
 	TRACE(("leave session_init"))
 }
 
@@ -121,7 +132,7 @@
 	/* 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);
@@ -132,6 +143,10 @@
 				FD_SET(ses.sock, &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,27 +158,29 @@
 			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 != -1) {
@@ -181,6 +198,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 ) */
@@ -229,7 +250,7 @@
 	/* write our version string, this blocks */
 	if (atomicio(write, ses.sock, 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 */
@@ -250,7 +271,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 +362,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 +387,27 @@
 	}
 
 	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;
+}
--- a/config.guess	Tue Mar 21 16:16:41 2006 +0000
+++ b/config.guess	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/config.sub	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/configure.in	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/dbclient.1	Sun Sep 14 06:47:51 2008 +0000
@@ -29,24 +29,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,10 +59,46 @@
 .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.
+.SH ENVIRONMENT
+.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.
+.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.
 .SH AUTHOR
 Matt Johnston ([email protected]).
 .br
--- a/dbutil.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/dbutil.c	Sun Sep 14 06:47:51 2008 +0000
@@ -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))
@@ -400,7 +400,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 +412,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 +452,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 +461,7 @@
 		len = sizeof(struct sockaddr_in6);
 	}
 #endif
+#endif
 
 
 	ret = getnameinfo((struct sockaddr*)addr, len, hbuf, sizeof(hbuf),
@@ -521,26 +527,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 +693,9 @@
 	}
 	TRACE(("leave setnonblocking"))
 }
+
+void disallow_core() {
+	struct rlimit lim;
+	lim.rlim_cur = lim.rlim_max = 0;
+	setrlimit(RLIMIT_CORE, &lim);
+}
--- a/dbutil.h	Tue Mar 21 16:16:41 2006 +0000
+++ b/dbutil.h	Sun Sep 14 06:47:51 2008 +0000
@@ -63,6 +63,7 @@
 void __m_free(void* ptr);
 void m_burn(void* data, unsigned int len);
 void setnonblocking(int fd);
+void disallow_core();
 
 /* Used to force mp_ints to be initialised */
 #define DEF_MP_INT(X) mp_int X = {0, 0, 0, NULL}
--- a/debian/README.runit	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/README.runit	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/changelog	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/control	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/dropbear.README.Debian	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/dropbear.init	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/dropbear.postinst	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/implicit	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debian/rules	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/debug.h	Sun Sep 14 06:47:51 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.
--- a/dropbear.8	Tue Mar 21 16:16:41 2006 +0000
+++ b/dropbear.8	Sun Sep 14 06:47:51 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,24 @@
 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 AUTHOR
 Matt Johnston ([email protected]).
 .br
--- a/dropbearkey.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/dropbearkey.c	Sun Sep 14 06:47:51 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 user@host 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 %s@%s\nFingerprint: %s\n",
+			typestring, base64key, username, hostname, fp);
 
 	m_free(fp);
 	buf_free(buf);
--- a/dss.c	Tue Mar 21 16:16:41 2006 +0000
+++ b/dss.c	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/genrsa.c	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/includes.h	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/kex.h	Sun Sep 14 06:47:51 2008 +0000
@@ -53,7 +53,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	Tue Mar 21 16:16:41 2006 +0000
+++ b/keyimport.c	Sun Sep 14 06:47:51 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);
 	}
@@ -926,40 +929,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 +945,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	Tue Mar 21 16:16:41 2006 +0000
+++ b/libtomcrypt/Doxyfile	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/libtomcrypt/Makefile.in	Sun Sep 14 06:47:51 2008 +0000
@@ -4,7 +4,7 @@
 # Modified by Clay Culver
 
 # The version
-VERSION=1.05
+VERSION=1.16
 
 VPATH=@srcdir@
 srcdir=@srcdir@
@@ -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) $@ $(OBJECTS) 
-	$(RANLIB) $(LIBNAME)
+	$(RANLIB) $@
 
 #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	Sun Sep 14 06:47:51 2008 +0000
@@ -0,0 +1,3 @@
+See doc/crypt.pdf
+
+
--- a/libtomcrypt/TODO	Tue Mar 21 16:16:41 2006 +0000
+++ b/libtomcrypt/TODO	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/libtomcrypt/build.sh	Sun Sep 14 06:47:51 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	Tue Mar 21 16:16:41 2006 +0000
+++ b/libtomcrypt/changes	Sun Sep 14 06:47:51 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	Sun Sep 14 06:47:51 2008 +0000
@@ -0,0 +1,24 @@
+\addvspace {10\p@ }
+\addvspace {10\p@ }
+\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\p@ }
+\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\p@ }
+\contentsline {figure}{\numberline {4.1}{\ignorespaces Built--In Software Hashes}}{57}{figure.4.1}
+\addvspace {10\p@ }
+\addvspace {10\p@ }
+\contentsline {figure}{\numberline {6.1}{\ignorespaces List of Provided PRNGs}}{82}{figure.6.1}
+\addvspace {10\p@ }
+\addvspace {10\p@ }
+\addvspace {10\p@ }
+\contentsline {figure}{\numberline {9.1}{\ignorespaces DSA Key Sizes}}{119}{figure.9.1}
+\addvspace {10\p@ }
+\contentsline {figure}{\numberline {10.1}{\ignorespaces List of ASN.1 Supported Types}}{127}{figure.10.1}
+\addvspace {10\p@ }
+\addvspace {10\p@ }
+\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\p@ }
+\addvspace {10\p@ }
--- a/libtomcrypt/crypt.tex	Tue Mar 21 16:16:41 2006 +0000
+++ b/libtomcrypt/crypt.tex	Sun Sep 14 06:47:51 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} parameter is the 
+random public string of length \textit{noncelen} octets.  The \textit{header} parameter is the random (or fixed or \textbf{NULL}) header for the 
+message of length \textit{headerlen} octets.
+
+When this function completes, the \textit{eax} state will be initialized such that you can now either have data decrypted or 
+encrypted in EAX mode.  Note: if \textit{headerlen} is zero you may pass \textit{header} as \textbf{NULL} to indicate there is no initial header data.
 
 To encrypt or decrypt data in a streaming mode use the following.
 \index{eax\_encrypt()} \index{eax\_decrypt()}
 \begin{verbatim}
-int eax_encrypt(eax_state *eax, const unsigned char *pt, 
-                unsigned char *ct, unsigned long length);
-
-int eax_decrypt(eax_state *eax, const unsigned char *ct, 
-                unsigned char *pt, unsigned long length);
-\end{verbatim}
-The function ``eax\_encrypt'' will encrypt the bytes in ``pt'' of ``length'' bytes and store the ciphertext in
-``ct''.  Note that ``ct'' and ``pt'' may be the same region in memory.   This function will also send the ciphertext
-through the OMAC function.  The function ``eax\_decrypt'' decrypts ``ct'' and stores it in ``pt''.  This also allows 
-``pt'' and ``ct'' to be the same region in memory.  
-
-You cannot both encrypt or decrypt with the same ``eax'' context.  For bi-directional communication you
-will need to initialize two EAX contexts (preferably with different headers and nonces).  
-
-Note that both of these functions allow you to send the data in any granularity but the order is important.  While
+int eax_encrypt(          eax_state *eax, 
+                const unsigned char *pt, 
+                      unsigned char *ct, 
+                      unsigned long  length);
+
+int eax_decrypt(          eax_state *eax, 
+                const unsigned char *ct, 
+                      unsigned char *pt, 
+                      unsigned long  length);
+\end{verbatim}
+The function \textit{eax\_encrypt} will encrypt the bytes in \textit{pt} of \textit{length} octets, and store the ciphertext in
+\textit{ct}.  Note: \textit{ct} and \textit{pt} may be the same region in memory.   This function will also send the ciphertext
+through the OMAC function.  The function \textit{eax\_decrypt} decrypts \textit{ct}, and stores it in \textit{pt}.  This also allows 
+\textit{pt} and \textit{ct} to be the same region in memory.  
+
+You cannot both encrypt or decrypt with the same \textit{eax} context.  For bi--directional communication you will need to initialize 
+two EAX contexts (preferably with different headers and nonces).  
+
+Note: both of these functions allow you to send the data in any granularity but the order is important.  While
 the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
 EAX stream with the following.
 
 \index{eax\_addheader()}
 \begin{verbatim}
-int eax_addheader(eax_state *eax, 
-                  const unsigned char *header, unsigned long length);
-\end{verbatim}
-
-This will add the ``length'' bytes from ``header'' to the given ``eax'' stream.  Once the message is finished the 
-``tag'' (checksum) may be computed with the following function.
+int eax_addheader(          eax_state *eax, 
+                  const unsigned char *header, 
+                        unsigned long  length);
+\end{verbatim}
+This will add the \textit{length} octet from \textit{header} to the given \textit{eax} header.  Once the message is finished, the 
+\textit{tag} (checksum) may be computed with the following function:
 
 \index{eax\_done()}
 \begin{verbatim}
-int eax_done(eax_state *eax, 
-             unsigned char *tag, unsigned long *taglen);
-\end{verbatim}
-This will terminate the EAX state ``eax'' and store upto ``taglen'' bytes of the message tag in ``tag''.  The function
-then stores how many bytes of the tag were written out back into ``taglen''.
-
-The EAX mode code can be tested to ensure it matches the test vectors by calling the following function.
+int eax_done(    eax_state *eax, 
+             unsigned char *tag, 
+             unsigned long *taglen);
+\end{verbatim}
+This will terminate the EAX state \textit{eax}, and store up to \textit{taglen} bytes of the message tag in \textit{tag}.  The function
+then stores how many bytes of the tag were written out back in to \textit{taglen}.
+
+The EAX mode code can be tested to ensure it matches the test vectors by calling the following function:
 \index{eax\_test()}
 \begin{verbatim}
 int eax_test(void);
@@ -1029,22 +1259,22 @@
    /* ... make up random nonce and key ... */
 
    /* initialize context */
-   if ((err = eax_init(            &eax,  /* the context */
-                find_cipher("rijndael"),  /* cipher we want to use */
-                                  nonce,  /* our state nonce */
-                                     16,  /* none is 16 bytes */
-                              "TestApp",  /* example header, identifies this program */
-                                      7)  /* length of the header */
+   if ((err = eax_init(            &eax,  /* context */
+                find_cipher("rijndael"),  /* cipher id */
+                                  nonce,  /* the nonce */
+                                     16,  /* nonce is 16 bytes */
+                              "TestApp",  /* example header */
+                                      7)  /* header length */
        ) != CRYPT_OK) {
       printf("Error eax_init: %s", error_to_string(err));
       return EXIT_FAILURE;
    }
 
    /* now encrypt data, say in a loop or whatever */
-   if ((err = eax_encrypt(     &eax,      /* eax context */
-                                 pt,      /* plaintext  (source) */
-                                 ct,      /* ciphertext (destination) */
-                          sizeof(pt)      /* size of plaintext */
+   if ((err = eax_encrypt(     &eax, /* eax context */
+                                 pt, /* plaintext  (source) */
+                                 ct, /* ciphertext (destination) */
+                          sizeof(pt) /* size of plaintext */
       ) != CRYPT_OK) {
       printf("Error eax_encrypt: %s", error_to_string(err));
       return EXIT_FAILURE;
@@ -1052,16 +1282,16 @@
 
    /* finish message and get authentication tag */
    taglen = sizeof(tag);
-   if ((err = eax_done(   &eax,           /* eax context */
-                           tag,           /* where to put tag */
-                       &taglen            /* length of tag space */
+   if ((err = eax_done(   &eax,      /* eax context */
+                           tag,      /* where to put tag */
+                       &taglen       /* length of tag space */
       ) != CRYPT_OK) {
       printf("Error eax_done: %s", error_to_string(err));
       return EXIT_FAILURE;
    }
 
-   /* now we have the authentication tag in "tag" and it's taglen bytes long */
-
+   /* now we have the authentication tag in "tag" and 
+    * it's taglen bytes long */
 }
 \end{verbatim}
                        
@@ -1071,7 +1301,8 @@
 
 \index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
 \begin{verbatim}
-int eax_encrypt_authenticate_memory(int cipher,
+int eax_encrypt_authenticate_memory(
+                    int  cipher,
     const unsigned char *key,    unsigned long keylen,
     const unsigned char *nonce,  unsigned long noncelen,
     const unsigned char *header, unsigned long headerlen,
@@ -1079,7 +1310,8 @@
           unsigned char *ct,
           unsigned char *tag,    unsigned long *taglen);
 
-int eax_decrypt_verify_memory(int cipher,
+int eax_decrypt_verify_memory(
+                    int  cipher,
     const unsigned char *key,    unsigned long keylen,
     const unsigned char *nonce,  unsigned long noncelen,
     const unsigned char *header, unsigned long headerlen,
@@ -1093,38 +1325,45 @@
 have the same meaning as with those respective functions.  
 
 The only difference is eax\_decrypt\_verify\_memory() does not emit a tag.  Instead you pass it a tag as input and it compares it against
-the tag it computed while decrypting the message.  If the tags match then it stores a $1$ in ``res'', otherwise it stores a $0$.
+the tag it computed while decrypting the message.  If the tags match then it stores a $1$ in \textit{res}, otherwise it stores a $0$.
 
 \subsection{OCB Mode}
 LibTomCrypt provides support for a mode called OCB\footnote{See 
-P. Rogaway, M. Bellare, J. Black, T. Krovetz, ``OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption''.}
+P. Rogaway, M. Bellare, J. Black, T. Krovetz, \textit{OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption}.}
 .  OCB is an encryption protocol that simultaneously provides authentication.  It is slightly faster to use than EAX mode
 but is less flexible.  Let's review how to initialize an OCB context.
 
 \index{ocb\_init()}
 \begin{verbatim}
-int ocb_init(ocb_state *ocb, int cipher, 
-             const unsigned char *key, unsigned long keylen, 
+int ocb_init(          ocb_state *ocb, 
+                             int  cipher, 
+             const unsigned char *key, 
+                   unsigned long  keylen, 
              const unsigned char *nonce);
 \end{verbatim}
 
-This will initialize the ``ocb'' context using cipher descriptor ``cipher''.  It will use a ``key'' of length ``keylen''
-and the random ``nonce''.  Note that ``nonce'' must be a random (public) string the same length as the block ciphers
+This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}.  It will use a \textit{key} of length \textit{keylen}
+and the random \textit{nonce}.  Note that \textit{nonce} must be a random (public) string the same length as the block ciphers
 block size (e.g. 16 bytes for AES).
 
-This mode has no ``Associated Data'' like EAX mode does which means you cannot authenticate metadata along with the stream.
+This mode has no \textit{Associated Data} like EAX mode does which means you cannot authenticate metadata along with the stream.
 To encrypt or decrypt data use the following.
 
 \index{ocb\_encrypt()} \index{ocb\_decrypt()}
 \begin{verbatim}
-int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
-int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);
-\end{verbatim}
-
-This will encrypt (or decrypt for the latter) a fixed length of data from ``pt'' to ``ct'' (vice versa for the latter).  
-They assume that ``pt'' and ``ct'' are the same size as the block cipher's block size.  Note that you cannot call 
-both functions given a single ``ocb'' state.  For bi-directional communication you will have to initialize two ``ocb''
-states (with different nonces).  Also ``pt'' and ``ct'' may point to the same location in memory.
+int ocb_encrypt(          ocb_state *ocb, 
+                const unsigned char *pt, 
+                      unsigned char *ct);
+
+int ocb_decrypt(          ocb_state *ocb, 
+                const unsigned char *ct, 
+                      unsigned char *pt);
+\end{verbatim}
+
+This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).  
+They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size.  Note that you cannot call 
+both functions given a single \textit{ocb} state.  For bi-directional communication you will have to initialize two \textit{ocb}
+states (with different nonces).  Also \textit{pt} and \textit{ct} may point to the same location in memory.
 
 \subsubsection{State Termination}
 
@@ -1132,41 +1371,45 @@
 
 \index{ocb\_done\_encrypt()}
 \begin{verbatim}
-int ocb_done_encrypt(ocb_state *ocb, 
-                     const unsigned char *pt, unsigned long ptlen,
+int ocb_done_encrypt(          ocb_state *ocb, 
+                     const unsigned char *pt, 
+                           unsigned long  ptlen,
                            unsigned char *ct, 
-                           unsigned char *tag, unsigned long *taglen);
-\end{verbatim}
-
-This will terminate an encrypt stream ``ocb''.  If you have trailing bytes of plaintext that will not complete a block 
-you can pass them here.  This will also encrypt the ``ptlen'' bytes in ``pt'' and store them in ``ct''.  It will also
-store upto ``taglen'' bytes of the tag into ``tag''.
-
-Note that ``ptlen'' must be less than or equal to the block size of block cipher chosen.  Also note that if you have 
+                           unsigned char *tag, 
+                           unsigned long *taglen);
+\end{verbatim}
+
+This will terminate an encrypt stream \textit{ocb}.  If you have trailing bytes of plaintext that will not complete a block 
+you can pass them here.  This will also encrypt the \textit{ptlen} bytes in \textit{pt} and store them in \textit{ct}.  It will also
+store up to \textit{taglen} bytes of the tag into \textit{tag}.
+
+Note that \textit{ptlen} must be less than or equal to the block size of block cipher chosen.  Also note that if you have 
 an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.  
 
 To terminate a decrypt stream and compared the tag you call the following.
 
 \index{ocb\_done\_decrypt()}
 \begin{verbatim}
-int ocb_done_decrypt(ocb_state *ocb, 
-                     const unsigned char *ct,  unsigned long ctlen,
+int ocb_done_decrypt(          ocb_state *ocb, 
+                     const unsigned char *ct,  
+                           unsigned long  ctlen,
                            unsigned char *pt, 
-                     const unsigned char *tag, unsigned long taglen, 
-                           int *res);
-\end{verbatim}
-
+                     const unsigned char *tag, 
+                           unsigned long  taglen, 
+                                     int *res);
+\end{verbatim}
 Similarly to the previous function you can pass trailing message bytes into this function.  This will compute the 
-tag of the message (internally) and then compare it against the ``taglen'' bytes of ``tag'' provided.  By default
-``res'' is set to zero.  If all ``taglen'' bytes of ``tag'' can be verified then ``res'' is set to one (authenticated
+tag of the message (internally) and then compare it against the \textit{taglen} bytes of \textit{tag} provided.  By default
+\textit{res} is set to zero.  If all \textit{taglen} bytes of \textit{tag} can be verified then \textit{res} is set to one (authenticated
 message).
 
 \subsubsection{Packet Functions}
 To make life simpler the following two functions are provided for memory bound OCB.
 
-\index{ocb\_encrypt\_authenticate\_memory()}
-\begin{verbatim}
-int ocb_encrypt_authenticate_memory(int cipher,
+%\index{ocb\_encrypt\_authenticate\_memory()}
+\begin{verbatim}
+int ocb_encrypt_authenticate_memory(
+                    int  cipher,
     const unsigned char *key,    unsigned long keylen,
     const unsigned char *nonce,  
     const unsigned char *pt,     unsigned long ptlen,
@@ -1174,12 +1417,13 @@
           unsigned char *tag,    unsigned long *taglen);
 \end{verbatim}
 
-This will OCB encrypt the message ``pt'' of length ``ptlen'' and store the ciphertext in ``ct''.  The length ``ptlen''
+This will OCB encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}.  The length \textit{ptlen}
 can be any arbitrary length.  
 
 \index{ocb\_decrypt\_verify\_memory()}
 \begin{verbatim}
-int ocb_decrypt_verify_memory(int cipher,
+int ocb_decrypt_verify_memory(
+                    int  cipher,
     const unsigned char *key,    unsigned long keylen,
     const unsigned char *nonce,  
     const unsigned char *ct,     unsigned long ctlen,
@@ -1188,18 +1432,20 @@
           int           *res);
 \end{verbatim}
 
-Similarly this will OCB decrypt and compare the internally computed tag against the tag provided. ``res'' is set 
+Similarly, this will OCB decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set 
 appropriately.
 
 \subsection{CCM Mode}
-CCM is a NIST proposal for Encrypt+Authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.  Unlike EAX and OCB mode
-it is only meant for ``packet'' mode where the length of the input is known in advance.  Since it is a packet mode function CCM only has one 
+CCM is a NIST proposal for encrypt + authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.  Unlike EAX and OCB mode,
+it is only meant for \textit{packet} mode where the length of the input is known in advance.  Since it is a packet mode function, CCM only has one 
 function that performs the protocol.
 
 \index{ccm\_memory()}
 \begin{verbatim}
-int ccm_memory(int cipher,
+int ccm_memory(
+                    int  cipher,
     const unsigned char *key,    unsigned long keylen,
+    symmetric_key       *uskey,
     const unsigned char *nonce,  unsigned long noncelen,
     const unsigned char *header, unsigned long headerlen,
           unsigned char *pt,     unsigned long ptlen,
@@ -1208,16 +1454,22 @@
                     int  direction);
 \end{verbatim}
 
-This performs the ``CCM'' operation on the data.  The ``cipher'' variable indicates which cipher in the descriptor table to use.  It must have a 
-16--byte block size for CCM.  The key is ``key'' with a length of ``keylen'' octets.  The nonce or salt is ``nonce'' of
-length ``noncelen'' octets.  The header is meta--data you want to send with the message but not have encrypted, it is stored in ``header''
-of length ``headerlen'' octets.  The header can be zero octets long (if $headerlen = 0$ then you can pass ``header'' as \textbf{NULL}).  
-
-The plaintext is stored in ``pt'' and the ciphertext in ``ct''.  The length of both are expected to be equal and is passed in as ``ptlen''.  It is
-allowable that $pt = ct$.  The ``direction'' variable indicates whether encryption (direction $=$ \textbf{CCM\_ENCRYPT}) or 
+This performs the \textit{CCM} operation on the data.  The \textit{cipher} variable indicates which cipher in the descriptor table to use.  It must have a 
+16--byte block size for CCM.  
+
+The key can be specified in one of two fashions.  First, it can be passed as an array of octets in \textit{key} of length \textit{keylen}.  Alternatively,
+it can be passed in as a previously scheduled key in \textit{uskey}.  The latter fashion saves time when the same key is used for multiple packets.  If
+\textit{uskey} is not \textbf{NULL}, then \textit{key} may be \textbf{NULL} (and vice-versa). 
+
+The nonce or salt is \textit{nonce} of length \textit{noncelen} octets.  The header is meta--data you want to send with the message but not have 
+encrypted, it is stored in \textit{header} of length \textit{headerlen} octets.  The header can be zero octets long (if $headerlen = 0$ then 
+you can pass \textit{header} as \textbf{NULL}).  
+
+The plaintext is stored in \textit{pt}, and the ciphertext in \textit{ct}.  The length of both are expected to be equal and is passed in as \textit{ptlen}.  It is
+allowable that $pt = ct$.  The \textit{direction} variable indicates whether encryption (direction $=$ \textbf{CCM\_ENCRYPT}) or 
 decryption (direction $=$ \textbf{CCM\_DECRYPT}) is to be performed.
 
-As implemented this copy of CCM cannot handle a header or plaintext longer than $2^{32} - 1$ octets long.  
+As implemented, this version of CCM cannot handle header or plaintext data longer than $2^{32} - 1$ octets long.  
 
 You can test the implementation of CCM with the following function.
 
@@ -1226,102 +1478,167 @@
 int ccm_test(void);
 \end{verbatim}
 
-This will return \textbf{CRYPT\_OK} if the CCM routine passes known test vectors.
+This will return \textbf{CRYPT\_OK} if the CCM routine passes known test vectors.  It requires AES or Rijndael to be registered previously, otherwise it will
+return \textbf{CRYPT\_NOP}.
+
+\subsubsection{CCM Example}
+The following is a sample of how to call CCM.
+
+\begin{small}
+\begin{verbatim}
+#include <tomcrypt.h>
+int main(void)
+{
+   unsigned char key[16], nonce[12], pt[32], ct[32], 
+                 tag[16], tagcp[16];
+   unsigned long taglen;
+   int           err;
+
+   /* register cipher */
+   register_cipher(&aes_desc);
+
+   /* somehow fill key, nonce, pt */
+ 
+   /* encrypt it */
+   taglen = sizeof(tag);
+   if ((err = 
+       ccm_memory(find_cipher("aes"),
+                  key, 16,    /* 128-bit key */
+                  NULL,       /* not prescheduled */
+                  nonce, 12,  /* 96-bit nonce */
+                  NULL, 0,    /* no header */
+                  pt, 32,     /* 32-byte plaintext */
+                  ct,         /* ciphertext */
+                  tag, &taglen,
+                  CCM_ENCRYPT)) != CRYPT_OK) {
+       printf("ccm_memory error %s\n", error_to_string(err));
+       return -1;
+   }
+   /* ct[0..31] and tag[0..15] now hold the output */
+
+   /* decrypt it */
+   taglen = sizeof(tagcp);
+   if ((err = 
+       ccm_memory(find_cipher("aes"),
+                  key, 16,    /* 128-bit key */
+                  NULL,       /* not prescheduled */
+                  nonce, 12,  /* 96-bit nonce */
+                  NULL, 0,    /* no header */
+                  ct, 32,     /* 32-byte ciphertext */
+                  pt,         /* plaintext */
+                  tagcp, &taglen,
+                  CCM_DECRYPT)) != CRYPT_OK) {
+       printf("ccm_memory error %s\n", error_to_string(err));
+       return -1;
+   }
+
+   /* now pt[0..31] should hold the original plaintext,
+      tagcp[0..15] and tag[0..15] should have the same contents */
+}
+\end{verbatim}
+\end{small}
 
 \subsection{GCM Mode}
-Galois counter mode is an IEEE proposal for authenticated encryption.  Like EAX and OCB it can be used in a streaming capacity however, unlike EAX it cannot
-accept ``additional authentication data'' (meta--data) after plaintext has been processed.  This mode also only works with block ciphers with a sixteen
-byte block.
-
-A GCM stream is meant to be processed in three modes each one sequential serial.  First the initial vector (per session) data is processed.  This should be 
-unique to every session.  Next the the optional additional authentication data is processed and finally the plaintext.  
+Galois counter mode is an IEEE proposal for authenticated encryption (also it is a planned NIST standard).  Like EAX and OCB mode, it can be used in a streaming capacity 
+however, unlike EAX it cannot accept \textit{additional authentication data} (meta--data) after plaintext has been processed.  This mode also only works with 
+block ciphers with a 16--byte block.
+
+A GCM stream is meant to be processed in three modes, one after another.  First, the initial vector (per session) data is processed.  This should be 
+unique to every session.  Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).  
 
 \subsubsection{Initialization}
 To initialize the GCM context with a secret key call the following function.
 
 \index{gcm\_init()}
 \begin{verbatim}
-int gcm_init(gcm_state *gcm, int cipher,
-             const unsigned char *key, int keylen);
-\end{verbatim}
-This initializes the GCM state ``gcm'' for the given cipher indexed by ``cipher'' with a secret key ``key'' of length ``keylen'' octets.  The cipher chosen
-must have a 16--byte block size (e.g. AES).  
+int gcm_init(          gcm_state *gcm, 
+                             int  cipher,
+             const unsigned char *key, 
+                             int  keylen);
+\end{verbatim}
+This initializes the GCM state \textit{gcm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets.  The cipher 
+chosen must have a 16--byte block size (e.g., AES).  
 
 \subsubsection{Initial Vector}
 After the state has been initialized (or reset) the next step is to add the session (or packet) initial vector.  It should be unique per packet encrypted.
 
 \index{gcm\_add\_iv()}
 \begin{verbatim}
-int gcm_add_iv(gcm_state *gcm, 
-               const unsigned char *IV,     unsigned long IVlen);
-\end{verbatim}
-
-This adds the initial vector octets from ``IV'' of length ``IVlen'' to the GCM state ``gcm''.  You can call this function as many times as required
+int gcm_add_iv(          gcm_state *gcm, 
+               const unsigned char *IV,     
+                     unsigned long  IVlen);
+\end{verbatim}
+This adds the initial vector octets from \textit{IV} of length \textit{IVlen} to the GCM state \textit{gcm}.  You can call this function as many times as required
 to process the entire IV.  
 
-Note that the GCM protocols provides a ``shortcut'' for 12--byte IVs where no preprocessing is to be done.  If you want to minimize per packet latency it's ideal
-to only use 12--byte IVs.  You can just increment it like a counter for each packet and the CTR [privacy] will be ensured.
+Note: the GCM protocols provides a \textit{shortcut} for 12--byte IVs where no pre-processing is to be done.  If you want to minimize per packet latency it is ideal
+to only use 12--byte IVs.  You can just increment it like a counter for each packet.
 
 \subsubsection{Additional Authentication Data}
-After the entire IV has been processed the additional authentication data can be processed.  Unlike the IV a packet/session does not require additional
-authentication data (AAD) for security.  The AAD is meant to be used as side--channel data you want to be authenticated with the packet.  Note that once
-you begin adding AAD to the GCM state you cannot return to adding IV data until the state is reset.
+After the entire IV has been processed, the additional authentication data can be processed.  Unlike the IV, a packet/session does not require additional
+authentication data (AAD) for security.  The AAD is meant to be used as side--channel data you want to be authenticated with the packet.  Note:  once
+you begin adding AAD to the GCM state you cannot return to adding IV data until the state has been reset.
 
 \index{gcm\_add\_aad()}
 \begin{verbatim}
-int gcm_add_aad(gcm_state *gcm, 
-               const unsigned char *adata,     unsigned long adatalen);
-\end{verbatim}
-This adds the additional authentication data ``adata'' of length ``adatalen'' to the GCM state ``gcm''.
+int gcm_add_aad(          gcm_state *gcm, 
+                const unsigned char *adata, 
+                      unsigned long  adatalen);
+\end{verbatim}
+This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the GCM state \textit{gcm}.
 
 \subsubsection{Plaintext Processing}
-After the AAD has been processed the plaintext (or ciphertext depending on the direction) can be processed.  
+After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.  
 
 \index{gcm\_process()}
 \begin{verbatim}
-int gcm_process(gcm_state *gcm,
-                     unsigned char *pt,     unsigned long ptlen,
-                     unsigned char *ct,
-                     int direction);
-\end{verbatim}
-This processes message data where ``pt'' is the plaintext and ``ct'' is the ciphertext.  The length of both are equal and stored in ``ptlen''.  Depending on the 
-mode ``pt'' is the input and ``ct'' is the output (or vice versa).  When ``direction'' equals \textbf{GCM\_ENCRYPT} the plaintext is read, encrypted and stored
-in the ciphertext buffer.  When ``direction'' equals \textbf{GCM\_DECRYPT} the opposite occurs.
+int gcm_process(    gcm_state *gcm,
+                unsigned char *pt, 
+                unsigned long  ptlen,
+                unsigned char *ct,
+                          int  direction);
+\end{verbatim}
+This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext.  The length of both are equal and stored in \textit{ptlen}.  Depending on 
+the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa).  When \textit{direction} equals \textbf{GCM\_ENCRYPT} the plaintext is read, 
+encrypted and stored in the ciphertext buffer.  When \textit{direction} equals \textbf{GCM\_DECRYPT} the opposite occurs.
 
 \subsubsection{State Termination}
 To terminate a GCM state and retrieve the message authentication tag call the following function.
 
 \index{gcm\_done()}
 \begin{verbatim}
-int gcm_done(gcm_state *gcm, 
-                     unsigned char *tag,    unsigned long *taglen);
-\end{verbatim}
-This terminates the GCM state ``gcm'' and stores the tag in ``tag'' of length ``taglen'' octets.
+int gcm_done(    gcm_state *gcm, 
+             unsigned char *tag, 
+             unsigned long *taglen);
+\end{verbatim}
+This terminates the GCM state \textit{gcm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
 
 \subsubsection{State Reset}
 The call to gcm\_init() will perform considerable pre--computation (when \textbf{GCM\_TABLES} is defined) and if you're going to be dealing with a lot of packets
-it is very costly to have to call it repeatedly.  To aid in this endeavour the reset function has been provided.
+it is very costly to have to call it repeatedly.  To aid in this endeavour, the reset function has been provided.
 
 \index{gcm\_reset()}
 \begin{verbatim}
 int gcm_reset(gcm_state *gcm);
 \end{verbatim}
 
-This will reset the GCM state ``gcm'' to the state that gcm\_init() left it.  The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
+This will reset the GCM state \textit{gcm} to the state that gcm\_init() left it.  The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
 
 \subsubsection{One--Shot Packet}
 To process a single packet under any given key the following helper function can be used.
 
 \index{gcm\_memory()}
 \begin{verbatim}
-int gcm_memory(      int           cipher,
-               const unsigned char *key,    unsigned long keylen,
-               const unsigned char *IV,     unsigned long IVlen,
-               const unsigned char *adata,  unsigned long adatalen,
-                     unsigned char *pt,     unsigned long ptlen,
-                     unsigned char *ct, 
-                     unsigned char *tag,    unsigned long *taglen,
-                               int direction);
+int gcm_memory(      
+                    int  cipher,
+    const unsigned char *key,    
+          unsigned long keylen,
+    const unsigned char *IV,    unsigned long IVlen,
+    const unsigned char *adata, unsigned long adatalen,
+          unsigned char *pt,    unsigned long ptlen,
+          unsigned char *ct, 
+          unsigned char *tag,   unsigned long *taglen,
+                    int  direction);
 \end{verbatim}
 
 This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
@@ -1361,7 +1678,8 @@
    }
 
    /* process the plaintext */
-   if ((err = gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
+   if ((err = 
+        gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
       return err;
    }
 
@@ -1373,7 +1691,8 @@
 
    /* ... send a header describing the lengths ... */
 
-   /* depending on the protocol and how IV is generated you may have to send it too... */
+   /* depending on the protocol and how IV is 
+    * generated you may have to send it too... */
    send(socket, iv, ivlen, 0);
 
    /* send the aad */
@@ -1401,7 +1720,8 @@
    register_cipher(&aes_desc);
 
    /* init the GCM state */
-   if ((err = gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
+   if ((err = 
+        gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
       whine_and_pout(err);
    }
 
@@ -1416,7 +1736,8 @@
            }
        }
 
-       if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm)) != CRYPT_OK) {
+       if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm)) 
+           != CRYPT_OK) {
            whine_and_pout(err);
        }
    }
@@ -1426,24 +1747,23 @@
 \end{small}
 
 \chapter{One-Way Cryptographic Hash Functions}
-\section{Core Functions}
-
-Like the ciphers there are hash core functions and a universal data type to hold the hash state called ``hash\_state''.  
-To initialize hash XXX (where XXX is the name) call:
+\mysection{Core Functions}
+Like the ciphers, there are hash core functions and a universal data type to hold the hash state called \textit{hash\_state}.  To initialize hash 
+XXX (where XXX is the name) call:
 \index{Hash Functions}
 \begin{verbatim}
 void XXX_init(hash_state *md);
 \end{verbatim}
 
-This simply sets up the hash to the default state governed by the specifications of the hash.  To add data to the 
-message being hashed call:
-\begin{verbatim}
-int XXX_process(hash_state *md, const unsigned char *in, unsigned long inlen);
-\end{verbatim}
-
+This simply sets up the hash to the default state governed by the specifications of the hash.  To add data to the message being hashed call:
+\begin{verbatim}
+int XXX_process(         hash_state *md, 
+                const unsigned char *in, 
+                      unsigned long  inlen);
+\end{verbatim}
 Essentially all hash messages are virtually infinitely\footnote{Most hashes are limited to $2^{64}$ bits or 2,305,843,009,213,693,952 bytes.} long message which 
-are buffered.  The data can be passed in any sized chunks as long as the order of the bytes are the same the message digest
-(hash output) will be the same.  For example, this means that:
+are buffered.  The data can be passed in any sized chunks as long as the order of the bytes are the same the message digest (hash output) will be the same.  For example, 
+this means that:
 \begin{verbatim}
 md5_process(&md, "hello ", 6);
 md5_process(&md, "world", 5);
@@ -1456,20 +1776,20 @@
 
 To finally get the message digest (the hash) call:
 \begin{verbatim}
-int XXX_done(hash_state *md, 
-              unsigned char *out);
-\end{verbatim}
-
-This function will finish up the hash and store the result in the ``out'' array.  You must ensure that ``out'' is long
-enough for the hash in question.  Often hashes are used to get keys for symmetric ciphers so the ``XXX\_done()'' functions
-will wipe the ``md'' variable before returning automatically.
+int XXX_done(   hash_state *md, 
+             unsigned char *out);
+\end{verbatim}
+
+This function will finish up the hash and store the result in the \textit{out} array.  You must ensure that \textit{out} is long
+enough for the hash in question.  Often hashes are used to get keys for symmetric ciphers so the \textit{XXX\_done()} functions
+will wipe the \textit{md} variable before returning automatically.
 
 To test a hash function call:
 \begin{verbatim}
 int XXX_test(void);
 \end{verbatim}
 
-This will return {\bf CRYPTO\_OK} if the hash matches the test vectors, otherwise it returns an error code.  An
+This will return {\bf CRYPT\_OK} if the hash matches the test vectors, otherwise it returns an error code.  An
 example snippet that hashes a message with md5 is given below.
 \begin{small}
 \begin{verbatim}
@@ -1493,28 +1813,46 @@
 \end{verbatim}
 \end{small}
 
-\section{Hash Descriptors}
-Like the set of ciphers the set of hashes have descriptors too.  They are stored in an array called ``hash\_descriptor'' and
+\mysection{Hash Descriptors}
+Like the set of ciphers, the set of hashes have descriptors as well.  They are stored in an array called \textit{hash\_descriptor} and
 are defined by:
 \begin{verbatim}
 struct _hash_descriptor {
     char *name;
+
     unsigned long hashsize;    /* digest output size in bytes  */
     unsigned long blocksize;   /* the block size the hash uses */
+
     void (*init)   (hash_state *hash);
-    int  (*process)(hash_state *hash, 
-                    const unsigned char *in, unsigned long inlen);
+
+    int  (*process)(         hash_state *hash, 
+                    const unsigned char *in, 
+                          unsigned long  inlen);
+
     int  (*done)   (hash_state *hash, unsigned char *out);
+
     int  (*test)   (void);
 };
 \end{verbatim}
 
-Similarly ``name'' is the name of the hash function in ASCII (all lowercase).  ``hashsize'' is the size of the digest output
-in bytes.  The remaining fields are pointers to the functions that do the respective tasks.  There is a function to
-search the array as well called ``int find\_hash(char *name)''.  It returns -1 if the hash is not found, otherwise the
+\index{find\_hash()}
+The \textit{name} member is the name of the hash function (all lowercase).  The \textit{hashsize} member is the size of the digest output
+in bytes, while \textit{blocksize} is the size of blocks the hash expects to the compression function.  Technically, this detail is not important
+for high level developers but is useful to know for performance reasons.  
+
+The \textit{init} member initializes the hash, \textit{process} passes data through the hash, \textit{done} terminates the hash and retrieves the 
+digest.  The \textit{test} member tests the hash against the specified test vectors.
+
+There is a function to search the array as well called \textit{int find\_hash(char *name)}.  It returns -1 if the hash is not found, otherwise, the
 position in the descriptor table of the hash.
 
-You can use the table to indirectly call a hash function that is chosen at runtime.  For example:
+In addition, there is also find\_hash\_oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
+\index{find\_hash\_oid()}
+\begin{verbatim}
+int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
+\end{verbatim}
+
+You can use the table to indirectly call a hash function that is chosen at run-time.  For example:
 \begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
@@ -1559,28 +1897,48 @@
 \end{verbatim}
 \end{small}
 
-Note the usage of ``MAXBLOCKSIZE''.  In Libtomcrypt no symmetric block, key or hash digest is larger than MAXBLOCKSIZE in
+Note the usage of \textbf{MAXBLOCKSIZE}.  In LibTomCrypt, no symmetric block, key or hash digest is larger than \textbf{MAXBLOCKSIZE} in
 length.  This provides a simple size you can set your automatic arrays to that will not get overrun.
 
-There are three helper functions as well:
-\index{hash\_memory()} \index{hash\_file()}
-\begin{verbatim}
-int hash_memory(int hash, 
-                const unsigned char *in,   unsigned long inlen, 
-                      unsigned char *out,  unsigned long *outlen);
-
-int hash_file(int hash, const char *fname, 
-              unsigned char *out, unsigned long *outlen);
-
-int hash_filehandle(int hash, FILE *in, 
-                    unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-
-The ``hash'' parameter is the location in the descriptor table of the hash (\textit{e.g. the return of find\_hash()}).  
-The ``*outlen'' variable is used to keep track of the output size.  You must set it to the size of your output buffer before 
-calling the functions.  When they complete succesfully they store the length of the message digest back in it.  The functions 
-are otherwise straightforward.  The ``hash\_filehandle'' function assumes that ``in'' is an file handle opened in binary mode.  
-It will hash to the end of file and not reset the file position when finished.
+There are three helper functions to make working with hashes easier.  The first is a function to hash a buffer, and produce the digest in a single
+function call.
+
+\index{hash\_memory()} 
+\begin{verbatim}
+int hash_memory(                int  hash, 
+                const unsigned char *in,   
+                      unsigned long  inlen, 
+                      unsigned char *out,  
+                      unsigned long *outlen);
+\end{verbatim}
+
+This will hash the data pointed to by \textit{in} of length \textit{inlen}.  The hash used is indexed by the \textit{hash} parameter.  The message
+digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.  
+
+The next helper function allows for the hashing of a file based on a file name.  
+\index{hash\_file()}
+\begin{verbatim}
+int hash_file(          int  hash, 
+                 const char *fname, 
+              unsigned char *out, 
+              unsigned long *outlen);
+\end{verbatim}
+
+This will hash the file named by \textit{fname} using the hash indexed by \textit{hash}.  The file named in this function call must be readable by the 
+user owning the process performing the request.  This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
+when it is called.  The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.  
+
+\index{hash\_filehandle()}
+\begin{verbatim}
+int hash_filehandle(          int  hash, 
+                             FILE *in, 
+                    unsigned char *out, 
+                    unsigned long *outlen);
+\end{verbatim}
+
+This will hash the file identified by the handle \textit{in} using the hash indexed by \textit{hash}.  This will begin hashing from the current file pointer position, and
+will not rewind the file pointer when finished.  This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
+when it is called.  The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.  
 
 To perform the above hash with md5 the following code could be used:
 \begin{small}
@@ -1603,7 +1961,8 @@
 
    /* call the hash */
    len = sizeof(out);
-   if ((err = hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
+   if ((err = 
+       hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
       printf("Error hashing data: %s\n", error_to_string(err));
       return -1;
    }
@@ -1612,15 +1971,29 @@
 \end{verbatim}
 \end{small}
 
-The following hashes are provided as of this release:
+\subsection{Hash Registration}
+Similar to the cipher descriptor table you must register your hash algorithms before you can use them.  These functions
+work exactly like those of the cipher registration code.  The functions are:
+\index{register\_hash()} \index{unregister\_hash()}
+\begin{verbatim}
+int register_hash(const struct _hash_descriptor *hash);
+
+int unregister_hash(const struct _hash_descriptor *hash);
+\end{verbatim}
+
+The following hashes are provided as of this release within the LibTomCrypt library:
 \index{Hash descriptor table}
+
+\begin{figure}[here]
 \begin{center}
 \begin{tabular}{|c|c|c|}
-      \hline Name & Descriptor Name & Size of Message Digest (bytes) \\
+      \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Size of Message Digest (bytes)} \\
       \hline WHIRLPOOL & whirlpool\_desc & 64 \\
       \hline SHA-512 & sha512\_desc & 64 \\
       \hline SHA-384 & sha384\_desc & 48 \\
+      \hline RIPEMD-320 & rmd160\_desc & 40 \\
       \hline SHA-256 & sha256\_desc & 32 \\
+      \hline RIPEMD-256 & rmd160\_desc & 32 \\
       \hline SHA-224 & sha224\_desc & 28 \\
       \hline TIGER-192 & tiger\_desc & 24 \\
       \hline SHA-1 & sha1\_desc & 20 \\
@@ -1632,22 +2005,17 @@
       \hline
 \end{tabular}
 \end{center}
-
-Similar to the cipher descriptor table you must register your hash algorithms before you can use them.  These functions
-work exactly like those of the cipher registration code.  The functions are:
-\index{register\_hash()} \index{unregister\_hash()}
-\begin{verbatim}
-int register_hash(const struct _hash_descriptor *hash);
-int unregister_hash(const struct _hash_descriptor *hash);
-\end{verbatim}
-
-\section{Cipher Hash Construction}
+\caption{Built--In Software Hashes}
+\end{figure}
+\vfil
+
+\mysection{Cipher Hash Construction}
 \index{Cipher Hash Construction}
-An addition to the suite of hash functions is the ``Cipher Hash Construction'' or ``CHC'' mode.  In this mode
+An addition to the suite of hash functions is the \textit{Cipher Hash Construction} or \textit{CHC} mode.  In this mode
 applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use.  In 
 particular this allows a cryptosystem to be designed using very few moving parts.
 
-In order to use the CHC system the developer will have to take a few extra steps.  First the ``chc\_desc'' hash
+In order to use the CHC system the developer will have to take a few extra steps.  First the \textit{chc\_desc} hash
 descriptor must be registered with register\_hash().  At this point the CHC hash cannot be used to hash
 data.  While it is in the hash system you still have to tell the CHC code which cipher to use.  This is accomplished
 via the chc\_register() function.
@@ -1686,15 +2054,17 @@
 
    /* start chc with AES */
    if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
-      printf("Error binding AES to CHC: %s\n", error_to_string(err));
+      printf("Error binding AES to CHC: %s\n", 
+             error_to_string(err));
    }
 
-   /* now you can use chc_hash in any LTC function [aside from pkcs...] */
-   /* ... */
-\end{verbatim}
-
-
-\section{Notice}
+   /* now you can use chc_hash in any LTC function 
+    * [aside from pkcs...] */
+}
+\end{verbatim}
+
+
+\mysection{Notice}
 It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.  
 These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
 (e.g. Yarrow).
@@ -1703,64 +2073,71 @@
 for all purposes you would normally use a hash for.
 
 \chapter{Message Authentication Codes}
-\section{HMAC Protocol}
-Thanks to Dobes Vandermeer the library now includes support for hash based message authenication codes or HMAC for short.  An HMAC
-of a message is a keyed authenication code that only the owner of a private symmetric key will be able to verify.  The purpose is
+\mysection{HMAC Protocol}
+Thanks to Dobes Vandermeer, the library now includes support for hash based message authentication codes, or HMAC for short.  An HMAC
+of a message is a keyed authentication code that only the owner of a private symmetric key will be able to verify.  The purpose is
 to allow an owner of a private symmetric key to produce an HMAC on a message then later verify if it is correct.  Any impostor or
 eavesdropper will not be able to verify the authenticity of a message.  
 
 The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key 
 and its length.  The key is much like a key you would pass to a cipher.  That is, it is simply an array of octets stored in
-chars.  The initialization routine is:
+unsigned characters.  The initialization routine is:
 \index{hmac\_init()}
 \begin{verbatim}
-int hmac_init(hmac_state *hmac, int hash, 
-              const unsigned char *key, unsigned long keylen);
-\end{verbatim}
-The ``hmac'' parameter is the state for the HMAC code.  ``hash'' is the index into the descriptor table of the hash you want
-to use to authenticate the message.  ``key'' is the pointer to the array of chars that make up the key.  ``keylen'' is the
+int hmac_init(         hmac_state *hmac, 
+                              int  hash, 
+              const unsigned char *key, 
+                    unsigned long  keylen);
+\end{verbatim}
+The \textit{hmac} parameter is the state for the HMAC code.  The \textit{hash} parameter is the index into the descriptor table of the hash you want
+to use to authenticate the message.  The \textit{key} parameter is the pointer to the array of chars that make up the key.  The \textit{keylen} parameter is the
 length (in octets) of the key you want to use to authenticate the message.  To send octets of a message through the HMAC system you must use the following function:
 \index{hmac\_process()}
 \begin{verbatim}
-int hmac_process(hmac_state *hmac, 
-                 const unsigned char *in, unsigned long inlen);
-\end{verbatim}
-``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process.  ``len'' is the
-number of octets to process.  Like the hash process routines you can send the data in arbitrarly sized chunks. When you 
+int hmac_process(         hmac_state *hmac, 
+                 const unsigned char *in, 
+                       unsigned long  inlen);
+\end{verbatim}
+\textit{hmac} is the HMAC state you are working with. \textit{buf} is the array of octets to send into the HMAC process.  \textit{len} is the
+number of octets to process.  Like the hash process routines you can send the data in arbitrarily sized chunks. When you 
 are finished with the HMAC process you must call the following function to get the HMAC code:
 \index{hmac\_done()}
 \begin{verbatim}
-int hmac_done(hmac_state *hmac, 
-              unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-``hmac'' is the HMAC state you are working with.  ``out'' is the array of octets where the HMAC code should be stored.  You must
-set ``outlen'' to the size of the destination buffer before calling this function.  It is updated with the length of the HMAC code
-produced (depending on which hash was picked).  If ``outlen'' is less than the size of the message digest (and ultimately
-the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first ``outlen'' bytes).
-
-There are two  utility functions provided to make using HMACs easier todo.  They accept the key and information about the
-message (file pointer, address in memory) and produce the HMAC result in one shot.  These are useful if you want to avoid
+int hmac_done(   hmac_state *hmac, 
+              unsigned char *out, 
+              unsigned long *outlen);
+\end{verbatim}
+The \textit{hmac} parameter is the HMAC state you are working with.  The \textit{out} parameter is the array of octets where the HMAC code should be stored.  
+You must set \textit{outlen} to the size of the destination buffer before calling this function.  It is updated with the length of the HMAC code
+produced (depending on which hash was picked).  If \textit{outlen} is less than the size of the message digest (and ultimately
+the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first \textit{outlen} bytes).
+
+There are two utility functions provided to make using HMACs easier to do.  They accept the key and information about the
+message (file pointer, address in memory), and produce the HMAC result in one shot.  These are useful if you want to avoid
 calling the three step process yourself.
 
 \index{hmac\_memory()}
 \begin{verbatim}
-int hmac_memory(int hash, 
-                const unsigned char *key, unsigned long  keylen,
-                const unsigned char *in,  unsigned long  inlen, 
-                      unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-This will produce an HMAC code for the array of octets in ``in'' of length ``inlen''.  The index into the hash descriptor 
-table must be provided in ``hash''.  It uses the key from ``key'' with a key length of ``keylen''.  
-The result is stored in the array of octets ``out'' and the length in ``outlen''.  The value of ``outlen'' must be set
+int hmac_memory(
+                   int  hash, 
+   const unsigned char *key, unsigned long  keylen,
+   const unsigned char *in,  unsigned long  inlen, 
+         unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will produce an HMAC code for the array of octets in \textit{in} of length \textit{inlen}.  The index into the hash descriptor 
+table must be provided in \textit{hash}.  It uses the key from \textit{key} with a key length of \textit{keylen}.  
+The result is stored in the array of octets \textit{out} and the length in \textit{outlen}.  The value of \textit{outlen} must be set
 to the size of the destination buffer before calling this function.  Similarly for files there is the  following function:
 \index{hmac\_file()}
 \begin{verbatim}
-int hmac_file(int hash, const char *fname, 
-              const unsigned char *key, unsigned long  keylen, 
-                    unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-``hash'' is the index into the hash descriptor table of the hash you want to use.  ``fname'' is the filename to process.  
-``key'' is the array of octets to use as the key of length ``keylen''.  ``out'' is the array of octets where the 
+int hmac_file(
+                   int  hash, 
+            const char *fname, 
+   const unsigned char *key, unsigned long  keylen, 
+         unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+\textit{hash} is the index into the hash descriptor table of the hash you want to use.  \textit{fname} is the filename to process.  
+\textit{key} is the array of octets to use as the key of length \textit{keylen}.  \textit{out} is the array of octets where the 
 result should be stored.
 
 To test if the HMAC code is working there is the following function:
@@ -1818,28 +2195,33 @@
 \end{verbatim}
 \end{small}
 
-\section{OMAC Support}
+\mysection{OMAC Support}
+\index{OMAC} \index{CMAC}
 OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an 
-algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES.  From an API 
-standpoint the OMAC routines work much like the HMAC routines do.  Instead in this case a cipher is used instead of a hash.  
+algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES.  Note:  OMAC has been standardized as
+CMAC within NIST, for the purposes of this library OMAC and CMAC are synonymous.  From an API standpoint, the OMAC routines work much like the 
+HMAC routines.  Instead, in this case a cipher is used instead of a hash.  
 
 To start an OMAC state you call
 \index{omac\_init()}
 \begin{verbatim}
-int omac_init(omac_state *omac, int cipher, 
-              const unsigned char *key, unsigned long keylen);
-\end{verbatim}
-The ``omac'' variable is the state for the OMAC algorithm.  ``cipher'' is the index into the cipher\_descriptor table
+int omac_init(         omac_state *omac, 
+                              int  cipher, 
+              const unsigned char *key, 
+                    unsigned long  keylen);
+\end{verbatim}
+The \textit{omac} parameter is the state for the OMAC algorithm.  The \textit{cipher} parameter is the index into the cipher\_descriptor table
 of the cipher\footnote{The cipher must have a 64 or 128 bit block size.  Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
-wish to use.  ``key'' and ``keylen'' are the keys used to authenticate the data.
+wish to use.  The \textit{key} and \textit{keylen} parameters are the keys used to authenticate the data.
 
 To send data through the algorithm call
 \index{omac\_process()}
 \begin{verbatim}
-int omac_process(omac_state *state, 
-                 const unsigned char *in, unsigned long inlen);
-\end{verbatim}
-This will send ``inlen'' bytes from ``in'' through the active OMAC state ``state''.  Returns \textbf{CRYPT\_OK} if the 
+int omac_process(         omac_state *state, 
+                 const unsigned char *in, 
+                       unsigned long  inlen);
+\end{verbatim}
+This will send \textit{inlen} bytes from \textit{in} through the active OMAC state \textit{state}.  Returns \textbf{CRYPT\_OK} if the 
 function succeeds.  The function is not sensitive to the granularity of the data.  For example,
 
 \begin{verbatim}
@@ -1857,13 +2239,14 @@
 
 \index{omac\_done()}
 \begin{verbatim}
-int omac_done(omac_state *state, 
-              unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-Which will terminate the OMAC and output the \textit{tag} (MAC) to ``out''.  Note that unlike the HMAC and other code 
-``outlen'' can be smaller than the default MAC size (for instance AES would make a 16-byte tag).  Part of the OMAC 
+int omac_done(   omac_state *state, 
+              unsigned char *out, 
+              unsigned long *outlen);
+\end{verbatim}
+Which will terminate the OMAC and output the \textit{tag} (MAC) to \textit{out}.  Note that unlike the HMAC and other code 
+\textit{outlen} can be smaller than the default MAC size (for instance AES would make a 16-byte tag).  Part of the OMAC 
 specification states that the output may be truncated.  So if you pass in $outlen = 5$ and use AES as your cipher than
-the output MAC code will only be five bytes long.  If ``outlen'' is larger than the default size it is set to the default
+the output MAC code will only be five bytes long.  If \textit{outlen} is larger than the default size it is set to the default
 size to show how many bytes were actually used.
 
 Similar to the HMAC code the file and memory functions are also provided.  To OMAC a buffer of memory in one shot use the 
@@ -1871,26 +2254,28 @@
 
 \index{omac\_memory()}
 \begin{verbatim}
-int omac_memory(int cipher, 
-                const unsigned char *key, unsigned long keylen,
-                const unsigned char *in,  unsigned long inlen,
-                      unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-This will compute the OMAC of ``inlen'' bytes of ``in'' using the key ``key'' of length ``keylen'' bytes and the cipher
-specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with the same
+int omac_memory(                
+                    int  cipher, 
+    const unsigned char *key, unsigned long keylen,
+    const unsigned char *in,  unsigned long inlen,
+          unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will compute the OMAC of \textit{inlen} bytes of \textit{in} using the key \textit{key} of length \textit{keylen} bytes and the cipher
+specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same
 rules as omac\_done.
 
 To OMAC a file use
 \index{omac\_file()}
 \begin{verbatim}
-int omac_file(int cipher, 
-              const unsigned char *key, unsigned long keylen,
-              const char *filename, 
-                    unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-
-Which will OMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
-and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with 
+int omac_file(
+                    int  cipher, 
+    const unsigned char *key,      unsigned long keylen,
+             const char *filename, 
+          unsigned char *out,      unsigned long *outlen);
+\end{verbatim}
+
+Which will OMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes
+and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with 
 the same rules as omac\_done.
 
 To test if the OMAC code is working there is the following function:
@@ -1948,8 +2333,8 @@
 \end{verbatim}
 \end{small}
 
-\section{PMAC Support}
-The PMAC\footnote{J.Black, P.Rogaway, ``A Block--Cipher Mode of Operation for Parallelizable Message Authentication''} 
+\mysection{PMAC Support}
+The PMAC\footnote{J.Black, P.Rogaway, \textit{A Block--Cipher Mode of Operation for Parallelizable Message Authentication}} 
 protocol is another MAC algorithm that relies solely on a symmetric-key block cipher.  It uses essentially the same
 API as the provided OMAC code.  
 
@@ -1957,20 +2342,23 @@
 
 \index{pmac\_init()}
 \begin{verbatim}
-int pmac_init(pmac_state *pmac, int cipher, 
-              const unsigned char *key, unsigned long keylen);
-\end{verbatim}
-Which initializes the ``pmac'' state with the given ``cipher'' and ``key'' of length ``keylen'' bytes.  The chosen cipher
+int pmac_init(         pmac_state *pmac, 
+                              int  cipher, 
+              const unsigned char *key, 
+                    unsigned long  keylen);
+\end{verbatim}
+Which initializes the \textit{pmac} state with the given \textit{cipher} and \textit{key} of length \textit{keylen} bytes.  The chosen cipher
 must have a 64 or 128 bit block size (e.x. AES).
 
 To MAC data simply send it through the process function.
 
 \index{pmac\_process()}
 \begin{verbatim}
-int pmac_process(pmac_state *state, 
-                 const unsigned char *in, unsigned long inlen);
-\end{verbatim}
-This will process ``inlen'' bytes of ``in'' in the given ``state''.  The function is not sensitive to the granularity of the
+int pmac_process(         pmac_state *state, 
+                 const unsigned char *in, 
+                       unsigned long  inlen);
+\end{verbatim}
+This will process \textit{inlen} bytes of \textit{in} in the given \textit{state}.  The function is not sensitive to the granularity of the
 data.  For example,
 
 \begin{verbatim}
@@ -1988,38 +2376,41 @@
 
 \index{pmac\_done()}
 \begin{verbatim}
-int pmac_done(pmac_state *state, 
-              unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-This will store upto ``outlen'' bytes of the tag for the given ``state'' into ``out''.  Note that if ``outlen'' is larger
-than the size of the tag it is set to the amount of bytes stored in ``out''.
-
-Similar to the PMAC code the file and memory functions are also provided.  To PMAC a buffer of memory in one shot use the 
+int pmac_done(   pmac_state *state, 
+              unsigned char *out, 
+              unsigned long *outlen);
+\end{verbatim}
+This will store up to \textit{outlen} bytes of the tag for the given \textit{state} into \textit{out}.  Note that if \textit{outlen} is larger
+than the size of the tag it is set to the amount of bytes stored in \textit{out}.
+
+Similar to the OMAC code the file and memory functions are also provided.  To PMAC a buffer of memory in one shot use the 
 following function.
 
 \index{pmac\_memory()}
 \begin{verbatim}
-int pmac_memory(int cipher, 
-                const unsigned char *key, unsigned long  keylen,
-                const unsigned char *in,  unsigned long  inlen,
-                      unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-This will compute the PMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
-specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with the same
-rules as omac\_done.
+int pmac_memory(
+                    int  cipher, 
+    const unsigned char *key, unsigned long  keylen,
+    const unsigned char *in,  unsigned long  inlen,
+          unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will compute the PMAC of \textit{msglen} bytes of \textit{msg} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
+specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same
+rules as pmac\_done().
 
 To PMAC a file use
 \index{pmac\_file()}
 \begin{verbatim}
-int pmac_file(int cipher, 
-              const unsigned char *key, unsigned long keylen,
-              const char *filename, 
-              unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-
-Which will PMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
-and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with 
-the same rules as omac\_done.
+int pmac_file(
+                    int  cipher, 
+    const unsigned char *key,      unsigned long keylen,
+             const char *filename, 
+          unsigned char *out,      unsigned long *outlen);
+\end{verbatim}
+
+Which will PMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, 
+and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with 
+the same rules as pmac\_done().
 
 To test if the PMAC code is working there is the following function:
 \index{pmac\_test()}
@@ -2028,22 +2419,26 @@
 \end{verbatim}
 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
 
-\section{Pelican MAC}
-Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a ``mixing function''.  It achieves a very high 
+\mysection{Pelican MAC}
+Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a \textit{mixing function}.  It achieves a very high 
 rate of processing and is potentially very secure.  It requires AES to be enabled to function.  You do not have to register\_cipher() AES first though
 as it calls AES directly.
 
 \index{pelican\_init()}
 \begin{verbatim}
-int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
+int pelican_init(      pelican_state *pelmac, 
+                 const unsigned char *key, 
+                       unsigned long  keylen);
 \end{verbatim}
 This will initialize the Pelican state with the given AES key.  Once this has been done you can begin processing data.
 
 \index{pelican\_process()}
 \begin{verbatim}
-int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
-\end{verbatim}
-This will process ``inlen'' bytes of ``in'' through the Pelican MAC.  It's best that you pass in multiples of 16 bytes as it makes the
+int pelican_process(      pelican_state *pelmac, 
+                    const unsigned char *in, 
+                          unsigned long  inlen);
+\end{verbatim}
+This will process \textit{inlen} bytes of \textit{in} through the Pelican MAC.  It's best that you pass in multiples of 16 bytes as it makes the
 routine more efficient but you may pass in any length of text.  You can call this function as many times as required to process
 an entire message.
 
@@ -2051,7 +2446,7 @@
 \begin{verbatim}
 int pelican_done(pelican_state *pelmac, unsigned char *out);
 \end{verbatim}
-This terminates a Pelican MAC and writes the 16--octet tag to ``out''.
+This terminates a Pelican MAC and writes the 16--octet tag to \textit{out}.
 
 \subsection{Example}
 
@@ -2066,11 +2461,12 @@
    /* somehow initialize a key */
 
    /* initialize pelican mac */
-   if ((err = pelican_init(&pelstate,          /* the state */
-                           key,                /* user key */
-                           32                  /* key length in octets */
+   if ((err = pelican_init(&pelstate, /* the state */
+                           key,       /* user key */
+                           32         /* key length in octets */
                           )) != CRYPT_OK) {
-      printf("Error initializing Pelican: %s", error_to_string(err));
+      printf("Error initializing Pelican: %s", 
+              error_to_string(err));
       return EXIT_FAILURE;
    }
 
@@ -2079,15 +2475,17 @@
                               "hello world",   /* data to mac */        
                               11               /* length of data */
                               )) != CRYPT_OK) {
-      printf("Error processing Pelican: %s", error_to_string(err));
+      printf("Error processing Pelican: %s", 
+             error_to_string(err));
       return EXIT_FAILURE;
    }
 
    /* Terminate the MAC */
-   if ((err = pelican_done(&pelstate,       /* the state */
-                           tag              /* where to store the tag */
+   if ((err = pelican_done(&pelstate,/* the state */
+                           tag       /* where to store the tag */
                            )) != CRYPT_OK) {
-      printf("Error terminating Pelican: %s", error_to_string(err));
+      printf("Error terminating Pelican: %s", 
+             error_to_string(err));
       return EXIT_FAILURE;
    }
 
@@ -2097,12 +2495,174 @@
 }
 \end{verbatim}
 
+\mysection{XCBC-MAC}
+As of LibTomCrypt v1.15, XCBC-MAC (RFC 3566) has been provided to support TLS encryption suites.  Like OMAC, it computes a message authentication code
+by using a cipher in CBC mode.  It also uses a single key which it expands into the requisite three keys for the MAC function.  A XCBC--MAC state is
+initialized with the following function:
+
+\index{xcbc\_init()}
+\begin{verbatim}
+int xcbc_init(         xcbc_state *xcbc, 
+                              int  cipher, 
+              const unsigned char *key, 
+                    unsigned long  keylen);
+\end{verbatim}
+
+This will initialize the XCBC--MAC state \textit{xcbc}, with the key specified in \textit{key} of length \textit{keylen} octets.  The cipher indicated
+by the \textit{cipher} index can be either a 64 or 128--bit block cipher.  This will return \textbf{CRYPT\_OK} on success.
+
+To process data through XCBC--MAC use the following function:
+
+\index{xcbc\_process()}
+\begin{verbatim}
+int xcbc_process(         xcbc_state *state, 
+                 const unsigned char *in, 
+                       unsigned long  inlen);
+\end{verbatim}
+
+This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the XCBC--MAC state pointed to by \textit{state}.  Like the other MAC functions,
+the granularity of the input is not important but the order is.  This will return \textbf{CRYPT\_OK} on success.
+
+To compute the MAC tag value use the following function:
+
+\index{xcbc\_done()}
+\begin{verbatim}
+int xcbc_done(   xcbc_state *state, 
+              unsigned char *out, 
+              unsigned long *outlen);
+\end{verbatim}
+
+This will retrieve the XCBC--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}.  The \textit{outlen} parameter
+specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns.  This will return \textbf{CRYPT\_OK} on success.
+
+Helper functions are provided to make parsing memory buffers and files easier.  The following functions are provided:
+
+\index{xcbc\_memory()}
+\begin{verbatim}
+int xcbc_memory(
+                    int  cipher, 
+    const unsigned char *key, unsigned long  keylen,
+    const unsigned char *in,  unsigned long  inlen,
+          unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will compute the XCBC--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
+specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as xcbc\_done().
+
+To xcbc a file use
+\index{xcbc\_file()}
+\begin{verbatim}
+int xcbc_file(
+                    int  cipher, 
+    const unsigned char *key,      unsigned long keylen,
+             const char *filename, 
+          unsigned char *out,      unsigned long *outlen);
+\end{verbatim}
+
+Which will XCBC--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher 
+specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as xcbc\_done().
+
+
+To test XCBC--MAC for RFC 3566 compliance use the following function:
+
+\index{xcbc\_test()}
+\begin{verbatim}
+int xcbc_test(void);
+\end{verbatim}
+
+This will return \textbf{CRYPT\_OK} on success.  This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return 
+\textbf{CRYPT\_NOP}. 
+
+\mysection{F9--MAC}
+The F9--MAC is yet another CBC--MAC variant proposed for the 3GPP standard.  Originally specified to be used with the KASUMI block cipher, it can also be used
+with other ciphers.  For LibTomCrypt, the F9--MAC code can use any cipher.  
+
+\subsection{Usage Notice}
+F9--MAC differs slightly from the other MAC functions in that it requires the caller to perform the final message padding.  The padding quite simply is a direction
+bit followed by a 1 bit and enough zeros to make the message a multiple of the cipher block size.  If the message is byte aligned, the padding takes on the form of 
+a single 0x40 or 0xC0 byte followed by enough 0x00 bytes to make the message proper multiple.  
+
+If the user simply wants a MAC function (hint: use OMAC) padding with a single 0x40 byte should be sufficient for security purposes and still be reasonably compatible
+with F9--MAC.
+
+\subsection{F9--MAC Functions}
+A F9--MAC state is initialized with the following function:
+\index{f9\_init()}
+\begin{verbatim}
+int f9_init(           f9_state *f9, 
+                            int  cipher, 
+            const unsigned char *key, 
+                  unsigned long  keylen);
+\end{verbatim}
+
+This will initialize the F9--MAC state \textit{f9}, with the key specified in \textit{key} of length \textit{keylen} octets.  The cipher indicated
+by the \textit{cipher} index can be either a 64 or 128--bit block cipher.  This will return \textbf{CRYPT\_OK} on success.
+
+To process data through F9--MAC use the following function:
+\index{f9\_process()}
+\begin{verbatim}
+int f9_process(           f9_state *state, 
+               const unsigned char *in, 
+                     unsigned long  inlen);
+\end{verbatim}
+
+This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the F9--MAC state pointed to by \textit{state}.  Like the other MAC functions,
+the granularity of the input is not important but the order is.  This will return \textbf{CRYPT\_OK} on success.
+
+To compute the MAC tag value use the following function:
+
+\index{f9\_done()}
+\begin{verbatim}
+int f9_done(     f9_state *state, 
+            unsigned char *out, 
+            unsigned long *outlen);
+\end{verbatim}
+
+This will retrieve the F9--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}.  The \textit{outlen} parameter
+specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns.  This will return 
+\textbf{CRYPT\_OK} on success.
+
+Helper functions are provided to make parsing memory buffers and files easier.  The following functions are provided:
+
+\index{f9\_memory()}
+\begin{verbatim}
+int f9_memory(
+                    int  cipher, 
+    const unsigned char *key, unsigned long  keylen,
+    const unsigned char *in,  unsigned long  inlen,
+          unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will compute the F9--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
+specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as f9\_done().
+
+To F9--MAC a file use
+\index{f9\_file()}
+\begin{verbatim}
+int f9_file(
+                    int  cipher, 
+    const unsigned char *key,      unsigned long keylen,
+             const char *filename, 
+          unsigned char *out,      unsigned long *outlen);
+\end{verbatim}
+
+Which will F9--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher 
+specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as f9\_done().
+
+
+To test f9--MAC for RFC 3566 compliance use the following function:
+
+\index{f9\_test()}
+\begin{verbatim}
+int f9_test(void);
+\end{verbatim}
+
+This will return \textbf{CRYPT\_OK} on success.  This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return 
+\textbf{CRYPT\_NOP}. 
 
 \chapter{Pseudo-Random Number Generators}
-\section{Core Functions}
+\mysection{Core Functions}
 The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well.  A cryptographic PRNG is
 used to expand a shorter bit string into a longer bit string.  PRNGs are used wherever random data is required such as Public Key (PK)
-key generation.  There is a universal structure called ``prng\_state''.  To initialize a PRNG call:
+key generation.  There is a universal structure called \textit{prng\_state}.  To initialize a PRNG call:
 \index{PRNG start}
 \begin{verbatim}
 int XXX_start(prng_state *prng);
@@ -2112,22 +2672,23 @@
 entropy.  Ideally you'd have some OS level source to tap like in UNIX.  To add entropy to the PRNG call:
 \index{PRNG add\_entropy}
 \begin{verbatim}
-int XXX_add_entropy(const unsigned char *in, unsigned long inlen, 
-                    prng_state *prng);
-\end{verbatim}
-
-Which returns {\bf CRYPTO\_OK} if the entropy was accepted.  Once you think you have enough entropy you call another
+int XXX_add_entropy(const unsigned char *in, 
+                          unsigned long  inlen, 
+                             prng_state *prng);
+\end{verbatim}
+Which returns {\bf CRYPT\_OK} if the entropy was accepted.  Once you think you have enough entropy you call another
 function to put the entropy into action.
 \index{PRNG ready}
 \begin{verbatim}
 int XXX_ready(prng_state *prng);
 \end{verbatim}
 
-Which returns {\bf CRYPTO\_OK} if it is ready.  Finally to actually read bytes call:
+Which returns {\bf CRYPT\_OK} if it is ready.  Finally to actually read bytes call:
 \index{PRNG read}
 \begin{verbatim}
-unsigned long XXX_read(unsigned char *out, unsigned long outlen,
-                       prng_state *prng);
+unsigned long XXX_read(unsigned char *out, 
+                       unsigned long  outlen,
+                          prng_state *prng);
 \end{verbatim}
 
 Which returns the number of bytes read from the PRNG.  When you are finished with a PRNG state you call
@@ -2143,29 +2704,31 @@
 
 \index{PRNG export}
 \begin{verbatim}
-int XXX_export(unsigned char *out, unsigned long *outlen, 
-               prng_state    *prng);
-\end{verbatim}
-
-This will write a ``PRNG state'' to the buffer ``out'' of length ``outlen'' bytes.  The idea of 
-the export is meant to be used as a ``seed file''.  That is, when the program starts up there will not likely
+int XXX_export(unsigned char *out, 
+               unsigned long *outlen, 
+                  prng_state *prng);
+\end{verbatim}
+
+This will write a \textit{PRNG state} to the buffer \textit{out} of length \textit{outlen} bytes.  The idea of 
+the export is meant to be used as a \textit{seed file}.  That is, when the program starts up there will not likely
 be that much entropy available.   To import a state to seed a PRNG call the following function.
 
 \index{PRNG import}
 \begin{verbatim}
-int XXX_import(const unsigned char *in, unsigned long inlen, 
-                     prng_state     *prng);
+int XXX_import(const unsigned char *in, 
+                     unsigned long  inlen, 
+                        prng_state *prng);
 \end{verbatim}
 
 This will call the start and add\_entropy functions of the given PRNG.  It will use the state in
-``in'' of length ``inlen'' as the initial seed.  You must pass the same seed length as was exported
+\textit{in} of length \textit{inlen} as the initial seed.  You must pass the same seed length as was exported
 by the corresponding export function.
 
-Note that importing a state will not ``resume'' the PRNG from where it left off.  That is, if you export
+Note that importing a state will not \textit{resume} the PRNG from where it left off.  That is, if you export
 a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not 
 specifically equal the 8 bytes you generated previously.
 
-When a program is first executed the normal course of operation is 
+When a program is first executed the normal course of operation is:
 
 \begin{enumerate}
    \item Gather entropy from your sources for a given period of time or number of events.
@@ -2174,7 +2737,7 @@
 
 When your program is finished you simply call the export function and save the state to a medium (disk,
 flash memory, etc).  The next time your application starts up you can detect the state, feed it to the 
-import function and go on your way.  It is ideal that (as soon as possible) after startup you export a
+import function and go on your way.  It is ideal that (as soon as possible) after start up you export a
 fresh state.  This helps in the case that the program aborts or the machine is powered down without
 being given a chance to exit properly.  
 
@@ -2195,12 +2758,11 @@
 It is possible to be adding entropy and reading from a PRNG at the same time.  For example, if you first seed the PRNG
 and call ready() you can now read from it.  You can also keep adding new entropy to it.  The new entropy will not be used
 in the PRNG until ready() is called again.  This allows the PRNG to be used and re-seeded at the same time.  No real error 
-checking is guaranteed to see if the entropy is sufficient or if the PRNG is even in a ready state before reading.
+checking is guaranteed to see if the entropy is sufficient, or if the PRNG is even in a ready state before reading.
 
 \subsection{Example}
-
-Below is a simple snippet to read 10 bytes from yarrow.  Its important to note that this snippet is 
-{\bf NOT} secure since the entropy added is not random.
+Below is a simple snippet to read 10 bytes from Yarrow.  It is important to note that this snippet is {\bf NOT} secure since 
+the entropy added is not random.
 
 \begin{verbatim}
 #include <tomcrypt.h>
@@ -2215,46 +2777,69 @@
       printf("Start error: %s\n", error_to_string(err));
    }
    /* add entropy */
-   if ((err = yarrow_add_entropy("hello world", 11, &prng)) != CRYPT_OK) {
+   if ((err = yarrow_add_entropy("hello world", 11, &prng)) 
+       != CRYPT_OK) {
       printf("Add_entropy error: %s\n", error_to_string(err));
    }
    /* ready and read */
    if ((err = yarrow_ready(&prng)) != CRYPT_OK) {
       printf("Ready error: %s\n", error_to_string(err));
    }
-   printf("Read %lu bytes from yarrow\n", yarrow_read(buf, 10, &prng));
+   printf("Read %lu bytes from yarrow\n", 
+          yarrow_read(buf, sizeof(buf), &prng));
    return 0;
 }
 \end{verbatim}
 
-\section{PRNG Descriptors}
+\mysection{PRNG Descriptors}
 \index{PRNG Descriptor}
-PRNGs have descriptors too (surprised?). Stored in the structure ``prng\_descriptor''.  The format of an element is:
+PRNGs have descriptors that allow plugin driven functions to be created using PRNGs. The plugin descriptors are stored in the structure \textit{prng\_descriptor}.  The 
+format of an element is:
 \begin{verbatim}
 struct _prng_descriptor {
     char *name;
     int  export_size;    /* size in bytes of exported state */
+
     int (*start)      (prng_state *);
-    int (*add_entropy)(const unsigned char *, unsigned long, prng_state *);
+
+    int (*add_entropy)(const unsigned char *, unsigned long, 
+                       prng_state *);
+
     int (*ready)      (prng_state *);
-    unsigned long (*read)(unsigned char *, unsigned long len, prng_state *);
+
+    unsigned long (*read)(unsigned char *, unsigned long len, 
+                          prng_state *);
+
     void (*done)(prng_state *);
+
     int (*export)(unsigned char *, unsigned long *, prng_state *);
+
     int (*import)(const unsigned char *, unsigned long, prng_state *);
+
     int (*test)(void);
 };
 \end{verbatim}
 
-There is a ``int find\_prng(char *name)'' function as well.  Returns -1 if the PRNG is not found, otherwise it returns
-the position in the prng\_descriptor array.
-
-Just like the ciphers and hashes you must register your prng before you can use it.  The two functions provided work
-exactly as those for the cipher registry functions.  They are:
+To find a PRNG in the descriptor table the following function can be used:
+\index{find\_prng()}
+\begin{verbatim}
+int find_prng(const char *name);
+\end{verbatim}
+This will search the PRNG descriptor table for the PRNG named \textit{name}.  It will return -1 if the PRNG is not found, otherwise, it returns
+the index into the descriptor table.
+
+Just like the ciphers and hashes, you must register your prng before you can use it.  The two functions provided work exactly as those for the cipher registry functions.  
+They are the following:
+\index{register\_prng()} \index{unregister\_prng()}
 \begin{verbatim}
 int register_prng(const struct _prng_descriptor *prng);
 int unregister_prng(const struct _prng_descriptor *prng);
 \end{verbatim}
 
+The register function will register the PRNG, and return the index into the table where it was placed (or -1 for error).  It will avoid registering the same
+descriptor twice, and will return the index of the current placement in the table if the caller attempts to register it more than once.  The unregister function
+will return \textbf{CRYPT\_OK} if the PRNG was found and removed.  Otherwise, it returns \textbf{CRYPT\_ERROR}.
+
 \subsection{PRNGs Provided}
 \begin{figure}[here]
 \begin{center}
@@ -2274,9 +2859,9 @@
 
 \subsubsection{Yarrow}
 Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources 
-(keyboard, mouse, interrupts, etc) and produce an unbounded string of random bytes.  
-
-\textit{Note:} This PRNG is still secure for most taskings but is no longer recommended.  Users
+(keyboard, mouse, interrupts, etc), and produce an unbounded string of random bytes.  
+
+\textit{Note:} This PRNG is still secure for most tasks but is no longer recommended.  Users
 should use Fortuna instead.
 
 \subsubsection{Fortuna}
@@ -2287,47 +2872,46 @@
 providing more security.  
 
 Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher 
-and SHA--256 hash function.  Technically Fortuna will work with any block cipher that accepts a 256--bit
-key and any hash that produces at least a 256--bit output.  However, to make the implementation simpler
+and SHA--256 hash function.  Technically, Fortuna will work with any block cipher that accepts a 256--bit
+key, and any hash that produces at least a 256--bit output.  However, to make the implementation simpler
 it has been fixed to those choices.
 
 Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being 
 added to the PRNG learn far less about the state than that of Yarrow.  Without getting into to many
 details Fortuna has the ability to recover from state determination attacks where the attacker starts
-to learn information from the PRNGs output about the internal state.  Yarrow on the other hand cannot 
+to learn information from the PRNGs output about the internal state.  Yarrow on the other hand, cannot 
 recover from that problem until new entropy is added to the pool and put to use through the ready() function.
 
 \subsubsection{RC4}
 
-RC4 is an old stream cipher that can also double duty as a PRNG in a pinch.  You ``key'' it by
-calling add\_entropy() and setup the key by calling ready().  You can only add upto 256 bytes via
+RC4 is an old stream cipher that can also double duty as a PRNG in a pinch.  You key RC4 by
+calling add\_entropy(), and setup the key by calling ready().  You can only add up to 256 bytes via
 add\_entropy().  
 
-When you read from RC4 the output of the RC4 algorithm is XOR'd against your buffer you provide.  In this
-manner you can use rc4\_read() as an encrypt (and decrypt) function.  
-
-You really shouldn't use RC4 anymore.  This isn't because RC4 is weak (though biases are known to exist) just
-simply that faster alternatives exist.
+When you read from RC4, the output is XOR'ed against your buffer you provide.  In this manner, you can use rc4\_read() 
+as an encrypt (and decrypt) function.  
+
+You really should not use RC4.  This is not because RC4 is weak, (though biases are known to exist) but simply due to 
+the fact that faster alternatives exist.
 
 \subsubsection{SOBER-128}
 
-SOBER-128 is a stream cipher designed by the QUALCOMM Australia team.  Like RC4 you ``key'' it by 
+SOBER--128 is a stream cipher designed by the QUALCOMM Australia team.  Like RC4, you key it by 
 calling add\_entropy().  There is no need to call ready() for this PRNG as it does not do anything.  
 
-Note that this cipher has several oddities about how it operates.  The first time you call 
-add\_entropy() that sets the cipher's key.  Every other time you call the same function it sets
-the cipher's IV variable.  The IV mechanism allows you to encrypt several messages with the same
-key and not re--use the same key material.
-
-Unlike Yarrow and Fortuna all of the entropy (and hence security) of this algorithm rests in the data
-you pass it on the first call to add\_entropy().  All buffers sent to add\_entropy() must have a length
+Note: this cipher has several oddities about how it operates.  The first call to add\_entropy() sets the cipher's key.  
+Every other time call to the add\_entropy() function sets the cipher's IV variable.  The IV mechanism allows you to 
+encrypt several messages with the same key, and not re--use the same key material.
+
+Unlike Yarrow and Fortuna, all of the entropy (and hence security) of this algorithm rests in the data
+you pass it on the \textbf{first} call to add\_entropy().  All buffers sent to add\_entropy() must have a length
 that is a multiple of four bytes.
 
-Like RC4 the output of SOBER--128 is XOR'ed against the buffer you provide it.  In this manner you can use
+Like RC4, the output of SOBER--128 is XOR'ed against the buffer you provide it.  In this manner, you can use
 sober128\_read() as an encrypt (and decrypt) function.
 
-Since SOBER-128 has a fixed keying scheme and is very fast (faster than RC4) the ideal usage of SOBER-128 is to 
-key it from the output of Fortuna (or Yarrow) and use it to encrypt messages.  It is also ideal for
+Since SOBER-128 has a fixed keying scheme, and is very fast (faster than RC4) the ideal usage of SOBER-128 is to 
+key it from the output of Fortuna (or Yarrow), and use it to encrypt messages.  It is also ideal for
 simulations which need a high quality (and fast) stream of bytes.  
 
 \subsubsection{Example Usage}
@@ -2345,7 +2929,7 @@
       exit(-1);
    }
 
-   /* use ``key'' as the key */
+   /* use "key" as the key */
    if ((err = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
       printf("RC4 add entropy error: %s\n", error_to_string(err));
       exit(-1);
@@ -2369,35 +2953,39 @@
 \end{small}
 To decrypt you have to do the exact same steps.  
 
-\section{The Secure RNG}
+\mysection{The Secure RNG}
 \index{Secure RNG}
-An RNG is related to a PRNG except that it doesn't expand a smaller seed to get the data.  They generate their random bits
+An RNG is related to a PRNG in many ways, except that it does not expand a smaller seed to get the data.  They generate their random bits
 by performing some computation on fresh input bits.  Possibly the hardest thing to get correctly in a cryptosystem is the 
-PRNG.  Computers are deterministic beasts that try hard not to stray from pre-determined paths.  That makes gathering 
-entropy needed to seed the PRNG a hard task.  
+PRNG.  Computers are deterministic that try hard not to stray from pre--determined paths.  This makes gathering entropy needed to seed a PRNG 
+a hard task.  
 
 There is one small function that may help on certain platforms:
 \index{rng\_get\_bytes()}
 \begin{verbatim}
-unsigned long rng_get_bytes(unsigned char *buf, unsigned long len, 
-                  void (*callback)(void));
-\end{verbatim}
-
-Which will try one of three methods of getting random data.  The first is to open the popular ``/dev/random'' device which 
-on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite.  It emulates ``/dev/random'' via the Microsoft CSP.}.  
-The second method is to try the Microsoft Cryptographic Service Provider and read the RNG.  The third method is an ANSI C 
-clock drift method that is also somewhat popular but gives bits of lower entropy.  The ``callback'' parameter is a pointer to a function that returns void.  Its used when the slower ANSI C RNG must be 
-used so the calling application can still work.  This is useful since the ANSI C RNG has a throughput of three 
-bytes a second.  The callback pointer may be set to {\bf NULL} to avoid using it if you don't want to.  The function 
-returns the number of bytes actually read from any RNG source.  There is a function to help setup a PRNG as well:
+unsigned long rng_get_bytes(
+    unsigned char *buf, 
+    unsigned long  len, 
+    void         (*callback)(void));
+\end{verbatim}
+
+Which will try one of three methods of getting random data.  The first is to open the popular \textit{/dev/random} device which 
+on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite.  It emulates \textit{/dev/random} via the Microsoft CSP.}.  
+The second method is to try the Microsoft Cryptographic Service Provider, and read the RNG.  The third method is an ANSI C 
+clock drift method that is also somewhat popular but gives bits of lower entropy.  The \textit{callback} parameter is a pointer to a function that returns void.  It is 
+used when the slower ANSI C RNG must be used so the calling application can still work.  This is useful since the ANSI C RNG has a throughput of roughly three 
+bytes a second.  The callback pointer may be set to {\bf NULL} to avoid using it if you do not want to.  The function returns the number of bytes actually read from 
+any RNG source.  There is a function to help setup a PRNG as well:
 \index{rng\_make\_prng()}
 \begin{verbatim}
-int rng_make_prng(int bits, int wprng, prng_state *prng, 
-                  void (*callback)(void));
-\end{verbatim}
-This will try to setup the prng with a state of at least ``bits'' of entropy.  The ``callback'' parameter works much like
-the callback in ``rng\_get\_bytes()''.  It is highly recommended that you use this function to setup your PRNGs unless you have a
-platform where the RNG doesn't work well.  Example usage of this function is given below.
+int rng_make_prng(       int  bits, 
+                         int  wprng, 
+                  prng_state *prng, 
+                       void (*callback)(void));
+\end{verbatim}
+This will try to initialize the prng with a state of at least \textit{bits} of entropy.  The \textit{callback} parameter works much like
+the callback in \textit{rng\_get\_bytes()}.  It is highly recommended that you use this function to setup your PRNGs unless you have a
+platform where the RNG does not work well.  Example usage of this function is given below:
 
 \begin{small}
 \begin{verbatim}
@@ -2415,13 +3003,15 @@
    }
 
    /* setup the PRNG */
-   if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) {
+   if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) 
+       != CRYPT_OK) {
       printf("Error setting up PRNG, %s\n", error_to_string(err));
       return -1;
    }
 
    /* make a 192-bit ECC key */
-   if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) != CRYPT_OK) {
+   if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) 
+       != CRYPT_OK) {
       printf("Error making key: %s\n", error_to_string(err));
       return -1;
    }
@@ -2431,9 +3021,9 @@
 \end{small}
 
 \subsection{The Secure PRNG Interface}
-It is possible to access the secure RNG through the PRNG interface and in turn use it within dependent functions such
+It is possible to access the secure RNG through the PRNG interface, and in turn use it within dependent functions such
 as the PK API.  This simplifies the cryptosystem on platforms where the secure RNG is fast.  The secure PRNG never 
-requires to be started, that is you need not call the start, add\_entropy or ready functions.  For example, consider
+requires to be started, that is you need not call the start, add\_entropy, or ready functions.  For example, consider
 the previous example using this PRNG.
 
 \begin{small}
@@ -2451,7 +3041,8 @@
    }
 
    /* make a 192-bit ECC key */
-   if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey)) != CRYPT_OK) {
+   if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey)) 
+       != CRYPT_OK) {
       printf("Error making key: %s\n", error_to_string(err));
       return -1;
    }
@@ -2460,43 +3051,92 @@
 \end{verbatim}
 \end{small}
 
-
-
 \chapter{RSA Public Key Cryptography}
 
-\section{Introduction}
+\mysection{Introduction}
 RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography.  In the specifications are
-padding algorithms for encryption and signatures.  The standard includes the ``v2.1'' algorithms.
-To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS 
-respectively.  
-
-\section{PKCS \#1 Encryption}
-
+padding algorithms for encryption and signatures.  The standard includes the \textit{v1.5} and \textit{v2.1} algorithms.
+To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS respectively.  
+
+\mysection{PKCS \#1 Padding}
+PKCS \#1 v1.5 padding is so simple that both signature and encryption padding are performed by the same function.  Note: the
+signature padding does \textbf{not} include the ASN.1 padding required.  That is performed by the rsa\_sign\_hash\_ex() function
+documented later on in this chapter.  
+
+\subsection{PKCS \#1 v1.5 Encoding}
+The following function performs PKCS \#1 v1.5 padding:
+\index{pkcs\_1\_v1\_5\_encode()}
+\begin{verbatim}
+int pkcs_1_v1_5_encode(
+    const unsigned char *msg, 
+          unsigned long  msglen,
+                    int  block_type,
+          unsigned long  modulus_bitlen,
+             prng_state *prng, 
+                    int  prng_idx,
+          unsigned char *out, 
+          unsigned long *outlen);
+\end{verbatim}
+
+This will encode the message pointed to by \textit{msg} of length \textit{msglen} octets.  The \textit{block\_type} parameter must be set to
+\textbf{LTC\_PKCS\_1\_EME} to perform encryption padding.  It must be set to \textbf{LTC\_PKCS\_1\_EMSA} to perform signature padding.  The \textit{modulus\_bitlen} 
+parameter indicates the length of the modulus in bits.  The padded data is stored in \textit{out} with a length of \textit{outlen} octets.  The output will not be 
+longer than the modulus which helps allocate the correct output buffer size.
+
+Only encryption padding requires a PRNG.  When performing signature padding the \textit{prng\_idx} parameter may be left to zero as it is not checked for validity.
+
+\subsection{PKCS \#1 v1.5 Decoding}
+The following function performs PKCS \#1 v1.5 de--padding:
+\index{pkcs\_1\_v1\_5\_decode()}
+\begin{verbatim}
+int pkcs_1_v1_5_decode(
+    const unsigned char *msg, 
+          unsigned long  msglen,
+                    int  block_type,
+          unsigned long  modulus_bitlen,
+          unsigned char *out, 
+          unsigned long *outlen,
+                    int *is_valid);
+\end{verbatim}
+\index{LTC\_PKCS\_1\_EME} \index{LTC\_PKCS\_1\_EMSA}
+This will remove the PKCS padding data pointed to by \textit{msg} of length \textit{msglen}.  The decoded data is stored in \textit{out} of length
+\textit{outlen}.  If the padding is valid, a 1 is stored in \textit{is\_valid}, otherwise, a 0 is stored.  The \textit{block\_type} parameter must be set to either
+\textbf{LTC\_PKCS\_1\_EME} or \textbf{LTC\_PKCS\_1\_EMSA} depending on whether encryption or signature padding is being removed.
+
+\mysection{PKCS \#1 v2.1 Encryption}
 PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation.  As far as this portion of
 the library is concerned we are only dealing with th OAEP padding of the message.
 
 \subsection{OAEP Encoding}
 
+The following function performs PKCS \#1 v2.1 encryption padding:
+
 \index{pkcs\_1\_oaep\_encode()}
 \begin{alltt}
-int pkcs_1_oaep_encode(const unsigned char *msg,    unsigned long msglen,
-                       const unsigned char *lparam, unsigned long lparamlen,
-                             unsigned long modulus_bitlen, prng_state *prng,
-                             int           prng_idx,         int  hash_idx,
-                             unsigned char *out,    unsigned long *outlen);
+int pkcs_1_oaep_encode(
+    const unsigned char *msg,    
+          unsigned long  msglen,
+    const unsigned char *lparam, 
+          unsigned long  lparamlen,
+          unsigned long  modulus_bitlen, 
+             prng_state *prng,
+                    int  prng_idx,
+                    int  hash_idx,
+          unsigned char *out, 
+          unsigned long *outlen);
 \end{alltt}
 
-This accepts ``msg'' as input of length ``msglen'' which will be OAEP padded.  The ``lparam'' variable is an additional system specific
+This accepts \textit{msg} as input of length \textit{msglen} which will be OAEP padded.  The \textit{lparam} variable is an additional system specific
 tag that can be applied to the encoding.  This is useful to identify which system encoded the message.  If no variance is desired then
-``lparam'' can be set to \textbf{NULL}.  
+\textit{lparam} can be set to \textbf{NULL}.  
 
 OAEP encoding requires the length of the modulus in bits in order to calculate the size of the output.  This is passed as the parameter
-``modulus\_bitlen''.  ``hash\_idx'' is the index into the hash descriptor table of the hash desired.  PKCS \#1 allows any hash to be 
+\textit{modulus\_bitlen}.  \textit{hash\_idx} is the index into the hash descriptor table of the hash desired.  PKCS \#1 allows any hash to be 
 used but both the encoder and decoder must use the same hash in order for this to succeed.  The size of hash output affects the maximum
- sized input message.  ``prng\_idx'' and ``prng'' are the random number generator arguments required to randomize the padding process.  
-The padded message is stored in ``out'' along with the length in ``outlen''.
-
-If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for ``msg'' is 
+ sized input message.  \textit{prng\_idx} and \textit{prng} are the random number generator arguments required to randomize the padding process.  
+The padded message is stored in \textit{out} along with the length in \textit{outlen}.
+
+If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for \textit{msg} is 
 $m - 2h - 2$.  For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.  
 
 Note that when the message is padded it still has not been RSA encrypted.  You must pass the output of this function to 
@@ -2506,43 +3146,53 @@
 
 \index{pkcs\_1\_oaep\_decode()}
 \begin{alltt}
-int pkcs_1_oaep_decode(const unsigned char *msg,    unsigned long msglen,
-                       const unsigned char *lparam, unsigned long lparamlen,
-                             unsigned long modulus_bitlen, int hash_idx,
-                             unsigned char *out,    unsigned long *outlen,
-                             int           *res);
+int pkcs_1_oaep_decode(
+    const unsigned char *msg,    
+          unsigned long  msglen,
+    const unsigned char *lparam, 
+          unsigned long  lparamlen,
+          unsigned long  modulus_bitlen, 
+                    int  hash_idx,
+          unsigned char *out,    
+          unsigned long *outlen,
+                    int *res);
 \end{alltt}
 
-This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder.  ``msg'' is the 
-output of pkcs\_1\_oaep\_encode() of length ``msglen''.  ``lparam'' is the same system variable passed to the OAEP encoder.  If it does not
-match what was used during encoding this function will not decode the packet.  ``modulus\_bitlen'' is the size of the RSA modulus in bits
-and must match what was used during encoding.  Similarly the ``hash\_idx'' index into the hash descriptor table must match what was used
+This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder.  \textit{msg} is the 
+output of pkcs\_1\_oaep\_encode() of length \textit{msglen}.  \textit{lparam} is the same system variable passed to the OAEP encoder.  If it does not
+match what was used during encoding this function will not decode the packet.  \textit{modulus\_bitlen} is the size of the RSA modulus in bits
+and must match what was used during encoding.  Similarly the \textit{hash\_idx} index into the hash descriptor table must match what was used
 during encoding.
 
-If the function succeeds it decodes the OAEP encoded message into ``out'' of length ``outlen'' and stores a 
-$1$ in ``res''.  If the packet is invalid it stores $0$ in ``res'' and if the function fails for another reason
+If the function succeeds it decodes the OAEP encoded message into \textit{out} of length \textit{outlen} and stores a 
+$1$ in \textit{res}.  If the packet is invalid it stores $0$ in \textit{res} and if the function fails for another reason
 it returns an error code.  
 
-\section{PKCS \#1 Digital Signatures}
+\mysection{PKCS \#1 Digital Signatures}
 
 \subsection{PSS Encoding}
 PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.  
 
 \index{pkcs\_1\_pss\_encode()}
 \begin{alltt}
-int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
-                            unsigned long saltlen,  prng_state   *prng,     
-                            int           prng_idx, int           hash_idx,
-                            unsigned long modulus_bitlen,
-                            unsigned char *out,     unsigned long *outlen);
+int pkcs_1_pss_encode(
+    const unsigned char *msghash, 
+          unsigned long  msghashlen,
+          unsigned long  saltlen,  
+             prng_state *prng,     
+                    int  prng_idx, 
+                    int  hash_idx,
+          unsigned long  modulus_bitlen,
+          unsigned char *out, 
+          unsigned long *outlen);
 \end{alltt}
 
-This function assumes the message to be PSS encoded has previously been hashed.  The input hash ``msghash'' is of length 
-``msghashlen''.  PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.  
-``hash\_idx'' is the index into the hash descriptor table of the hash to use.  ``prng\_idx'' and ``prng'' are the random
+This function assumes the message to be PSS encoded has previously been hashed.  The input hash \textit{msghash} is of length 
+\textit{msghashlen}.  PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.  
+\textit{hash\_idx} is the index into the hash descriptor table of the hash to use.  \textit{prng\_idx} and \textit{prng} are the random
 number generator information required for the salt.
 
-Similar to OAEP encoding ``modulus\_bitlen'' is the size of the RSA modulus (in bits).  It limits the size of the salt.  If $m$ is the length
+Similar to OAEP encoding \textit{modulus\_bitlen} is the size of the RSA modulus (in bits).  It limits the size of the salt.  If $m$ is the length
 of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.  
 
 This function does not actually sign the data it merely pads the hash of a message so that it can be processed by rsa\_exptmod().
@@ -2553,25 +3203,30 @@
 
 \index{pkcs\_1\_pss\_decode()}
 \begin{alltt}
-int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
-                      const unsigned char *sig,     unsigned long siglen,
-                            unsigned long saltlen,  int           hash_idx,
-                            unsigned long modulus_bitlen, int    *res);
+int pkcs_1_pss_decode(
+    const unsigned char *msghash, 
+          unsigned long  msghashlen,
+    const unsigned char *sig, 
+          unsigned long  siglen,
+          unsigned long  saltlen,
+                    int  hash_idx,
+          unsigned long  modulus_bitlen, 
+                    int *res);
 \end{alltt}
-This will decode the PSS encoded message in ``sig'' of length ``siglen'' and compare it to values in ``msghash'' of length
-``msghashlen''.  If the block is a valid PSS block and the decoded hash equals the hash supplied ``res'' is set to non--zero.  Otherwise, 
+This will decode the PSS encoded message in \textit{sig} of length \textit{siglen} and compare it to values in \textit{msghash} of length
+\textit{msghashlen}.  If the block is a valid PSS block and the decoded hash equals the hash supplied \textit{res} is set to non--zero.  Otherwise, 
 it is set to zero.  The rest of the parameters are as in the PSS encode call.
 
-It's important to use the same ``saltlen'' and hash for both encoding and decoding as otherwise the procedure will not work.
-
-\section{RSA Operations}
+It's important to use the same \textit{saltlen} and hash for both encoding and decoding as otherwise the procedure will not work.
+
+\mysection{RSA Key Operations}
 \subsection{Background}
 
-RSA is a public key algorithm that is based on the inability to find the ``e-th'' root modulo a composite of unknown 
+RSA is a public key algorithm that is based on the inability to find the \textit{e-th} root modulo a composite of unknown 
 factorization.  Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
 not strictly equivalent.
 
-The system begins with with two primes $p$ and $q$ and their product $N = pq$.  The order or ``Euler totient'' of the
+The system begins with with two primes $p$ and $q$ and their product $N = pq$.  The order or \textit{Euler totient} of the
 multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to 
 $\mbox{lcm}(p - 1, q - 1)$.  The public key consists of the composite $N$ and some integer $e$ such that 
 $\mbox{gcd}(e, \phi(N)) = 1$.  The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$ 
@@ -2581,7 +3236,7 @@
 $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$.  Since finding the inverse exponent $d$
 given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
 $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$.  Similarly the owner of the private key 
-can sign a message by ``decrypting'' it.  Others can verify it by ``encrypting'' it.  
+can sign a message by \textit{decrypting} it.  Others can verify it by \textit{encrypting} it.  
 
 Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.  
 Ideally $e$ should be larger than $100$ to prevent direct analysis.  For example, if $e$ is three and you do not pad
@@ -2597,107 +3252,242 @@
 
 \subsection{RSA Key Generation}
 
-For RSA routines a single ``rsa\_key'' structure is used.  To make a new RSA key call:
+For RSA routines a single \textit{rsa\_key} structure is used.  To make a new RSA key call:
 \index{rsa\_make\_key()}
 \begin{verbatim}
 int rsa_make_key(prng_state *prng, 
-                 int wprng, int size, 
-                 long e, rsa_key *key);
-\end{verbatim}
-
-Where ``wprng'' is the index into the PRNG descriptor array.  ``size'' is the size in bytes of the RSA modulus desired.
-``e'' is the encryption exponent desired, typical values are 3, 17, 257 and 65537.  I suggest you stick with 65537 since its big
-enough to prevent trivial math attacks and not super slow.  ``key'' is where the key is placed.  All keys must be at 
-least 128 bytes and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
-
-Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you make the key.  Make sure to call 
-``rsa\_free()'' (see below) when you are finished with the key.  If ``rsa\_make\_key()'' fails it will automatically 
-free the ram allocated itself.
+                        int  wprng, 
+                        int  size, 
+                       long  e, 
+                    rsa_key *key);
+\end{verbatim}
+
+Where \textit{wprng} is the index into the PRNG descriptor array.  The \textit{size} parameter is the size in bytes of the RSA modulus desired.
+The \textit{e} parameter is the encryption exponent desired, typical values are 3, 17, 257 and 65537.  Stick with 65537 since it is big enough to prevent 
+trivial math attacks, and not super slow.  The \textit{key} parameter is where the constructed key is placed.  All keys must be at 
+least 128 bytes, and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
+
+\index{rsa\_free()}
+Note: the \textit{rsa\_make\_key()} function allocates memory at run--time when you make the key.  Make sure to call 
+\textit{rsa\_free()} (see below) when you are finished with the key.  If \textit{rsa\_make\_key()} fails it will automatically 
+free the memory allocated.
 
 \index{PK\_PRIVATE} \index{PK\_PUBLIC}
 There are two types of RSA keys.  The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}.  The first type is a private 
-RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated
-and has been replaced by the PK\_PRIVATE type.} in the form of a RSAPrivateKey.  The second type is a public RSA key
-which only includes the modulus and public exponent.  It takes the form of a RSAPublicKey.
+RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated, and has been replaced by the 
+PK\_PRIVATE type.} in the form of a RSAPrivateKey (PKCS \#1 compliant).  The second type, is a public RSA key which only includes the modulus and public exponent.  
+It takes the form of a RSAPublicKey (PKCS \#1 compliant).
 
 \subsection{RSA Exponentiation}
-
-To do raw work with the RSA function call:
+To do raw work with the RSA function, that is without padding, use the following function:
 \index{rsa\_exptmod()}
 \begin{verbatim}
-int rsa_exptmod(const unsigned char *in,   unsigned long inlen,
-                      unsigned char *out,  unsigned long *outlen, 
-                      int which, prng_state *prng, int prng_idx,
-                      rsa_key *key);
-\end{verbatim}
-This loads the bignum from ``in'' as a big endian word in the format PKCS specifies, raises it to either ``e'' or ``d'' and stores the result
-in ``out'' and the size of the result in ``outlen''. ``which'' is set to {\bf PK\_PUBLIC} to use ``e'' 
-(i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use ``d'' as the exponent (i.e. for decrypting/signing).
-
-Note that the output of his function is zero-padded as per PKCS \#1 specifications.  This allows this routine to 
-interoprate with PKCS \#1 padding functions properly.
-
-\subsection{RSA Key Encryption}
+int rsa_exptmod(const unsigned char *in,   
+                      unsigned long  inlen,
+                      unsigned char *out,  
+                      unsigned long *outlen, 
+                                int  which, 
+                            rsa_key *key);
+\end{verbatim}
+This will load the bignum from \textit{in} as a big endian integer in the format PKCS \#1 specifies, raises it to either \textit{e} or \textit{d} and stores the result
+in \textit{out} and the size of the result in \textit{outlen}. \textit{which} is set to {\bf PK\_PUBLIC} to use \textit{e} 
+(i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use \textit{d} as the exponent (i.e. for decrypting/signing).
+
+Note: the output of this function is zero--padded as per PKCS \#1 specification.  This allows this routine to work with PKCS \#1 padding functions properly.
+
+\mysection{RSA Key Encryption}
 Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
 To facilitate encrypting short keys the following functions have been provided.
 
 \index{rsa\_encrypt\_key()}
 \begin{verbatim}
-int rsa_encrypt_key(const unsigned char *in,  unsigned long inlen,
-                          unsigned char *out, unsigned long *outlen,
-                    const unsigned char *lparam, unsigned long lparamlen,
-                    prng_state *prng, int prng_idx, int hash_idx, rsa_key *key);
-\end{verbatim}
-This function will OAEP pad ``in'' of length inlen bytes then RSA encrypt it and store the ciphertext
-in ``out'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
-to pkcs\_1\_oaep\_encode().
-
+int rsa_encrypt_key(
+    const unsigned char *in,  
+          unsigned long  inlen,
+          unsigned char *out, 
+          unsigned long *outlen,
+    const unsigned char *lparam, 
+          unsigned long  lparamlen,
+             prng_state *prng, 
+                    int  prng_idx, 
+                    int  hash_idx, 
+                rsa_key *key);
+\end{verbatim}
+This function will OAEP pad \textit{in} of length \textit{inlen} bytes, RSA encrypt it, and store the ciphertext
+in \textit{out} of length \textit{outlen} octets.  The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
+to \index{pkcs\_1\_oaep\_encode()} pkcs\_1\_oaep\_encode().
+
+\subsection{Extended Encryption}
+As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions.  The following is the extended
+encryption function:
+
+\index{rsa\_encrypt\_key\_ex()}
+\begin{verbatim}
+int rsa_encrypt_key_ex(
+    const unsigned char *in,     
+          unsigned long  inlen,
+          unsigned char *out,    
+          unsigned long *outlen,
+    const unsigned char *lparam, 
+          unsigned long  lparamlen,
+             prng_state *prng, 
+                    int  prng_idx, 
+                    int  hash_idx, 
+                    int  padding, 
+                rsa_key *key);
+\end{verbatim}
+
+\index{LTC\_PKCS\_1\_OAEP} \index{LTC\_PKCS\_1\_V1\_5}
+The parameters are all the same as for rsa\_encrypt\_key() except for the addition of the \textit{padding} parameter.  It must be set to
+\textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 encryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 encryption.
+
+When performing v1.5 encryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
+
+\mysection{RSA Key Decryption}
 \index{rsa\_decrypt\_key()}
 \begin{verbatim}
-int rsa_decrypt_key(const unsigned char *in,  unsigned long inlen,
-                          unsigned char *out, unsigned long *outlen, 
-                    const unsigned char *lparam, unsigned long lparamlen,
-                          int            hash_idx, int *stat,
-                          rsa_key       *key);
-\end{verbatim}
-This function will RSA decrypt ``in'' of length ``inlen'' then OAEP depad the resulting data and store it in
-``out'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
+int rsa_decrypt_key(
+    const unsigned char *in, 
+          unsigned long  inlen,
+          unsigned char *out, 
+          unsigned long *outlen, 
+    const unsigned char *lparam, 
+          unsigned long  lparamlen,
+                    int  hash_idx, 
+                    int *stat,
+                rsa_key *key);
+\end{verbatim}
+This function will RSA decrypt \textit{in} of length \textit{inlen} then OAEP de-pad the resulting data and store it in
+\textit{out} of length \textit{outlen}.  The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
 to pkcs\_1\_oaep\_decode().
 
-If the RSA decrypted data isn't a valid OAEP packet then ``stat'' is set to $0$.  Otherwise, it is set to $1$.
-
-\subsection{RSA Hash Signatures}
-Similar to RSA key encryption RSA is also used to ``digitally sign'' message digests (hashes).  To facilitate this
+If the RSA decrypted data is not a valid OAEP packet then \textit{stat} is set to $0$.  Otherwise, it is set to $1$.
+
+\subsection{Extended Decryption}
+As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions.  The following is the extended
+decryption function:
+
+\index{rsa\_decrypt\_key\_ex()}
+\begin{verbatim}
+int rsa_decrypt_key_ex(
+    const unsigned char *in,       
+          unsigned long  inlen,
+          unsigned char *out,      
+          unsigned long *outlen,
+    const unsigned char *lparam,   
+          unsigned long  lparamlen,
+                    int  hash_idx, 
+                    int  padding,
+                    int *stat,
+                rsa_key *key);
+\end{verbatim}
+
+Similar to the extended encryption, the new parameter \textit{padding} indicates which version of the PKCS \#1 standard to use.  
+It must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 decryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 decryption.
+
+When performing v1.5 decryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
+
+
+\mysection{RSA Signature Generation}
+Similar to RSA key encryption RSA is also used to \textit{digitally sign} message digests (hashes).  To facilitate this
 process the following functions have been provided.
 
 \index{rsa\_sign\_hash()}
 \begin{verbatim}
-int rsa_sign_hash(const unsigned char *in,   unsigned long  inlen, 
-                        unsigned char *out,  unsigned long *outlen, 
-                        prng_state    *prng,     int            prng_idx,
-                        int            hash_idx, unsigned long  saltlen,
-                        rsa_key *key);
-\end{verbatim}
-
-This will PSS encode the message hash ``in'' of length ``inlen''.  Next the PSS encoded message will be RSA ``signed'' and 
-the output is stored in ``out'' of length ``outlen''.  
-
-
+int rsa_sign_hash(const unsigned char *in, 
+                        unsigned long  inlen, 
+                        unsigned char *out,  
+                        unsigned long *outlen, 
+                           prng_state *prng,     
+                                  int  prng_idx,
+                                  int  hash_idx, 
+                        unsigned long  saltlen,
+                              rsa_key *key);
+\end{verbatim}
+
+This will PSS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets.  Next, the PSS encoded hash will be RSA 
+\textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.  
+
+The \textit{hash\_idx} parameter indicates which hash will be used to create the PSS encoding.  It should be the same as the hash used to
+hash the message being signed.  The \textit{saltlen} parameter indicates the length of the desired salt, and should typically be small.  A good
+default value is between 8 and 16 octets.  Strictly, it must be small than $modulus\_len - hLen - 2$ where \textit{modulus\_len} is the size of
+the RSA modulus (in octets), and \textit{hLen} is the length of the message digest produced by the chosen hash.  
+
+\subsection{Extended Signatures}
+
+As of v1.15, the library supports both v1.5 and v2.1 signatures.  The extended signature generation function has the following prototype:
+
+\index{rsa\_sign\_hash\_ex()}
+\begin{verbatim}
+int rsa_sign_hash_ex(
+    const unsigned char *in,       
+          unsigned long  inlen,
+          unsigned char *out,      
+          unsigned long *outlen,
+                    int  padding,
+          prng_state    *prng,     
+                    int  prng_idx,
+                    int  hash_idx, 
+          unsigned long  saltlen,
+                rsa_key *key);
+\end{verbatim}
+
+This will PKCS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets.  Next, the PKCS encoded hash will be RSA 
+\textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.  The \textit{padding} parameter
+must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to produce a v1.5 signature, otherwise, it must be set to \textbf{LTC\_PKCS\_1\_PSS} to produce a 
+v2.1 signature.
+
+When performing a v1.5 signature the \textit{prng}, \textit{prng\_idx}, and \textit{hash\_idx} parameters are not checked and can be left to any
+values such as $\lbrace$\textbf{NULL}, 0, 0$\rbrace$.
+
+\mysection{RSA Signature Verification}
 \index{rsa\_verify\_hash()}
 \begin{verbatim}
-int rsa_verify_hash(const unsigned char *sig,      unsigned long siglen,
-                    const unsigned char *msghash,  unsigned long msghashlen,
-                          int            hash_idx, unsigned long saltlen,
-                          int           *stat,     rsa_key      *key);
-\end{verbatim}
-
-This will RSA ``verify'' the signature in ``sig'' of length ``siglen''.  Next the RSA decoded data is PSS decoded
-and the extracted hash is compared against the message hash ``msghash'' of length ``msghashlen''.
-
-If the RSA decoded data is not a valid PSS message or if the PSS decoded hash does not match the ``msghash'' 
-the value ``res'' is set to $0$.  Otherwise, if the function succeeds and signature is valid ``res'' is set
-to $1$.
-
+int rsa_verify_hash(const unsigned char *sig, 
+                          unsigned long  siglen,
+                    const unsigned char *msghash,  
+                          unsigned long  msghashlen,
+                                    int  hash_idx, 
+                          unsigned long  saltlen,
+                                    int *stat,
+                                rsa_key *key);
+\end{verbatim}
+
+This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets.  Next, the RSA decoded data is PSS decoded
+and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
+
+If the RSA decoded data is not a valid PSS message, or if the PSS decoded hash does not match the \textit{msghash} 
+value, \textit{res} is set to $0$.  Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
+
+\subsection{Extended Verification}
+
+As of v1.15, the library supports both v1.5 and v2.1 signature verification.  The extended signature verification function has the following prototype:
+
+\index{rsa\_verify\_hash\_ex()}
+\begin{verbatim}
+int rsa_verify_hash_ex(
+    const unsigned char *sig,      
+          unsigned long  siglen,
+    const unsigned char *hash,     
+          unsigned long  hashlen,
+                    int  padding,
+                    int  hash_idx, 
+          unsigned long  saltlen,
+                    int *stat,     
+                rsa_key *key);
+\end{verbatim}
+
+This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets.  Next, the RSA decoded data is PKCS decoded
+and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
+
+If the RSA decoded data is not a valid PSS message, or if the PKCS decoded hash does not match the \textit{msghash} 
+value, \textit{res} is set to $0$.  Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
+
+The \textit{padding} parameter must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform a v1.5 verification.  Otherwise, it must be set to 
+\textbf{LTC\_PKCS\_1\_PSS} to perform a v2.1 verification.  When performing a v1.5 verification the \textit{hash\_idx} parameter is ignored.
+
+\mysection{RSA Encryption Example}
+\begin{small}
 \begin{verbatim}
 #include <tomcrypt.h>
 int main(void)
@@ -2713,6 +3503,9 @@
       return EXIT_FAILURE;
    }
 
+   /* register a math library (in this case TomsFastMath)
+   ltc_mp = tfm_desc;
+
    if (register_hash(&sha1_desc) == -1) {
       printf("Error registering sha1");
       return EXIT_FAILURE;
@@ -2733,16 +3526,16 @@
 
    /* fill in pt[] with a key we want to send ... */
    l1 = sizeof(out);
-   if ((err = rsa_encrypt_key(pt,    /* data we wish to encrypt */
-                              16,    /* data is 16 bytes long */
-                             out,    /* where to store ciphertext */
-                             &l1,    /* length of ciphertext */
-                       "TestApp",    /* our lparam for this program */
-                               7,    /* lparam is 7 bytes long */
-                            NULL,    /* PRNG state */
-                        prng_idx,    /* prng idx */
-                        hash_idx,    /* hash idx */
-                            &key)    /* our RSA key */
+   if ((err = rsa_encrypt_key(pt, /* data we wish to encrypt */
+                              16, /* data is 16 bytes long */
+                             out, /* where to store ciphertext */
+                             &l1, /* length of ciphertext */
+                       "TestApp", /* our lparam for this program */
+                               7, /* lparam is 7 bytes long */
+                            NULL, /* PRNG state */
+                        prng_idx, /* prng idx */
+                        hash_idx, /* hash idx */
+                            &key) /* our RSA key */
        ) != CRYPT_OK) {
        printf("rsa_encrypt_key %s", error_to_string(err));
        return EXIT_FAILURE;
@@ -2766,234 +3559,46 @@
    /* if all went well pt == pt2, l2 == 16, res == 1 */
 }
 \end{verbatim}
-
-
-\chapter{Diffie-Hellman Key Exchange}
-
-\section{Background}
-
-Diffie-Hellman was the original public key system proposed.  The system is based upon the group structure
-of finite fields.  For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$ 
-generates a large sub-group of prime order (for unique values of $x$).
-
-A secret key is an exponent $x$ and a public key is the value of $y \equiv g^x\mbox{ }(\mbox{mod }p)$.  The term
-``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$.  The key exchange part of
-Diffie-Hellman arises from the fact that two users A and B with keys $(A_x, A_y)$ and $(B_x, B_y)$ can exchange 
-a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
-
-From this public encryption and signatures can be developed.  The trivial way to encrypt (for example) using a public key 
-$y$ is to perform the key exchange offline.  The sender invents a key $k$ and its public copy 
-$k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
-the message with.  Typically $K$ would be sent to a one-way hash and the message digested used as a key in a 
-symmetric cipher.
-
-It is important that the order of the sub-group that $g$ generates not only be large but also prime.  There are
-discrete logarithm algorithms that take $\sqrt r$ time given the order $r$.  The discrete logarithm can be computed
-modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem.  In the cases where 
-$r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
-
-To thwart such attacks the primes and bases in the library have been designed and fixed.  Given a prime $p$ the order of
- the sub-group generated is a large prime namely ${p - 1} \over 2$.  Such primes are known as ``strong primes'' and the 
-smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
-
-\section{Core Functions}
-
-This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums.  The routines 
-provided are relatively easy to use and only take two function calls to negotiate a shared key.  There is a structure
-called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use.  The first routine is to
-make a Diffie-Hellman private key pair:
-\index{dh\_make\_key()}
-\begin{verbatim}
-int dh_make_key(prng_state *prng, int wprng, 
-                int keysize, dh_key *key);
-\end{verbatim}
-The ``keysize'' is the size of the modulus you want in bytes.  Currently support sizes are 96 to 512 bytes which correspond 
-to key sizes of 768 to 4096 bits. The smaller the key the faster it is to use however it will be less secure.  When 
-specifying a size not explicitly supported by the library it will round {\em up} to the next key size.  If the size is 
-above 512 it will return an error.  So if you pass ``keysize == 32'' it will use a 768 bit key but if you pass 
-``keysize == 20000'' it will return an error.  The primes and generators used are built-into the library and were designed 
-to meet very specific goals.  The primes are strong primes which means that if $p$ is the prime then
-$p-1$ is equal to $2r$ where $r$ is a large prime.  The bases are chosen to generate a group of order $r$ to prevent
-leaking a bit of the key.  This means the bases generate a very large prime order group which is good to make cryptanalysis
-hard.
-
-The next two routines are for exporting/importing Diffie-Hellman keys in a binary format.  This is useful for transport
-over communication mediums.  
-
-\index{dh\_export()} \index{dh\_import()}
-\begin{verbatim}
-int dh_export(unsigned char *out, unsigned long *outlen, 
-              int type, dh_key *key);
-
-int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
-\end{verbatim}
-
-These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with 
-Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails.  You can free a 
-``dh\_key'' using:
-\begin{verbatim}
-void dh_free(dh_key *key);
-\end{verbatim}
-After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret 
-with the other user using:
-\index{dh\_shared\_secret()}
-\begin{verbatim}
-int dh_shared_secret(dh_key *private_key, 
-                     dh_key *public_key, 
-                     unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-
-Where ``private\_key'' is the key you made and ``public\_key'' is the copy of the public key the other user sent you.  The result goes
-into ``out'' and the length into ``outlen''.  If all went correctly the data in ``out'' should be identical for both parties.  It is important to
-note that the two keys have to be the same size in order for this to work.  There is a function to get the size of a
-key:
-\index{dh\_get\_size()}
-\begin{verbatim}
-int dh_get_size(dh_key *key);
-\end{verbatim}
-This returns the size in bytes of the modulus chosen for that key.
-
-\subsection{Remarks on Usage}
-Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something.  An 
-example program that communicates over sockets, using MD5 and 1024-bit DH keys is\footnote{This function is a small example.  It is suggested that proper packaging be used.  For example, if the public key sent is truncated these routines will not detect that.}:
-\newpage
-\begin{small}
-\begin{verbatim}
-int establish_secure_socket(int sock, int mode, unsigned char *key, 
-                            prng_state *prng, int wprng)
-{
-   unsigned char buf[4096], buf2[4096];
-   unsigned long x, len;
-   int res, err, inlen;
-   dh_key mykey, theirkey;
-
-   /* make up our private key */
-   if ((err = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK)  {
-      return err;
-   }
-
-   /* export our key as public */ 
-   x = sizeof(buf);
-   if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
-      res = err;
-      goto done2;
-   }
-
-   if (mode == 0) {
-      /* mode 0 so we send first */
-      if (send(sock, buf, x, 0) != x) {
-         res = CRYPT_ERROR;
-         goto done2;
-      }          
-
-      /* get their key */
-      if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
-         res = CRYPT_ERROR;
-         goto done2;
-      }
-   } else {
-      /* mode >0 so we send second */
-      if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
-         res = CRYPT_ERROR;
-         goto done2;
-      }
-
-      if (send(sock, buf, x, 0) != x) {
-         res = CRYPT_ERROR;
-         goto done2;
-      }
-   }
-
-   if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) { 
-      res = err;
-      goto done2;
-   }
-
-   /* make shared secret */
-   x = sizeof(buf);
-   if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
-      res = err;
-      goto done;
-   }
- 
-   /* hash it */
-   len = 16;        /* default is MD5 so "key" must be at least 16 bytes long */
-   if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
-      res = err;
-      goto done;
-   }
-
-   /* clean up and return */
-   res = CRYPT_OK;
-done:
-   dh_free(&theirkey);
-done2:
-   dh_free(&mykey);
-   zeromem(buf,  sizeof(buf));
-   zeromem(buf2, sizeof(buf2));
-   return res;
-}
-\end{verbatim}
 \end{small}
-\newpage
-\subsection{Remarks on The Snippet}
-When the above code snippet is done (assuming all went well) their will be a shared 128-bit key in the ``key'' array
-passed to ``establish\_secure\_socket()''.
-
-\section{Other Diffie-Hellman Functions}
-In order to test the Diffie-Hellman function internal workings (e.g. the primes and bases) their is a test function made
-available:
-\index{dh\_test()}
-\begin{verbatim}
-int dh_test(void);
-\end{verbatim}
-
-This function returns {\bf CRYPT\_OK} if the bases and primes in the library are correct.  There is one last helper 
-function:
-\index{dh\_sizes()}
-\begin{verbatim}
-void dh_sizes(int *low, int *high);
-\end{verbatim}
-Which stores the smallest and largest key sizes support into the two variables.
-
-\section{DH Packet}
-Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
-algorithms.  
-\index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
-\begin{verbatim}
-int dh_encrypt_key(const unsigned char *in,   unsigned long  inlen,
-                         unsigned char *out,  unsigned long *len, 
-                         prng_state *prng, int wprng, int hash, 
-                         dh_key *key);
-
-int dh_decrypt_key(const unsigned char *in,  unsigned long  inlen,
-                         unsigned char *out, unsigned long *outlen, 
-                         dh_key *key);
-\end{verbatim}
-Where ``in'' is an input symmetric key of no more than 32 bytes.  Essentially these routines created a random public key
-and find the hash of the shared secret.  The message digest is than XOR'ed against the symmetric key.  All of the 
-required data is placed in ``out'' by ``dh\_encrypt\_key()''.   The hash must produce a message digest at least as large
-as the symmetric key you are trying to share.
-
-Similar to the RSA system you can sign and verify a hash of a message.
-\index{dh\_sign\_hash()} \index{dh\_verify\_hash()}
-\begin{verbatim}
-int dh_sign_hash(const unsigned char *in,  unsigned long inlen,
-                       unsigned char *out, unsigned long *outlen,
-                       prng_state *prng, int wprng, dh_key *key);
-
-int dh_verify_hash(const unsigned char *sig, unsigned long siglen,
-                         const unsigned char *hash, unsigned long hashlen, 
-                         int *stat, dh_key *key);
-\end{verbatim}
-
-The ``dh\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a DH packet in ``out''.  
-The ``dh\_verify\_hash'' function verifies the DH signature in ``sig'' against the hash in ``hash''.  It sets ``stat''
-to non-zero if the signature passes or zero if it fails.
+
+\mysection{RSA Key Format}
+
+The RSA key format adopted for exporting and importing keys is the PKCS \#1 format defined by the ASN.1 constructs known as 
+RSAPublicKey and RSAPrivateKey.  Additionally, the OpenSSL key format is supported by the import function only.
+
+\subsection{RSA Key Export}
+To export a RSA key use the following function.
+
+\index{rsa\_export()}
+\begin{verbatim}
+int rsa_export(unsigned char *out, 
+               unsigned long *outlen, 
+                         int  type, 
+                     rsa_key *key);
+\end{verbatim}
+This will export the RSA key in either a RSAPublicKey or RSAPrivateKey (PKCS \#1 types) depending on the value of \textit{type}.  When it is 
+set to \textbf{PK\_PRIVATE} the export format will be RSAPrivateKey and otherwise it will be RSAPublicKey.
+
+\subsection{RSA Key Import}
+To import a RSA key use the following function.
+
+\index{rsa\_import()}
+\begin{verbatim}
+int rsa_import(const unsigned char *in, 
+                     unsigned long  inlen, 
+                           rsa_key *key);
+\end{verbatim}
+
+This will import the key stored in \textit{inlen} and import it to \textit{key}.  If the function fails it will automatically free any allocated memory.  This
+function can import both RSAPublicKey and RSAPrivateKey formats.
+
+As of v1.06 this function can also import OpenSSL DER formatted public RSA keys.  They are essentially encapsulated RSAPublicKeys.  LibTomCrypt will
+import the key, strip off the additional data (it's the preferred hash) and fill in the rsa\_key structure as if it were a native RSAPublicKey.  Note that
+there is no function provided to export in this format.  
 
 \chapter{Elliptic Curve Cryptography}
 
-\section{Background}
+\mysection{Background}
 The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the 
 Diffie-Hellman routines in the previous chapter.  Elliptic curves (of certain forms) have the benefit that they are harder
 to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
@@ -3005,6 +3610,9 @@
 http://csrc.nist.gov/cryptval/dss.htm
 \end{verbatim}
 
+As of v1.15 three new curves from the SECG standards are also included they are the secp112r1, secp128r1, and secp160r1 curves.  These curves were added to 
+support smaller devices which do not need as large keys for security.
+
 They are all curves over the integers modulo a prime.  The curves have the basic equation that is:
 \begin{equation}
 y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
@@ -3012,17 +3620,54 @@
 
 The variable $b$ is chosen such that the number of points is nearly maximal.  In fact the order of the base points $\beta$ 
 provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$.  The curves
-range in order from $\approx 2^{192}$ points to $\approx 2^{521}$.  According to the source document any key size greater
+range in order from $\approx 2^{112}$ points to $\approx 2^{521}$.  According to the source document any key size greater
 than or equal to 256-bits is sufficient for long term security.  
 
-\section{Key Format}
-LibTomCrypt uses it's own format for ECC public and private keys.  While ANSI X9.62 partially specifies key formats (it covers public keys) it does it in a less
-than ideally simple manner.  In the case of LibTomCrypt it is meant \textbf{solely} for NIST $GF(p)$ curves.  The format of the keys is as follows:
-
+\mysection{Fixed Point Optimizations}
+\index{Fixed Point ECC}
+\index{MECC\_FP}
+As of v1.12 of LibTomCrypt, support for Fixed Point ECC point multiplication has been added.  It is a generic optimization that is
+supported by any conforming math plugin.  It is enabled by defining \textbf{MECC\_FP} during the build, such as 
+
+\begin{verbatim}
+CFLAGS="-DTFM_DESC -DMECC_FP" make 
+\end{verbatim}
+
+which will build LTC using the TFM math library and enabling this new feature.  The feature is not enabled by default as it is \textbf{NOT} thread
+safe (by default).  It supports the LTC locking macros (such as by enabling LTC\_PTHREAD), but by default is not locked.
+
+\index{FP\_ENTRIES}
+The optimization works by using a Fixed Point multiplier on any base point you use twice or more in a short period of time.  It has a limited size
+cache (of FP\_ENTRIES entries) which it uses to hold recent bases passed to ltc\_ecc\_mulmod().  Any base detected to be used twice is sent through the
+pre--computation phase, and then the fixed point algorithm can be used.  For example, if you use a NIST base point twice in a row, the 2$^{nd}$ and 
+all subsequent point multiplications with that point will use the faster algorithm.
+
+\index{FP\_LUT}
+The optimization uses a window on the multiplicand of FP\_LUT bits (default: 8, min: 2, max: 12), and this controls the memory/time trade-off. The larger the 
+value the faster the algorithm will be but the more memory it will take.  The memory usage is $3 \cdot 2^{FP\_LUT}$ integers which by default
+with TFM amounts to about 400kB of memory.  Tuning TFM (by changing FP\_SIZE) can decrease the usage by a fair amount.  Memory is only used by a cache entry
+if it is active.  Both FP\_ENTRIES and FP\_LUT are definable on the command line if you wish to override them. For instance,
+
+\begin{verbatim}
+CFLAGS="-DTFM_DESC -DMECC_FP -DFP_ENTRIES=8 -DFP_LUT=6" make
+\end{verbatim}
+
+\begin{flushleft} 
+\index{FP\_SIZE} \index{TFM} \index{tfm.h}
+would define a window of 6 bits and limit the cache to 8 entries.  Generally, it is better to first tune TFM by adjusting FP\_SIZE (from tfm.h).  It defaults
+to 4096 bits (512 bytes) which is way more than what is required by ECC.  At most, you need 1152 bits to accommodate ECC--521.  If you're only using (say)
+ECC--256 you will only need 576 bits, which would reduce the memory usage by 700\%.
+\end{flushleft}
+
+\mysection{Key Format}
+LibTomCrypt uses a unique format for ECC public and private keys.  While ANSI X9.63 partially specifies key formats, it does it in a less than ideally simple manner.  \
+In the case of LibTomCrypt, it is meant \textbf{solely} for NIST and SECG $GF(p)$ curves.  The format of the keys is as follows:
+
+\index{ECC Key Format}
 \begin{small}
 \begin{verbatim}
 ECCPublicKey ::= SEQUENCE {
-    flags       BIT STRING(1), -- public/private flag (always zero), 
+    flags       BIT STRING(0), -- public/private flag (always zero), 
     keySize     INTEGER,       -- Curve size (in bits) divided by eight 
                                -- and rounded down, e.g. 521 => 65
     pubkey.x    INTEGER,       -- The X co-ordinate of the public key point
@@ -3042,174 +3687,326 @@
 
 The first flags bit denotes whether the key is public (zero) or private (one).  
 
-\section{Core Functions}
-
-Like the DH routines there is a key structure ``ecc\_key'' used by the functions.  There is a function to make a key:
+\vfil
+
+\mysection{ECC Curve Parameters}
+The library uses the following structure to describe an elliptic curve.  This is used internally, as well as by the new
+extended ECC functions which allow the user to specify their own curves. 
+
+\index{ltc\_ecc\_set\_type}
+\begin{verbatim}
+/** Structure defines a NIST GF(p) curve */
+typedef struct {
+   /** The size of the curve in octets */
+   int size;
+
+   /** name of curve */
+   char *name; 
+
+   /** The prime that defines the field (encoded in hex) */
+   char *prime;
+
+   /** The fields B param (hex) */
+   char *B;
+
+   /** The order of the curve (hex) */
+   char *order;
+  
+   /** The x co-ordinate of the base point on the curve (hex) */
+   char *Gx;
+ 
+   /** The y co-ordinate of the base point on the curve (hex) */
+   char *Gy;
+} ltc_ecc_set_type;
+\end{verbatim}
+
+The curve must be of the form $y^2 = x^3 - 3x + b$, and all of the integer parameters are encoded in hexadecimal format.
+
+\mysection{Core Functions}
+\subsection{ECC Key Generation}
+There is a key structure called \textit{ecc\_key} used by the ECC functions.  There is a function to make a key:
 \index{ecc\_make\_key()}
 \begin{verbatim}
-int ecc_make_key(prng_state *prng, int wprng, 
-                 int keysize, ecc_key *key);
-\end{verbatim}
-
-The ``keysize'' is the size of the modulus in bytes desired.  Currently directly supported values are 24, 28, 32, 48 and 65 bytes which
-correspond to key sizes of 192, 224, 256, 384 and 521 bits respectively.  If you pass a key size that is between any key size
-it will round the keysize up to the next available one.  The rest of the parameters work like they do in the ``dh\_make\_key()'' function.  
-To free the ram allocated by a key call:
+int ecc_make_key(prng_state *prng, 
+                        int  wprng, 
+                        int  keysize, 
+                    ecc_key *key);
+\end{verbatim}
+
+The \textit{keysize} is the size of the modulus in bytes desired.  Currently directly supported values are 12, 16, 20, 24, 28, 32, 48, and 65 bytes which
+correspond to key sizes of 112, 128, 160, 192, 224, 256, 384, and 521 bits respectively.  If you pass a key size that is between any key size it will round 
+the keysize up to the next available one.
+
+The function will free any internally allocated resources if there is an error.
+
+\subsection{Extended Key Generation}
+As of v1.16, the library supports an extended key generation routine which allows the user to specify their own curve.  It is specified as follows:
+
+\index{ecc\_make\_key\_ex()}
+\begin{verbatim}
+int  ecc_make_key_ex(
+                 prng_state *prng, 
+                        int  wprng, 
+                    ecc_key *key, 
+     const ltc_ecc_set_type *dp);
+\end{verbatim}
+
+This function generates a random ECC key over the curve specified by the parameters by \textit{dp}.  The rest of the parameters are equivalent to
+those from the original key generation function.
+
+\subsection{ECC Key Free}
+To free the memory allocated by a ecc\_make\_key(), ecc\_make\_key\_ex(), ecc\_import(), or ecc\_import\_ex() call use the following function:
 \index{ecc\_free()}
 \begin{verbatim}
 void ecc_free(ecc_key *key);
 \end{verbatim}
 
-To import and export a key there are: 
+\subsection{ECC Key Export}
+To export an ECC key using the LibTomCrypt format call the following function:
 \index{ecc\_export()}
+\begin{verbatim}
+int ecc_export(unsigned char *out, 
+               unsigned long *outlen, 
+                         int  type, 
+                     ecc_key *key);
+\end{verbatim}
+This will export the key with the given \textit{type} (\textbf{PK\_PUBLIC} or \textbf{PK\_PRIVATE}), and store it to \textit{out}.  
+
+\subsection{ECC Key Import}
+The following function imports a LibTomCrypt format ECC key:
 \index{ecc\_import()}
 \begin{verbatim}
-int ecc_export(unsigned char *out, unsigned long *outlen, 
-               int type, ecc_key *key);
-
-int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
-\end{verbatim}
-These two work exactly like there DH counterparts.  Finally when you share your public key you can make a shared secret
-with:
+int ecc_import(const unsigned char *in, 
+                     unsigned long  inlen, 
+                           ecc_key *key);
+\end{verbatim}
+This will import the ECC key from \textit{in}, and store it in the ecc\_key structure pointed to by \textit{key}.  If the operation fails it will free
+any allocated memory automatically.
+
+\subsection{Extended Key Import}
+
+The following function imports a LibTomCrypt format ECC key using a specified set of curve parameters:
+\index{ecc\_import\_ex()}
+\begin{verbatim}
+int  ecc_import_ex(const unsigned char *in, 
+                         unsigned long  inlen, 
+                               ecc_key *key, 
+                const ltc_ecc_set_type *dp);
+\end{verbatim}
+This will import the key from the array pointed to by \textit{in} of length \textit{inlen} octets.  The key is stored in
+the ECC structure pointed to by \textit{key}.  The curve is specified by the parameters pointed to by \textit{dp}.  The function will free
+all internally allocated memory upon error.
+
+\subsection{ANSI X9.63 Export}
+The following function exports an ECC public key in the ANSI X9.63 format:
+
+\index{ecc\_ansi\_x963\_export()}
+\begin{verbatim}
+int ecc_ansi_x963_export(      ecc_key *key, 
+                         unsigned char *out, 
+                         unsigned long *outlen);
+\end{verbatim}
+The ECC key pointed to by \textit{key} is exported in public fashion to the array pointed to by \textit{out}.  The ANSI X9.63 format used is from
+section 4.3.6 of the standard.  It does not allow for the export of private keys.
+
+\subsection{ANSI X9.63 Import}
+The following function imports an ANSI X9.63 section 4.3.6 format public ECC key:
+
+\index{ecc\_ansi\_x963\_import()}
+\begin{verbatim}
+int ecc_ansi_x963_import(const unsigned char *in, 
+                               unsigned long  inlen, 
+                                     ecc_key *key);
+\end{verbatim}
+This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets.  The imported key is stored in the ECC key pointed to by 
+\textit{key}.  The function will free any allocated memory upon error.
+
+\subsection{Extended ANSI X9.63 Import}
+The following function allows the importing of an ANSI x9.63 section 4.3.6 format public ECC key using user specified domain parameters:
+
+\index{ecc\_ansi\_x963\_import\_ex()}
+\begin{verbatim}
+int ecc_ansi_x963_import_ex(const unsigned char *in, 
+                                  unsigned long  inlen, 
+                                        ecc_key *key, 
+                               ltc_ecc_set_type *dp);
+\end{verbatim}
+This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets using the domain parameters pointed to by \textit{dp}.  
+The imported key is stored in the ECC key pointed to by \textit{key}.  The function will free any allocated memory upon error.
+
+\subsection{ECC Shared Secret}
+To construct a Diffie-Hellman shared secret with a private and public ECC key, use the following function:
 \index{ecc\_shared\_secret()}
 \begin{verbatim}
-int ecc_shared_secret(ecc_key *private_key, 
-                      ecc_key *public_key, 
-                      unsigned char *out, unsigned long *outlen);
-\end{verbatim}
-Which works exactly like the DH counterpart, the ``private\_key'' is your own key and ``public\_key'' is the key the other
-user sent you.   Note that this function stores both $x$ and $y$ co-ordinates of the shared
-elliptic point.  You should hash the output to get a shared key in a more compact and useful form (most of the entropy is 
-in $x$ anyways).  Both keys have to be the same size for this to work, to help there is a function to get the size in bytes
- of a key.
-\index{ecc\_get\_size()}
-\begin{verbatim}
-int ecc_get_size(ecc_key *key);
-\end{verbatim}
-
-To test the ECC routines and to get the minimum and maximum key sizes there are these two functions:
-\index{ecc\_test()}
-\begin{verbatim}
-int ecc_test(void);
-void ecc_sizes(int *low, int *high);
-\end{verbatim}
-Which both work like their DH counterparts.
-
-\section{ECC Packet}
-Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
-algorithms.
-
-\index{ecc\_encrypt\_key()} \index{ecc\_decrypt\_key()}
-\begin{verbatim}
-int ecc_encrypt_key(const unsigned char *in,   unsigned long  inlen,
-                          unsigned char *out,  unsigned long *outlen, 
-                          prng_state *prng, int wprng, int hash, 
-                          ecc_key *key);
-
-int ecc_decrypt_key(const unsigned char *in,  unsigned long  inlen,
-                          unsigned char *out, unsigned long *outlen, 
-                          ecc_key *key);
-\end{verbatim}
-
-Where ``in'' is an input symmetric key of no more than 64 bytes.  Essentially these routines created a random public key
-and find the hash of the shared secret.  The message digest is than XOR'ed against the symmetric key.  All of the required
-data is placed in ``out'' by ``ecc\_encrypt\_key()''.   The hash chosen must produce a message digest at least as large
-as the symmetric key you are trying to share.
-
-\subsection{Encrypt Packet Format}
-
+int ecc_shared_secret(      ecc_key *private_key, 
+                            ecc_key *public_key, 
+                      unsigned char *out, 
+                      unsigned long *outlen);
+\end{verbatim}
+The \textit{private\_key} is typically the local private key, and \textit{public\_key} is the key the remote party has shared.   
+Note: this function stores only the $x$ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECC--DH.  
+
+\mysection{ECC Diffie-Hellman Encryption}
+ECC--DH Encryption is performed by producing a random key, hashing it, and XOR'ing the digest against the plaintext.  It is not strictly ANSI X9.63 compliant
+but it is very similar.  It has been extended by using an ASN.1 sequence and hash object identifiers to allow portable usage.  The following function
+encrypts a short string (no longer than the message digest) using this technique:
+
+\subsection{ECC-DH Encryption}
+\index{ecc\_encrypt\_key()}
+\begin{verbatim}
+int ecc_encrypt_key(const unsigned char *in,
+                          unsigned long  inlen,
+                          unsigned char *out, 
+                          unsigned long *outlen, 
+                             prng_state *prng, 
+                                    int  wprng, 
+                                    int  hash, 
+                                ecc_key *key);
+\end{verbatim}
+
+As the name implies this function encrypts a (symmetric) key, and is not intended for encrypting long messages directly.  It will encrypt the 
+plaintext in the array pointed to by \textit{in} of length \textit{inlen} octets.  It uses the public ECC key pointed to by \textit{key}, and
+hash algorithm indexed by \textit{hash} to construct a shared secret which may be XOR'ed against the plaintext.  The ciphertext is stored in
+the output buffer pointed to by \textit{out} of length \textit{outlen} octets.
+
+The data is encrypted to the public ECC \textit{key} such that only the holder of the private key can decrypt the payload.  To have multiple 
+recipients multiple call to this function for each public ECC key is required.
+
+\subsection{ECC-DH Decryption}
+\index{ecc\_decrypt\_key()}
+\begin{verbatim}
+int ecc_decrypt_key(const unsigned char *in, 
+                          unsigned long  inlen,
+                          unsigned char *out, 
+                          unsigned long *outlen, 
+                                ecc_key *key);
+\end{verbatim}
+
+This function will decrypt an encrypted payload.  The \textit{key} provided must be the private key corresponding to the public key
+used during encryption.  If the wrong key is provided the function will not specifically return an error code.  It is important
+to use some form of challenge response in that case (e.g. compute a MAC of a known string).
+
+\subsection{ECC Encryption Format}
 The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
 
 \begin{verbatim}
 ECCEncrypt ::= SEQUENCE {
    hashID        OBJECT IDENTIFIER, -- OID of hash used
-   pubkey        OCTET STRING     , -- Encapsulated ECCPublicKey (see above)
-   skey          OCTET STRING       -- xor of plaintext and "hash of shared secret"
+   pubkey        OCTET STRING     , -- Encapsulated ECCPublicKey
+   skey          OCTET STRING       -- xor of plaintext and 
+                                    --"hash of shared secret"
 }
 \end{verbatim}
 
-There are also functions to sign and verify the hash of a message.
-\index{ecc\_sign\_hash()} \index{ecc\_verify\_hash()}
-\begin{verbatim}
-int ecc_sign_hash(const unsigned char *in,  unsigned long inlen,
-                        unsigned char *out, unsigned long *outlen,
-                        prng_state *prng, int wprng, ecc_key *key);
-
-int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
-                    const unsigned char *hash, unsigned long hashlen, 
-                          int *stat, ecc_key *key);
-\end{verbatim}
-
-The ``ecc\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a ECC packet in ``out''.  
-The ``ecc\_verify\_hash'' function verifies the ECC signature in ``sig'' against the hash in ``hash''.  It sets ``stat''
-to non-zero if the signature passes or zero if it fails.
+\mysection{EC DSA Signatures}
+
+There are also functions to sign and verify messages.  They use the ANSI X9.62 EC-DSA algorithm to generate and verify signatures in the
+ANSI X9.62 format.  
+
+\subsection{EC-DSA Signature Generation}
+To sign a message digest (hash) use the following function:
+
+\index{ecc\_sign\_hash()}
+\begin{verbatim}
+int ecc_sign_hash(const unsigned char *in,  
+                        unsigned long  inlen,
+                        unsigned char *out, 
+                        unsigned long *outlen,
+                           prng_state *prng, 
+                                  int  wprng, 
+                              ecc_key *key);
+\end{verbatim}
+
+This function will EC--DSA sign the message digest stored in the array pointed to by \textit{in} of length \textit{inlen} octets.  The signature
+will be stored in the array pointed to by \textit{out} of length \textit{outlen} octets.  The function requires a properly seeded PRNG, and 
+the ECC \textit{key} provided must be a private key.
+
+\subsection{EC-DSA Signature Verification}
+\index{ecc\_verify\_hash()}
+\begin{verbatim}
+int ecc_verify_hash(const unsigned char *sig, 
+                          unsigned long  siglen,
+                    const unsigned char *hash, 
+                          unsigned long  hashlen, 
+                                    int *stat, 
+                                ecc_key *key);
+\end{verbatim}
+
+This function will verify the EC-DSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, against the message digest 
+pointed to by the array \textit{hash} of length \textit{hashlen}.  It will store a non--zero value in \textit{stat} if the signature is valid.  Note: 
+the function will not return an error if the signature is invalid.  It will return an error, if the actual signature payload is an invalid format.  
+The ECC \textit{key} must be the public (or private) ECC key corresponding to the key that performed the signature.
 
 \subsection{Signature Format}
-The signature code is an implementation of X9.62 EC-DSA and the output is comformant for GF(p) curves.
-
-\section{ECC Keysizes}
-With ECC if you try and sign a hash that is bigger than your ECC key you can run into problems.  The math will still work
-and in effect the signature will still work.  With ECC keys the strength of the signature is limited by the size of
-the hash or the size of they key, whichever is smaller.  For example, if you sign with SHA256 and an ECC-192 key in effect
-you have 192-bits of security.  
-
-The library will not warn you if you make this mistake so it is important to check yourself before using the 
-signatures.
+The signature code is an implementation of X9.62 EC--DSA, and the output is compliant for GF(p) curves.
+
+\mysection{ECC Keysizes}
+With ECC if you try to sign a hash that is bigger than your ECC key you can run into problems.  The math will still work, and in effect the signature will still 
+work.  With ECC keys the strength of the signature is limited by the size of the hash, or the size of they key, whichever is smaller.  For example, if you sign with 
+SHA256 and an ECC-192 key, you in effect have 96--bits of security.  
+
+The library will not warn you if you make this mistake, so it is important to check yourself before using the signatures.
 
 \chapter{Digital Signature Algorithm}
-\section{Introduction}
+\mysection{Introduction}
 The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to 
-reduce the bandwidth of a signature.  For example, to have ``80-bits of security'' with ElGamal you need a group of 
-order at least 1024-bits.  With DSA you need a group of order at least 160-bits.  By comparison the ElGamal signature
-would require at least 256 bytes where as the DSA signature would require only at least 40 bytes.  
-
-The API for the DSA is essentially the same as the other PK algorithms.  Except in the case of DSA no encryption or
-decryption routines are provided.  
-
-\section{Key Format}
+reduce the bandwidth of the signatures.  For example, to have \textit{80-bits of security} with ElGamal, you need a group with an order of at least 1024--bits.  
+With DSA, you need a group of order at least 160--bits.  By comparison, the ElGamal signature would require at least 256 bytes of storage, whereas the DSA signature 
+would require only at least 40 bytes.  
+
+\mysection{Key Format}
 Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
 now so that others can interoperate with this library.
 
 \begin{verbatim}
 DSAPublicKey ::= SEQUENCE {
-    publicFlags    BIT STRING(1), -- must be 0
-    g              INTEGER      , -- base generator, check that g^q mod p == 1
+    publicFlags    BIT STRING(0), -- must be 0
+    g              INTEGER      , -- base generator
+                                  -- check that g^q mod p == 1
                                   -- and that 1 < g < p - 1
     p              INTEGER      , -- prime modulus 
-    q              INTEGER      , -- order of sub-group (must be prime)
-    y              INTEGER      , -- public key, specifically, g^x mod p, 
+    q              INTEGER      , -- order of sub-group 
+                                  -- (must be prime)
+    y              INTEGER      , -- public key, specifically, 
+                                  -- g^x mod p, 
                                   -- check that y^q mod p == 1
                                   -- and that 1 < y < p - 1
 }
 
 DSAPrivateKey ::= SEQUENCE {
     publicFlags    BIT STRING(1), -- must be 1
-    g              INTEGER      , -- base generator, check that g^q mod p == 1
+    g              INTEGER      , -- base generator
+                                  -- check that g^q mod p == 1
                                   -- and that 1 < g < p - 1
     p              INTEGER      , -- prime modulus 
-    q              INTEGER      , -- order of sub-group (must be prime)
-    y              INTEGER      , -- public key, specifically, g^x mod p, 
+    q              INTEGER      , -- order of sub-group 
+                                  -- (must be prime)
+    y              INTEGER      , -- public key, specifically, 
+                                  -- g^x mod p, 
                                   -- check that y^q mod p == 1
                                   -- and that 1 < y < p - 1
     x              INTEGER        -- private key
 }
 \end{verbatim}
 
-The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys.  This makes the structure uniquely decodable and easy
-to work with.
-
-\section{Key Generation}
+The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys.  This makes the structure uniquely decodable, 
+and easy to work with.
+
+\mysection{Key Generation}
 To make a DSA key you must call the following function
 \begin{verbatim}
-int dsa_make_key(prng_state *prng, int wprng, 
-                 int group_size, int modulus_size, 
-                 dsa_key *key);
-\end{verbatim}
-The variable ``prng'' is an active PRNG state and ``wprng'' the index to the descriptor.  ``group\_size'' and 
-``modulus\_size'' control the difficulty of forging a signature.  Both parameters are in bytes.  The larger the
-``group\_size'' the more difficult a forgery becomes upto a limit.  The value of $group\_size$ is limited by 
+int dsa_make_key(prng_state *prng, 
+                        int  wprng, 
+                        int  group_size, 
+                        int  modulus_size, 
+                    dsa_key *key);
+\end{verbatim}
+The variable \textit{prng} is an active PRNG state and \textit{wprng} the index to the descriptor.  \textit{group\_size} and 
+\textit{modulus\_size} control the difficulty of forging a signature.  Both parameters are in bytes.  The larger the
+\textit{group\_size} the more difficult a forgery becomes upto a limit.  The value of $group\_size$ is limited by 
 $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$.  Suggested values for the pairs are as follows.
 
+\begin{figure}[here]
 \begin{center}
 \begin{tabular}{|c|c|c|}
 \hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
@@ -3220,6 +4017,8 @@
 \hline
 \end{tabular}
 \end{center}
+\caption{DSA Key Sizes}
+\end{figure}
 
 When you are finished with a DSA key you can call the following function to free the memory used.
 \index{dsa\_free()}
@@ -3227,7 +4026,7 @@
 void dsa_free(dsa_key *key);
 \end{verbatim}
 
-\section{Key Verification}
+\mysection{Key Verification}
 Each DSA key is composed of the following variables.
 
 \begin{enumerate}
@@ -3266,83 +4065,136 @@
 int dsa_verify_key(dsa_key *key, int *stat);
 \end{verbatim}
 
-This will test ``key'' and store the result in ``stat''.  If the result is $stat = 0$ the DSA key failed one of the tests
+This will test \textit{key} and store the result in \textit{stat}.  If the result is $stat = 0$ the DSA key failed one of the tests
 and should not be used at all.  If the result is $stat = 1$ the DSA key is valid (as far as valid mathematics are concerned).
 
-\section{Signatures}
-To generate a DSA signature call the following function
+\mysection{Signatures}
+\subsection{Signature Generation}
+To generate a DSA signature call the following function:
 
 \index{dsa\_sign\_hash()}
 \begin{verbatim}
-int dsa_sign_hash(const unsigned char *in,  unsigned long inlen,
-                        unsigned char *out, unsigned long *outlen,
-                        prng_state *prng, int wprng, dsa_key *key);
-\end{verbatim}
-
-Which will sign the data in ``in'' of length ``inlen'' bytes.  The signature is stored in ``out'' and the size
-of the signature in ``outlen''.  If the signature is longer than the size you initially specify in ``outlen'' nothing
-is stored and the function returns an error code.  The DSA ``key'' must be of the \textbf{PK\_PRIVATE} persuasion.
-
-To verify a hash created with that function use the following function
+int dsa_sign_hash(const unsigned char *in,  
+                        unsigned long  inlen,
+                        unsigned char *out, 
+                        unsigned long *outlen,
+                           prng_state *prng, 
+                                  int  wprng, 
+                              dsa_key *key);
+\end{verbatim}
+
+Which will sign the data in \textit{in} of length \textit{inlen} bytes.  The signature is stored in \textit{out} and the size
+of the signature in \textit{outlen}.  If the signature is longer than the size you initially specify in \textit{outlen} nothing
+is stored and the function returns an error code.  The DSA \textit{key} must be of the \textbf{PK\_PRIVATE} persuasion.
+
+\subsection{Signature Verification}
+To verify a hash created with that function use the following function:
 
 \index{dsa\_verify\_hash()} 
 \begin{verbatim}
-int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
-                    const unsigned char *hash, unsigned long inlen, 
-                    int *stat, dsa_key *key);
-\end{verbatim}
-Which will verify the data in ``hash'' of length ``inlen'' against the signature stored in ``sig'' of length ``siglen''.  
-It will set ``stat'' to $1$ if the signature is valid, otherwise it sets ``stat'' to $0$.  
-
-\section{Import and Export}
-
-To export a DSA key so that it can be transported use the following function
+int dsa_verify_hash(const unsigned char *sig, 
+                          unsigned long  siglen,
+                    const unsigned char *hash, 
+                          unsigned long  inlen, 
+                                    int *stat, 
+                                dsa_key *key);
+\end{verbatim}
+Which will verify the data in \textit{hash} of length \textit{inlen} against the signature stored in \textit{sig} of length \textit{siglen}.  
+It will set \textit{stat} to $1$ if the signature is valid, otherwise it sets \textit{stat} to $0$.  
+
+\mysection{DSA Encrypt and Decrypt}
+As of version 1.07, the DSA keys can be used to encrypt and decrypt small payloads.  It works similar to the ECC encryption where
+a shared key is computed, and the hash of the shared key XOR'ed against the plaintext forms the ciphertext.  The format used is functional port of
+the ECC encryption format to the DSA algorithm.
+
+\subsection{DSA Encryption}
+This function will encrypt a small payload with a recipients public DSA key.
+
+\index{dsa\_encrypt\_key()}
+\begin{verbatim}
+int dsa_encrypt_key(const unsigned char *in, 
+                          unsigned long  inlen,
+                          unsigned char *out,  
+                          unsigned long *outlen, 
+                             prng_state *prng, 
+                                    int  wprng, 
+                                    int  hash, 
+                                dsa_key *key);
+\end{verbatim}
+
+This will encrypt the payload in \textit{in} of length \textit{inlen} and store the ciphertext in the output buffer \textit{out}.  The
+length of the ciphertext \textit{outlen} must be originally set to the length of the output buffer.  The DSA \textit{key} can be 
+a public key.
+
+\subsection{DSA Decryption}
+
+\index{dsa\_decrypt\_key()}
+\begin{verbatim}                      
+int dsa_decrypt_key(const unsigned char *in,  
+                          unsigned long  inlen,
+                          unsigned char *out, 
+                          unsigned long *outlen, 
+                                dsa_key *key);
+\end{verbatim}
+This will decrypt the ciphertext \textit{in} of length \textit{inlen}, and store the original payload in \textit{out} of length \textit{outlen}.  
+The DSA \textit{key} must be a private key.
+
+\mysection{DSA Key Import and Export}
+
+\subsection{DSA Key Export}
+To export a DSA key so that it can be transported use the following function:
 \index{dsa\_export()}
 \begin{verbatim}
-int dsa_export(unsigned char *out, unsigned long *outlen, 
-               int type, 
-               dsa_key *key);
-\end{verbatim}
-This will export the DSA ``key'' to the buffer ``out'' and set the length in ``outlen'' (which must have been previously
-initialized to the maximum buffer size).  The ``type`` variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
+int dsa_export(unsigned char *out, 
+               unsigned long *outlen, 
+                         int  type, 
+                     dsa_key *key);
+\end{verbatim}
+This will export the DSA \textit{key} to the buffer \textit{out} and set the length in \textit{outlen} (which must have been previously
+initialized to the maximum buffer size).  The \textit{type} variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
 depending on whether you want to export a private or public copy of the DSA key.
 
+\subsection{DSA Key Import}
 To import an exported DSA key use the following function
-
+:
 \index{dsa\_import()}
 \begin{verbatim}
-int dsa_import(const unsigned char *in, unsigned long inlen, 
-               dsa_key *key);
-\end{verbatim}
-
-This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''.  If the process fails the function
+int dsa_import(const unsigned char *in, 
+                     unsigned long  inlen, 
+                           dsa_key *key);
+\end{verbatim}
+
+This will import the DSA key from the buffer \textit{in} of length \textit{inlen} to the \textit{key}.  If the process fails the function
 will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).  
 
 \chapter{Standards Support}
-\section{ASN.1 Formats}
+\mysection{ASN.1 Formats}
 LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols.  The data types
 are all provided with three basic functions with \textit{similar} prototypes.  One function has been dedicated to calculate the length in octets of a given
-format and two functions have been dedicated to encoding and decoding the format.  
-
-On top of the basic data types are the SEQUENCE and\footnote{Planned for LTC 1.06} SET data types which are collections of other ASN.1 types.  They are provided 
-in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure.  It is defined as 
+format, and two functions have been dedicated to encoding and decoding the format.  
+
+On top of the basic data types are the SEQUENCE and SET data types which are collections of other ASN.1 types.  They are provided 
+in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure.  It is defined as the following:
 
 \index{ltc\_asn1\_list structure}
 \begin{verbatim}
 typedef struct {
-   int           type;
-   void         *data;
-   unsigned long size;
-   int           used;
+   int                    type;
+   void                  *data;
+   unsigned long          size;
+   int                    used;
+   struct ltc_asn1_list_ *prev,  *next, 
+                         *child, *parent;
 } ltc_asn1_list;
 \end{verbatim}
 
-The ``type'' field is one of the following ASN.1 field definitions.  The ``data'' pointer is a void pointer to the data to be encoded (or the destination) and the 
-``size'' field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type).  The ``used'' field is primarily for the CHOICE decoder
+\index{LTC\_SET\_ASN1 macro}
+The \textit{type} field is one of the following ASN.1 field definitions.  The \textit{data} pointer is a void pointer to the data to be encoded (or the destination) and the 
+\textit{size} field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type).  The \textit{used} field is primarily for the CHOICE decoder
 and reflects if the particular member of a list was the decoded data type.  To help build the lists in an orderly fashion the macro
-``LTC\_SET\_ASN1(list, index, Type, Data, Size)'' has been provided.
-
-It will assign to the ``index''th position in the ``list'' the tripplet (Type, Data, Size).  An example usage would be:
+\textit{LTC\_SET\_ASN1(list, index, Type, Data, Size)} has been provided.
+
+It will assign to the \textit{index}th position in the \textit{list} the triplet (Type, Data, Size).  An example usage would be:
 
 \begin{small}
 \begin{verbatim}
@@ -3376,16 +4228,20 @@
 \begin{tabular}{|l|l|}
 \hline \textbf{Definition}           & \textbf{ASN.1 Type} \\
 \hline LTC\_ASN1\_EOL                & End of a ASN.1 list structure. \\
+\hline LTC\_ASN1\_BOOLEAN            & BOOLEAN type \\
 \hline LTC\_ASN1\_INTEGER            & INTEGER (uses mp\_int) \\
 \hline LTC\_ASN1\_SHORT\_INTEGER     & INTEGER (32--bit using unsigned long) \\
 \hline LTC\_ASN1\_BIT\_STRING        & BIT STRING (one bit per char) \\
 \hline LTC\_ASN1\_OCTET\_STRING      & OCTET STRING (one octet per char) \\
 \hline LTC\_ASN1\_NULL               & NULL \\
-\hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER (words are in unsigned long) \\
+\hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER  \\
 \hline LTC\_ASN1\_IA5\_STRING        & IA5 STRING (one octet per char) \\
-\hline LTC\_ASN1\_PRINTABLE\_STRING  & PRINTABLE STIRNG (one octet per char) \\
+\hline LTC\_ASN1\_UTF8\_STRING       & UTF8 STRING (one wchar\_t per char) \\
+\hline LTC\_ASN1\_PRINTABLE\_STRING  & PRINTABLE STRING (one octet per char) \\
 \hline LTC\_ASN1\_UTCTIME            & UTCTIME (see ltc\_utctime structure) \\
-\hline LTC\_ASN1\_SEQUENCE           & SEQUENCE OF \\
+\hline LTC\_ASN1\_SEQUENCE           & SEQUENCE (and SEQUENCE OF) \\
+\hline LTC\_ASN1\_SET                & SET \\
+\hline LTC\_ASN1\_SETOF              & SET OF \\
 \hline LTC\_ASN1\_CHOICE             & CHOICE \\
 \hline
 \end{tabular}
@@ -3397,39 +4253,43 @@
 \subsection{SEQUENCE Type}
 The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
 
-\subsubsection{SEUQNECE Encoding}
+\subsubsection{SEQUENCE Encoding}
 To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers.  The encoding is performed
 with the following function.
 
 \index{der\_encode\_sequence()}
 \begin{verbatim}
-int der_encode_sequence(ltc_asn1_list *list, unsigned long inlen,
-                        unsigned char *out,  unsigned long *outlen);
-\end{verbatim}
-This encodes a sequence of items pointed to by ``list'' where the list has ``inlen'' items in it.  The SEQUENCE will be encoded to ``out'' and of length ``outlen''.  The
-function will terminate when it reads all the items out of the list (upto ``inlen'') or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
-
-The ``data'' pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
+int der_encode_sequence(ltc_asn1_list *list, 
+                        unsigned long  inlen,
+                        unsigned char *out,  
+                        unsigned long *outlen);
+\end{verbatim}
+This encodes a sequence of items pointed to by \textit{list} where the list has \textit{inlen} items in it.  The SEQUENCE will be encoded to \textit{out} and of length \textit{outlen}.  The
+function will terminate when it reads all the items out of the list (upto \textit{inlen}) or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
+
+The \textit{data} pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
 verbatim to the dependent encoder.  The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions.  In these cases
-the ``data'' pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
+the \textit{data} pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
 
 \subsubsection{SEQUENCE Decoding}
 
 \index{der\_decode\_sequence()}
 
-Decoding a SEQUENCE is similar to encoding.  You set up an array of \textbf{ltc\_asn1\_list} where in this case the ``size'' member is the maximum size 
-(in certain cases).  For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the ``size'' field is updated after successful decoding to reflect how many
+Decoding a SEQUENCE is similar to encoding.  You set up an array of \textbf{ltc\_asn1\_list} where in this case the \textit{size} member is the maximum size 
+(in certain cases).  For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the \textit{size} field is updated after successful decoding to reflect how many
 units of the respective type has been loaded.  
 
 \begin{verbatim}
-int der_decode_sequence(const unsigned char *in,   unsigned long  inlen,
-                              ltc_asn1_list *list, unsigned long  outlen);
-\end{verbatim}
-
-This will decode upto ``outlen'' items from the input buffer ``in'' of length ``inlen'' octets.  The function will stop (gracefully) when it runs out of items to decode.
-It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occured.
-
-For the following types the ``size'' field will be updated to reflect the number of units read of the given type.
+int der_decode_sequence(const unsigned char *in,
+                              unsigned long  inlen,
+                              ltc_asn1_list *list, 
+                              unsigned long  outlen);
+\end{verbatim}
+
+This will decode upto \textit{outlen} items from the input buffer \textit{in} of length \textit{inlen} octets.  The function will stop (gracefully) when it runs out of items to decode.
+It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occurred.
+
+For the following types the \textit{size} field will be updated to reflect the number of units read of the given type.
 \begin{enumerate}
    \item BIT STRING
    \item OCTET STRING
@@ -3444,11 +4304,12 @@
 
 \index{der\_length\_sequence()}
 \begin{verbatim}
-int der_length_sequence(ltc_asn1_list *list, unsigned long inlen,
+int der_length_sequence(ltc_asn1_list *list, 
+                        unsigned long  inlen,
                         unsigned long *outlen);
 \end{verbatim}
 
-This will get the encoding size for the given ``list'' of length ``inlen'' and store it in ``outlen''.  
+This will get the encoding size for the given \textit{list} of length \textit{inlen} and store it in \textit{outlen}.  
 
 \subsubsection{SEQUENCE Multiple Argument Lists}
 
@@ -3458,45 +4319,142 @@
 \index{der\_decode\_sequence\_multi()}
 
 \begin{verbatim}
-int der_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
-int der_decode_sequence_multi(const unsigned char *in, unsigned long inlen, ...);
+int der_encode_sequence_multi(unsigned char *out, 
+                              unsigned long *outlen, ...);
+
+int der_decode_sequence_multi(const unsigned char *in, 
+                                    unsigned long  inlen, ...);
 \end{verbatim}
 
 These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
 
-The list of items are specified as a triple of the form ``(type, size, data)''  where ``type'' is an \textbf{int}, ``size'' is a \textbf{unsigned long}
-and ``data'' is \textbf{void} pointer.  The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
-
-It's ideal that you cast the ``size'' values to unsigned long to ensure that the proper data type is passed to the function.  Constants such as ``1'' without
-a cast or prototype are of type \textbf{int} by default.  Appending \textit{UL} or prepending \textit{(unsigned long)} is enough to cast it to the correct type.
+The list of items are specified as a triple of the form \textit{(type, size, data)}  where \textit{type} is an \textbf{int}, \textit{size} is a \textbf{unsigned long}
+and \textit{data} is \textbf{void} pointer.  The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
+
+It is ideal that you cast the \textit{size} values to unsigned long to ensure that the proper data type is passed to the function.  Constants such as \textit{1} without
+a cast or prototype are of type \textbf{int} by default.  Appending \textit{UL} or pre-pending \textit{(unsigned long)} is enough to cast it to the correct type.
+
+\begin{small}
+\begin{verbatim}
+unsigned char buf[MAXBUFSIZE];
+unsigned long buflen;
+int           err;
+
+   buflen = sizeof(buf);
+   if ((err = 
+        der_encode_sequence_multi(buf, &buflen,
+        LTC_ASN1_IA5_STRING, 5UL, "Hello",
+        LTC_ASN1_IA5_STRING, 7UL, " World!",
+        LTC_ASN1_EOL,        0UL, NULL)) != CRYPT_OK) {
+      // error handling
+   }
+\end{verbatim}
+\end{small}
+
+This example encodes a SEQUENCE with two IA5 STRING types containing ``Hello'' and `` World!'' respectively.  Note the usage of the \textbf{UL} modifier
+on the size parameters.  This forces the compiler to pass the numbers as the required \textbf{unsigned long} type that the function expects.
+
+\subsection{SET and SET OF}
+
+\index{SET} \index{SET OF}
+SET and SET OF are related to the SEQUENCE type in that they can be pretty much be decoded with the same code.  However, they are different, and they should
+be carefully noted.  The SET type is an unordered array of ASN.1 types sorted by the TAG (type identifier), whereas the SET OF type is an ordered array of 
+a \textbf{single} ASN.1 object sorted in ascending order by the DER their respective encodings.
+
+\subsubsection{SET Encoding}
+
+SETs use the same array structure of ltc\_asn1\_list that the SEQUENCE functions use.  They are encoded with the following function:
+
+\index{der\_encode\_set()}
+\begin{verbatim}
+int der_encode_set(ltc_asn1_list *list, 
+                   unsigned long  inlen,
+                   unsigned char *out,  
+                   unsigned long *outlen);
+\end{verbatim}            
+
+This will encode the list of ASN.1 objects in \textit{list} of length \textit{inlen} objects, and store the output in \textit{out} of length \textit{outlen} bytes.  
+The function will make a copy of the list provided, and sort it by the TAG.  Objects with identical TAGs are additionally sorted on their original placement in the 
+array (to make the process deterministic).
+
+This function will \textbf{NOT} recognize \textit{DEFAULT} objects, and it is the responsibility of the caller to remove them as required.
+
+\subsubsection{SET Decoding}
+
+The SET type can be decoded with the following function.
+
+\index{der\_decode\_set()}
+\begin{verbatim}
+int der_decode_set(const unsigned char *in, 
+                         unsigned long  inlen,
+                         ltc_asn1_list *list, 
+                         unsigned long  outlen);
+\end{verbatim}
+
+This will decode the SET specified by \textit{list} of length \textit{outlen} objects from the input buffer \textit{in} of length \textit{inlen} octets.
+
+It handles the fact that SETs are not strictly ordered and will make multiple passes (as required) through the list to decode all the objects.  
+
+\subsubsection{SET Length}
+The length of a SET can be determined by calling der\_length\_sequence() since they have the same encoding length.
+
+\subsubsection{SET OF Encoding}
+A \textit{SET OF} object is an array of identical objects (e.g. OCTET STRING) sorted in ascending order by the DER encoding of the object.  They are 
+used to store objects deterministically based solely on their encoding.  It uses the same array structure of ltc\_asn1\_list that the SEQUENCE functions
+use.  They are encoded with the following function.
+
+\index{der\_encode\_setof()}
+\begin{verbatim}
+int der_encode_setof(ltc_asn1_list *list, 
+                     unsigned long  inlen,
+                     unsigned char *out,  
+                     unsigned long *outlen);
+\end{verbatim}
+
+This will encode a \textit{SET OF} containing the \textit{list} of \textit{inlen} ASN.1 objects and store the encoding in the output buffer \textit{out} of length \textit{outlen}.
+
+The routine will first encode the SET OF in an unordered fashion (in a temporary buffer) then sort using the XQSORT macro and copy back to the output buffer.  This
+means you need at least enough memory to keep an additional copy of the output on the heap.  
+
+\subsubsection{SET OF Decoding}
+Since the decoding of a \textit{SET OF} object is unambiguous it can be decoded with der\_decode\_sequence().  
+
+\subsubsection{SET OF Length}
+Like the SET type the der\_length\_sequence() function can be used to determine the length of a \textit{SET OF} object.
 
 \subsection{ASN.1 INTEGER}
 
 To encode or decode INTEGER data types use the following functions.
 
-\index{der\_encode\_integer()}
-\index{der\_decode\_integer()}
-\index{der\_length\_integer()}
-\begin{verbatim}
-int der_encode_integer(mp_int *num, unsigned char *out, unsigned long *outlen);
-int der_decode_integer(const unsigned char *in, unsigned long inlen, mp_int *num);
-int der_length_integer(mp_int *num, unsigned long *len);
-\end{verbatim}
-
-These will encode or decode a signed INTEGER data type using the ``mp\_int'' data type to store the large INTEGER.  To encode smaller values without allocating
-an mp\_int to store the value the ``short'' INTEGER functions were made available.
-
-\index{der\_encode\_short\_integer()}
-\index{der\_decode\_short\_integer()}
-\index{der\_length\_short\_integer()}
+\index{der\_encode\_integer()}\index{der\_decode\_integer()}\index{der\_length\_integer()}
+\begin{verbatim}
+int der_encode_integer(         void *num, 
+                       unsigned char *out, 
+                       unsigned long *outlen);
+
+int der_decode_integer(const unsigned char *in, 
+                             unsigned long  inlen, 
+                                      void *num);
+
+int der_length_integer(         void *num, 
+                       unsigned long *len);
+\end{verbatim}
+
+These will encode or decode a signed INTEGER data type using the bignum data type to store the large INTEGER.  To encode smaller values without allocating
+a bignum to store the value, the \textit{short} INTEGER functions were made available.
+
+\index{der\_encode\_short\_integer()}\index{der\_decode\_short\_integer()}\index{der\_length\_short\_integer()}
 \begin{verbatim}
 int der_encode_short_integer(unsigned long  num, 
-                             unsigned char *out, unsigned long *outlen);
-
-int der_decode_short_integer(const unsigned char *in,  unsigned long inlen, 
+                             unsigned char *out, 
+                             unsigned long *outlen);
+
+int der_decode_short_integer(const unsigned char *in,  
+                                   unsigned long  inlen, 
                                    unsigned long *num);
 
-int der_length_short_integer(unsigned long num, unsigned long *outlen);
+int der_length_short_integer(unsigned long  num, 
+                             unsigned long *outlen);
 \end{verbatim}
 
 These will encode or decode an unsigned \textbf{unsigned long} type (only reads upto 32--bits).  For values in the range $0 \dots 2^{32} - 1$ the integer 
@@ -3504,108 +4462,145 @@
 
 \subsection{ASN.1 BIT STRING}
 
-\index{der\_encode\_bit\_string()}
-\index{der\_decode\_bit\_string()}
-\index{der\_length\_bit\_string()}
-\begin{verbatim}
-int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
-                                unsigned char *out, unsigned long *outlen);
-
-int der_decode_bit_string(const unsigned char *in, unsigned long inlen,
-                                unsigned char *out, unsigned long *outlen);
-
-int der_length_bit_string(unsigned long nbits, unsigned long *outlen);
-\end{verbatim}
-
-These will encode or decode a BIT STRING data type.  The bits are passed in (or read out) using one \textbf{char} per bit.  A non--zero value will be interpretted
-as a one bit and a zero value a zero bit.
+\index{der\_encode\_bit\_string()}\index{der\_decode\_bit\_string()}\index{der\_length\_bit\_string()}
+\begin{verbatim}
+int der_encode_bit_string(const unsigned char *in, 
+                                unsigned long  inlen,
+                                unsigned char *out, 
+                                unsigned long *outlen);
+
+int der_decode_bit_string(const unsigned char *in, 
+                                unsigned long  inlen,
+                                unsigned char *out, 
+                                unsigned long *outlen);
+
+int der_length_bit_string(unsigned long  nbits, 
+                          unsigned long *outlen);
+\end{verbatim}
+
+These will encode or decode a BIT STRING data type.  The bits are passed in (or read out) using one \textbf{char} per bit.  A non--zero value will be interpreted
+as a one bit, and a zero value a zero bit.
 
 \subsection{ASN.1 OCTET STRING}
 
-\index{der\_encode\_octet\_string()}
-\index{der\_decode\_octet\_string()}
-\index{der\_length\_octet\_string()}
-\begin{verbatim}
-int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
-                                  unsigned char *out, unsigned long *outlen);
-
-int der_decode_octet_string(const unsigned char *in, unsigned long inlen,
-                                  unsigned char *out, unsigned long *outlen);
-
-int der_length_octet_string(unsigned long noctets, unsigned long *outlen);
-\end{verbatim}
-
-These will encode or decode an OCTET STRING data type.  The octets are stored using one \textbf{char} each.  
+\index{der\_encode\_octet\_string()}\index{der\_decode\_octet\_string()}\index{der\_length\_octet\_string()}
+\begin{verbatim}
+int der_encode_octet_string(const unsigned char *in, 
+                                  unsigned long  inlen,
+                                  unsigned char *out, 
+                                  unsigned long *outlen);
+
+int der_decode_octet_string(const unsigned char *in, 
+                                  unsigned long  inlen,
+                                  unsigned char *out, 
+                                  unsigned long *outlen);
+
+int der_length_octet_string(unsigned long  noctets, 
+                            unsigned long *outlen);
+\end{verbatim}
+
+These will encode or decode an OCTET STRING data type.  The octets are stored using one \textbf{unsigned char} each.  
 
 \subsection{ASN.1 OBJECT IDENTIFIER}
 
-\index{der\_encode\_object\_identifier()}
-\index{der\_decode\_object\_identifier()}
-\index{der\_length\_object\_identifier()}
-\begin{verbatim}
-int der_encode_object_identifier(unsigned long *words, unsigned long  nwords,
-                                 unsigned char *out,   unsigned long *outlen);
-
-int der_decode_object_identifier(const unsigned char *in,    unsigned long  inlen,
-                                       unsigned long *words, unsigned long *outlen);
-
-int der_length_object_identifier(unsigned long *words, unsigned long nwords, 
+\index{der\_encode\_object\_identifier()}\index{der\_decode\_object\_identifier()}\index{der\_length\_object\_identifier()}
+\begin{verbatim}
+int der_encode_object_identifier(unsigned long *words, 
+                                 unsigned long  nwords,
+                                 unsigned char *out, 
                                  unsigned long *outlen);
-\end{verbatim}
-
-These will encode or decode an OBJECT IDENTIFIER object.  The words of the OID are stored in individual \textbf{unsigned long} elements and must be in the range
+
+int der_decode_object_identifier(const unsigned char *in,
+                                       unsigned long  inlen,
+                                       unsigned long *words, 
+                                       unsigned long *outlen);
+
+int der_length_object_identifier(unsigned long *words, 
+                                 unsigned long  nwords, 
+                                 unsigned long *outlen);
+\end{verbatim}
+
+These will encode or decode an OBJECT IDENTIFIER object.  The words of the OID are stored in individual \textbf{unsigned long} elements, and must be in the range
 $0 \ldots 2^{32} - 1$.  
 
 \subsection{ASN.1 IA5 STRING}
 
-\index{der\_encode\_ia5\_string()}
-\index{der\_decode\_ia5\_string()}
-\index{der\_length\_ia5\_string()}
-\begin{verbatim}
-int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
-                                unsigned char *out, unsigned long *outlen);
-
-int der_decode_ia5_string(const unsigned char *in, unsigned long inlen,
-                                unsigned char *out, unsigned long *outlen);
-
-int der_length_ia5_string(const unsigned char *octets, unsigned long noctets, 
+\index{der\_encode\_ia5\_string()}\index{der\_decode\_ia5\_string()}\index{der\_length\_ia5\_string()}
+\begin{verbatim}
+int der_encode_ia5_string(const unsigned char *in, 
+                                unsigned long  inlen,
+                                unsigned char *out, 
+                                unsigned long *outlen);
+
+int der_decode_ia5_string(const unsigned char *in, 
+                                unsigned long  inlen,
+                                unsigned char *out, 
                                 unsigned long *outlen);
-\end{verbatim}
-
-These will encode or decode an IA5 STRING.  The characters are read or stored in individual \textbf{char} elements.  This functions performs internal character
+
+int der_length_ia5_string(const unsigned char *octets, 
+                                unsigned long  noctets, 
+                                unsigned long *outlen);
+\end{verbatim}
+
+These will encode or decode an IA5 STRING.  The characters are read or stored in individual \textbf{char} elements.  These functions performs internal character
 to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on 
-say a SPARC machine.  Internally these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
-that the build platform honours the runtime platforms character conventions.
-
-If you're worried try building the test suite and running it.  It has hard coded test vectors to ensure it is operating properly. 
+say a SPARC machine.  Internally, these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
+that the build platform honours the run--time platforms character conventions.
 
 \subsection{ASN.1 PRINTABLE STRING}
 
-\index{der\_encode\_printable\_string()}
-\index{der\_decode\_printable\_string()}
-\index{der\_length\_printable\_string()}
-\begin{verbatim}
-int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
-                                unsigned char *out, unsigned long *outlen);
-
-int der_decode_printable_string(const unsigned char *in, unsigned long inlen,
-                                unsigned char *out, unsigned long *outlen);
-
-int der_length_printable_string(const unsigned char *octets, unsigned long noctets, 
-                                unsigned long *outlen);
-\end{verbatim}
-
-These will encode or decode an PRINTABLE STRING.  The characters are read or stored in individual \textbf{char} elements.  This functions performs internal character
+\index{der\_encode\_printable\_string()}\index{der\_decode\_printable\_string()}\index{der\_length\_printable\_string()}
+\begin{verbatim}
+int der_encode_printable_string(const unsigned char *in, 
+                                      unsigned long  inlen,
+                                      unsigned char *out, 
+                                      unsigned long *outlen);
+
+int der_decode_printable_string(const unsigned char *in, 
+                                      unsigned long  inlen,
+                                      unsigned char *out, 
+                                      unsigned long *outlen);
+
+int der_length_printable_string(const unsigned char *octets, 
+                                      unsigned long  noctets, 
+                                      unsigned long *outlen);
+\end{verbatim}
+
+These will encode or decode an PRINTABLE STRING.  The characters are read or stored in individual \textbf{char} elements.  These functions performs internal character
 to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on 
-say a SPARC machine.  Internally these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
-that the build platform honours the runtime platforms character conventions.
-
-If you're worried try building the test suite and running it.  It has hard coded test vectors to ensure it is operating properly. 
+say a SPARC machine.  Internally, these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
+that the build platform honours the run-time platforms character conventions.
+
+\subsection{ASN.1 UTF8 STRING}
+
+\index{der\_encode\_utf8\_string()}\index{der\_decode\_utf8\_string()}\index{der\_length\_utf8\_string()}
+\begin{verbatim}
+int der_encode_utf8_string(const wchar_t *in, 
+                           unsigned long  inlen,
+                           unsigned char *out, 
+                           unsigned long *outlen);
+
+int der_decode_utf8_string(const unsigned char *in, 
+                                 unsigned long  inlen,
+                                       wchar_t *out, 
+                                 unsigned long *outlen);
+
+int der_length_utf8_string(const wchar_t *octets, 
+                           unsigned long  noctets, 
+                           unsigned long *outlen);
+\end{verbatim}
+
+These will encode or decode an UTF8 STRING.  The characters are read or stored in individual \textbf{wchar\_t} elements.  These function performs no internal
+mapping and treat the characters as literals.  
+
+These functions use the \textbf{wchar\_t} type which is not universally available.  In those cases, the library will typedef it to \textbf{unsigned long}.  If you 
+intend to use the ISO C functions for working with wide--char arrays, you should make sure that wchar\_t has been defined previously.
 
 \subsection{ASN.1 UTCTIME}
 
 The UTCTIME type is to store a date and time in ASN.1 format.  It uses the following structure to organize the time.
 
+\index{ltc\_utctime structure}
 \begin{verbatim}
 typedef struct {
    unsigned YY, /* year    00--99 */
@@ -3620,32 +4615,32 @@
 } ltc_utctime;
 \end{verbatim}
 
-The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm).  When ``off\_dir'' is zero the time will be added otherwise it 
-will be subtracted.  
-
-For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of 2005, June 20th, 22:04:00 with a time offset of +05h00.  
-
-\index{der\_encode\_utctime()}
-\index{der\_decode\_utctime()}
-\index{der\_length\_utctime()}
-\begin{verbatim}
-int der_encode_utctime(ltc_utctime *utctime, 
-                       unsigned char *out,   unsigned long *outlen);
-
-int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
-                             ltc_utctime   *out);
-
-int der_length_utctime(ltc_utctime *utctime, unsigned long *outlen);
-\end{verbatim}
-
-The encoder will store time in one of the two ASN.1 formats, either ``YYMMDDhhmmssZ'' or ``YYMMDDhhmmss$\pm$hhmm'' and perform minimal error checking on the 
+The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm).  When \textit{off\_dir} is zero, the time will be added otherwise it 
+will be subtracted.  For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of 
+\textit{2005, June 20th, 22:04:00} with a time offset of +05h00.  
+
+\index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
+\begin{verbatim}
+int der_encode_utctime(  ltc_utctime *utctime, 
+                       unsigned char *out,   
+                       unsigned long *outlen);
+
+int der_decode_utctime(const unsigned char *in, 
+                             unsigned long *inlen,
+                               ltc_utctime *out);
+
+int der_length_utctime(  ltc_utctime *utctime, 
+                       unsigned long *outlen);
+\end{verbatim}
+
+The encoder will store time in one of the two ASN.1 formats, either \textit{YYMMDDhhmmssZ} or \textit{YYMMDDhhmmss$\pm$hhmm}, and perform minimal error checking on the 
 input.  The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
 
 It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
 
 \subsection{ASN.1 CHOICE}
 
-The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a ``ltc\_asn1\_list''.  There is no encoder for the CHOICE type, only a 
+The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a \textit{ltc\_asn1\_list}.  There is no encoder for the CHOICE type, only a 
 decoder.  The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet.  The list can contain any ASN.1 data
 type\footnote{Except it cannot have LTC\_ASN1\_INTEGER and LTC\_ASN1\_SHORT\_INTEGER simultaneously.} except for other CHOICE types.  
 
@@ -3653,15 +4648,119 @@
 
 \index{der\_decode\_choice()}
 \begin{verbatim}
-int der_decode_choice(const unsigned char *in,   unsigned long *inlen,
-                            ltc_asn1_list *list, unsigned long  outlen);
-\end{verbatim}
-
-This will decode the input in the ``in'' field of length ``inlen''.  It uses the provided ASN.1 list specified in the ``list'' field which has ``outlen'' elements.  
-The ``inlen'' field will be updated with the length of the decoded data type as well as the respective entry in the ``list'' field will have the ``used'' flag 
-set to non--zero to reflect it was the data type decoded.
-
-\section{Password Based Cryptography}
+int der_decode_choice(const unsigned char *in, 
+                            unsigned long *inlen,
+                            ltc_asn1_list *list, 
+                            unsigned long  outlen);
+\end{verbatim}
+
+This will decode the input in the \textit{in} field of length \textit{inlen}.  It uses the provided ASN.1 list specified in the \textit{list} field which has 
+\textit{outlen} elements.  The \textit{inlen} field will be updated with the length of the decoded data type, as well as the respective entry in the \textit{list} field 
+will have the \textit{used} flag set to non--zero to reflect it was the data type decoded.
+
+\subsection{ASN.1 Flexi Decoder}
+The ASN.1 \textit{flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets (provided they use data types LibTomCrypt supports) without first knowing
+the structure of the data.  Where der\_decode \_sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely
+free form.
+
+The flexi decoder uses the same \textit{ltc\_asn1\_list} but instead of being stored in an array it uses the linked list pointers \textit{prev}, \textit{next}, \textit{parent} 
+and \textit{child}.  The list works as a \textit{doubly-linked list} structure where decoded items at the same level are siblings (using next and prev) and items
+encoded in a SEQUENCE are stored as a child element.