changeset 435:337c45621e81

merge of 'a9b0496634cdd25647b65e585cc3240f3fa699ee' and 'c22be8b8f570b48e9662dac32c7b3e7148a42206'
author Matt Johnston <matt@ucc.asn.au>
date Thu, 22 Feb 2007 14:53:49 +0000
parents 0aaaf68e97dc (current diff) c216212001fc (diff)
children 7282370416a0
files libtomcrypt/src/headers/ltc_tommath.h libtomcrypt/src/headers/tommath_class.h libtomcrypt/src/headers/tommath_superclass.h libtomcrypt/src/misc/mpi/is_prime.c libtomcrypt/src/misc/mpi/mpi_to_ltc_error.c libtomcrypt/src/misc/mpi/rand_prime.c libtomcrypt/src/pk/asn1/der/sequence/der_decode_sequence.c libtomcrypt/src/pk/asn1/der/sequence/der_encode_sequence.c libtomcrypt/src/pk/dh/dh.c libtomcrypt/src/pk/dh/dh_sys.c libtomcrypt/src/pk/ecc/ecc_sys.c libtomcrypt/src/pk/packet_store_header.c libtomcrypt/src/pk/packet_valid_header.c libtomcrypt/testprof/dh_tests.c libtomcrypt/testprof/test.c libtommath/TODO libtommath/logs/sqr.old options.h runopts.h svr-main.c svr-runopts.c
diffstat 579 files changed, 29318 insertions(+), 12231 deletions(-) [+]
line wrap: on
line diff
--- a/CHANGES	Thu Feb 22 14:52:46 2007 +0000
+++ b/CHANGES	Thu Feb 22 14:53:49 2007 +0000
@@ -1,3 +1,55 @@
+0.49test1 - Mon 12 February 2007
+
+- 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"
+
+- 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
+
 0.48 - Thurs 9 March 2006
 
 - Check that the circular buffer is properly empty before
--- a/LICENSE	Thu Feb 22 14:52:46 2007 +0000
+++ b/LICENSE	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/Makefile.in	Thu Feb 22 14:53:49 2007 +0000
@@ -64,12 +64,12 @@
 sbindir=${exec_prefix}/sbin
 
 [email protected]@
[email protected]@
 [email protected]@
 [email protected]@
 [email protected]@
 [email protected]@
-CFLAGS=-I. -I$(srcdir)/libtomcrypt/src/headers/ @[email protected]
[email protected]@
+CFLAGS=-I. -I$(srcdir) -I$(srcdir)/libtomcrypt/src/headers/ $(CPPFLAGS) @[email protected]
 LIBS=$(LTC) $(LTM) @[email protected]
 [email protected]@
 
@@ -155,11 +155,11 @@
 
 dropbear dbclient dropbearkey dropbearconvert: $(HEADERS)  $(LTC) $(LTM) \
 													Makefile
-	$(LD) $(LDFLAGS) -o [email protected]$(EXEEXT) $([email protected]) $(LIBS)
+	$(CC) $(LDFLAGS) -o [email protected]$(EXEEXT) $([email protected]) $(LIBS)
 
 # scp doesn't use the libs so is special.
 scp: $(SCPOBJS)  $(HEADERS) Makefile
-	$(LD) $(LDFLAGS) -o [email protected]$(EXEEXT) $(SCPOBJS)
+	$(CC) $(LDFLAGS) -o [email protected]$(EXEEXT) $(SCPOBJS)
 
 
 # multi-binary compilation.
@@ -172,7 +172,7 @@
 dropbearmulti: multilink 
 
 multibinary: $(HEADERS) $(MULTIOBJS) $(LTC) $(LTM) Makefile
-	$(LD) $(LDFLAGS) -o dropbearmulti$(EXEEXT) $(MULTIOBJS) $(LIBS)
+	$(CC) $(LDFLAGS) -o dropbearmulti$(EXEEXT) $(MULTIOBJS) $(LIBS)
 
 multilink: multibinary $(addprefix link, $(PROGRAMS))
 
@@ -186,6 +186,8 @@
 $(LTM): options.h
 	cd libtommath && $(MAKE)
 
+.PHONY : clean sizes thisclean distclean tidy ltc-clean ltm-clean
+
 ltc-clean:
 	cd libtomcrypt && $(MAKE) clean
 
--- a/auth.h	Thu Feb 22 14:52:46 2007 +0000
+++ b/auth.h	Thu Feb 22 14:53:49 2007 +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 */
--- a/channel.h	Thu Feb 22 14:52:46 2007 +0000
+++ b/channel.h	Thu Feb 22 14:53:49 2007 +0000
@@ -73,10 +73,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 +84,8 @@
 					   for this channel (and are awaiting a confirmation
 					   or failure). */
 
+	int flushing;
+
 	const struct ChanType* type;
 
 };
@@ -94,7 +95,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	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-auth.c	Thu Feb 22 14:53:49 2007 +0000
@@ -236,8 +236,8 @@
 
 void cli_auth_try() {
 
+	int finished = 0;
 	TRACE(("enter cli_auth_try"))
-	int finished = 0;
 
 	CHECKCLEARTOWRITE();
 	
@@ -281,11 +281,11 @@
 
 /* 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;
 
-	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	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-authinteract.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-authpasswd.c	Thu Feb 22 14:53:49 2007 +0000
@@ -116,16 +116,19 @@
 void cli_auth_password() {
 
 	char* password = NULL;
+	char prompt[80];
 
 	TRACE(("enter cli_auth_password"))
 	CHECKCLEARTOWRITE();
 
+	snprintf(prompt, sizeof(prompt), "%[email protected]%s's password: ", 
+				cli_opts.username, cli_opts.remotehost);
 #ifdef ENABLE_CLI_ASKPASS_HELPER
 	if (want_askpass())
-		password = gui_getpass("Password: ");
+		password = gui_getpass(prompt);
 	else
 #endif
-		password = getpass_or_cancel("Password: ");
+		password = getpass_or_cancel(prompt);
 
 	buf_putbyte(ses.writepayload, SSH_MSG_USERAUTH_REQUEST);
 
--- a/cli-authpubkey.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-authpubkey.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-channel.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-chansession.c	Thu Feb 22 14:53:49 2007 +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 */
--- a/cli-kex.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-kex.c	Thu Feb 22 14:53:49 2007 +0000
@@ -119,9 +119,17 @@
 	char response = 'z';
 
 	fp = sign_key_fingerprint(keyblob, keybloblen);
+	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)\n", 
 			cli_opts.remotehost, 
 			fp);
+	m_free(fp);
 
 	tty = fopen(_PATH_TTY, "r");
 	if (tty) {
@@ -132,7 +140,6 @@
 	}
 
 	if (response == 'y') {
-		m_free(fp);
 		return;
 	}
 
@@ -145,49 +152,59 @@
 	FILE *hostsfile = NULL;
 	int readonly = 0;
 	struct passwd *pw = NULL;
+	char * homedir = NULL;
 	unsigned int hostlen, algolen;
 	unsigned long len;
 	const char *algoname = NULL;
 	buffer * line = NULL;
 	int ret;
 	
-	pw = getpwuid(getuid());
+	homedir = getenv("HOME");
 
-	if (pw == NULL) {
-		dropbear_exit("Failed to get homedir");
+	if (!homedir) {
+		pw = getpwuid(getuid());
+		if (pw) {
+			homedir = pw->pw_dir;
+		}
+		pw = NULL;
 	}
 
-	len = strlen(pw->pw_dir);
-	filename = m_malloc(len + 18); /* "/.ssh/known_hosts" and null-terminator*/
+	if (homedir) {
+
+		len = strlen(homedir);
+		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 */
+		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)))
+				ask_to_confirm(keyblob, keybloblen);
+				goto out; /* only get here on success */
+			}
 		}
-	}
 
-	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");
+		snprintf(filename, len+18, "%s/.ssh/known_hosts", homedir);
+		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 (hostsfile == NULL) {
 		TRACE(("hostsfile didn't open: %s", strerror(errno)))
+		dropbear_log(LOG_WARNING, "Failed to open %s/.ssh/known_hosts",
+				homedir);
 		ask_to_confirm(keyblob, keybloblen);
 		goto out; /* We only get here on success */
 	}
@@ -258,24 +275,26 @@
 		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) {
--- a/cli-main.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-main.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-runopts.c	Thu Feb 22 14:53:49 2007 +0000
@@ -44,12 +44,15 @@
 static void printhelp() {
 
 	fprintf(stderr, "Dropbear client v%s\n"
-					"Usage: %s [options] [[email protected]]host\n"
+					"Usage: %s [options] [[email protected]]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
@@ -88,7 +91,10 @@
 	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
@@ -144,6 +150,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 +172,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;
@@ -269,6 +284,11 @@
 			cli_opts.wantpty = 0;
 		}
 	}
+
+	if (cli_opts.backgrounded && cli_opts.cmd == NULL
+			&& cli_opts.no_cmd == 0) {
+		dropbear_exit("command required for -f");
+	}
 }
 
 #ifdef ENABLE_CLI_PUBKEY_AUTH
@@ -348,7 +368,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 +379,7 @@
 		TRACE(("connectaddr == NULL"))
 		goto fail;
 	}
-
-	connectaddr[0] = '\0';
+	*connectaddr = '\0';
 	connectaddr++;
 
 	connectport = strchr(connectaddr, ':');
@@ -367,8 +387,7 @@
 		TRACE(("connectport == NULL"))
 		goto fail;
 	}
-
-	connectport[0] = '\0';
+	*connectport = '\0';
 	connectport++;
 
 	newfwd = (struct TCPFwdList*)m_malloc(sizeof(struct TCPFwdList));
--- a/cli-service.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-service.c	Thu Feb 22 14:53:49 2007 +0000
@@ -82,6 +82,4 @@
 	}
 
 	dropbear_exit("unrecognised service accept");
-	/* m_free(servicename); not reached */
-
 }
--- a/cli-session.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/cli-session.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/common-algo.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/common-channel.c	Thu Feb 22 14:53:49 2007 +0000
@@ -43,22 +43,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 +85,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 +135,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,6 +148,7 @@
 	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->extrabuf = NULL; /* The user code can set it up */
@@ -164,25 +165,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 +204,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 +244,114 @@
 }
 
 
-/* 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) {
+
+	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 (channel->recv_close && !write_pending(channel)) {
+		if (!channel->sent_close) {
+			TRACE(("Sending MSG_CHANNEL_CLOSE in response to same."))
+			send_msg_channel_close(channel);
 		}
+		remove_channel(channel);
+		return;
+	}
 
-		if (!channel->senteof
-			&& channel->readfd == FD_CLOSED 
-			&& (channel->extrabuf != NULL || channel->errfd == FD_CLOSED)) {
-			send_msg_channel_eof(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 (channel->writefd == FD_CLOSED
-			&& channel->readfd == FD_CLOSED
-			&& (channel->extrabuf != NULL || channel->errfd == FD_CLOSED)) {
-			send_msg_channel_close(channel);
+		if (ERRFD_IS_READ(channel) && channel->readfd >= 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->sent_close
+			&& channel->readfd == FD_CLOSED
+			&& (ERRFD_IS_WRITE(channel) || channel->errfd == FD_CLOSED)
+			&& !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 +363,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 +382,7 @@
 
 	encrypt_packet();
 
-	channel->senteof = 1;
+	channel->sent_eof = 1;
 
 	TRACE(("leave send_msg_channel_eof"))
 }
@@ -357,32 +394,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 */
@@ -396,7 +426,6 @@
 	dropbear_assert(channel->extrabuf == NULL ||
 			channel->recvwindow <= cbuf_getavail(channel->extrabuf));
 	
-	
 	TRACE(("leave writechannel"))
 }
 
@@ -421,7 +450,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 +458,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 +483,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 +499,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 +525,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 +559,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 +575,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 +599,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 +654,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 +670,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);
 
@@ -706,9 +724,6 @@
 	unsigned int incr;
 	
 	channel = getchannel();
-	if (channel == NULL) {
-		dropbear_exit("Unknown channel");
-	}
 	
 	incr = buf_getint(ses.payload);
 	TRACE(("received window increment %d", incr))
@@ -735,7 +750,6 @@
 }
 	
 /* Handle a new channel request, performing any channel-type-specific setup */
-/* XXX server */
 void recv_msg_channel_open() {
 
 	unsigned char *type;
@@ -792,13 +806,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 +896,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
@@ -930,9 +987,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 +1004,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 +1019,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	Thu Feb 22 14:52:46 2007 +0000
+++ b/common-kex.c	Thu Feb 22 14:53:49 2007 +0000
@@ -217,12 +217,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 +260,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 +297,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 +519,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	Thu Feb 22 14:52:46 2007 +0000
+++ b/common-session.c	Thu Feb 22 14:53:49 2007 +0000
@@ -61,6 +61,12 @@
 
 	ses.connecttimeout = 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);
@@ -108,7 +114,6 @@
 
 	ses.allowprivport = 0;
 
-
 	TRACE(("leave session_init"))
 }
 
@@ -132,6 +137,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 +152,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) {
@@ -229,7 +240,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 +261,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);
--- a/config.guess	Thu Feb 22 14:52:46 2007 +0000
+++ b/config.guess	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/config.sub	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/configure.in	Thu Feb 22 14:53:49 2007 +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,57 @@
 	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/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/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	Thu Feb 22 14:52:46 2007 +0000
+++ b/dbclient.1	Thu Feb 22 14:53:49 2007 +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,6 +59,13 @@
 .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
--- a/dbutil.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/dbutil.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/dbutil.h	Thu Feb 22 14:53:49 2007 +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/changelog	Thu Feb 22 14:52:46 2007 +0000
+++ b/debian/changelog	Thu Feb 22 14:53:49 2007 +0000
@@ -1,14 +1,38 @@
-dropbear (0.48-0.1) unstable; urgency=high
+dropbear (0.49test1-0.1) unstable; urgency=low
 
   * New upstream release.
-  * SECURITY: Improve handling of denial of service attempts from a single IP.
+
+ -- Matt Johnston <[email protected]>  Mon, 12 Feb 2007 23:59:00 +0900
+
+dropbear (0.48.1-1) unstable; urgency=medium
 
- -- Matt Johnston <[email protected]>  Thu, 8 Mar 2006 19:20:21 +0800
+  * 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)..
 
-dropbear (0.47-0.1) unstable; urgency=high
+ -- 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/dropbear.README.Debian	Thu Feb 22 14:52:46 2007 +0000
+++ b/debian/dropbear.README.Debian	Thu Feb 22 14:53:49 2007 +0000
@@ -39,3 +39,14 @@
 See the Dropbear homepage for more information:
   http://matt.ucc.asn.au/dropbear/dropbear.html
 
+
+Entropy from /dev/random
+------------------------
+
+The dropbear binary package is configured at compile time to read
+entropy from /dev/random. If /dev/random on a system blocks when
+reading data from it, client logins may be delayed until the client
+times out. The dropbear server writes a notice to the logs when it
+sees /dev/random blocking.  A workaround for such systems is to
+re-compile the package with DROPBEAR_RANDOM_DEV set to /dev/urandom
+in options.h.
--- a/debian/implicit	Thu Feb 22 14:52:46 2007 +0000
+++ b/debian/implicit	Thu Feb 22 14:53:49 2007 +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/debug.h	Thu Feb 22 14:52:46 2007 +0000
+++ b/debug.h	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/dropbear.8	Thu Feb 22 14:53:49 2007 +0000
@@ -72,6 +72,10 @@
 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.
 .SH AUTHOR
--- a/dropbearkey.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/dropbearkey.c	Thu Feb 22 14:53:49 2007 +0000
@@ -283,8 +283,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 +299,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 +320,18 @@
 
 	fp = sign_key_fingerprint(buf_getptr(buf, len), len);
 
-	printf("Public key portion is:\n%s %s\nFingerprint: %s\n",
-			typestring, base64key, fp);
+	/* a [email protected] comment is informative */
+	username = "";
+	pw = getpwuid(getuid());
+	if (pw) {
+		username = pw->pw_name;
+	}
+
+	gethostname(hostname, sizeof(hostname));
+	hostname[sizeof(hostname)-1] = '\0';
+
+	printf("Public key portion is:\n%s %s %[email protected]%s\nFingerprint: %s\n",
+			typestring, base64key, username, hostname, fp);
 
 	m_free(fp);
 	buf_free(buf);
--- a/dss.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/dss.c	Thu Feb 22 14:53:49 2007 +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/includes.h	Thu Feb 22 14:52:46 2007 +0000
+++ b/includes.h	Thu Feb 22 14:53:49 2007 +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>
@@ -72,12 +73,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 +136,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/keyimport.c	Thu Feb 22 14:52:46 2007 +0000
+++ b/keyimport.c	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/libtomcrypt/Doxyfile	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/libtomcrypt/Makefile.in	Thu Feb 22 14:53:49 2007 +0000
@@ -4,7 +4,7 @@
 # Modified by Clay Culver
 
 # The version
-VERSION=1.05
+VERSION=1.16
 
 [email protected]@
 [email protected]@
@@ -22,8 +22,12 @@
 CFLAGS += -c -I$(srcdir)/src/headers/ -I$(srcdir)/../
 
 # additional warnings (newer GCC 3.4 and higher)
-#CFLAGS += -Wsystem-headers -Wdeclaration-after-statement -Wbad-function-cast -Wcast-align -Wstrict-prototypes -Wmissing-prototypes \
-#		  -Wmissing-declarations -Wpointer-arith 
+ifdef GCC_34
+CFLAGS += -Wsystem-headers -Wdeclaration-after-statement -Wbad-function-cast -Wcast-align -Wstrict-prototypes -Wmissing-prototypes \
+		  -Wmissing-declarations -Wpointer-arith 
+endif
+
+ifndef IGNORE_SPEED
 
 # optimize for SPEED
 #CFLAGS += -O3 -funroll-loops
@@ -34,6 +38,8 @@
 # optimize for SIZE
 #CFLAGS += -Os -DLTC_SMALL_CODE
 
+endif
+
 # older GCCs can't handle the "rotate with immediate" ROLc/RORc/etc macros
 # define this to help
 #CFLAGS += -DLTC_NO_ROLC
@@ -42,8 +48,14 @@
 #CFLAGS += -g3 -DLTC_NO_ASM
 
 #Output filenames for various targets.
-LIBNAME=libtomcrypt.a
-LIBTEST=testprof/libtomcrypt_prof.a
+ifndef LIBNAME
+   LIBNAME=libtomcrypt.a
+endif
+ifndef LIBTEST
+   LIBTEST=libtomcrypt_prof.a
+endif
+LIBTEST_S=$(LIBTEST)
+
 HASH=hashsum
 CRYPT=encrypt
 SMALL=small
@@ -56,10 +68,19 @@
 #LIBPATH-The directory for libtomcrypt to be installed to.
 #INCPATH-The directory to install the header files for libtomcrypt.
 #DATAPATH-The directory to install the pdf docs.
-DESTDIR=
-LIBPATH=/usr/lib
-INCPATH=/usr/include
-DATAPATH=/usr/share/doc/libtomcrypt/pdf
+ifndef DESTDIR
+   DESTDIR=
+endif
+
+ifndef LIBPATH
+   LIBPATH=/usr/lib
+endif
+ifndef INCPATH
+   INCPATH=/usr/include
+endif
+ifndef DATAPATH
+   DATAPATH=/usr/share/doc/libtomcrypt/pdf
+endif
 
 #Who do we install as?
 ifdef INSTALL_USER
@@ -75,15 +96,10 @@
 endif
 
 #List of objects to compile.
-
-#Leave MPI built-in or force developer to link against libtommath?
-#MPIOBJECT=src/misc/mpi/mpi.o
-#Dropbear uses libtommath
-MPIOBJECT=
-
-OBJECTS=src/ciphers/aes/aes_enc.o $(MPIOBJECT) src/ciphers/aes/aes.o src/ciphers/anubis.o \
-src/ciphers/blowfish.o src/ciphers/cast5.o src/ciphers/des.o src/ciphers/khazad.o src/ciphers/noekeon.o \
-src/ciphers/rc2.o src/ciphers/rc5.o src/ciphers/rc6.o src/ciphers/safer/safer.o \
+#START_INS
+OBJECTS=src/ciphers/aes/aes_enc.o src/ciphers/aes/aes.o src/ciphers/anubis.o src/ciphers/blowfish.o \
+src/ciphers/cast5.o src/ciphers/des.o src/ciphers/kasumi.o src/ciphers/khazad.o src/ciphers/kseed.o \
+src/ciphers/noekeon.o src/ciphers/rc2.o src/ciphers/rc5.o src/ciphers/rc6.o src/ciphers/safer/safer.o \
 src/ciphers/safer/safer_tab.o src/ciphers/safer/saferp.o src/ciphers/skipjack.o \
 src/ciphers/twofish/twofish.o src/ciphers/xtea.o src/encauth/ccm/ccm_memory.o \
 src/encauth/ccm/ccm_test.o src/encauth/eax/eax_addheader.o src/encauth/eax/eax_decrypt.o \
@@ -91,52 +107,65 @@
 src/encauth/eax/eax_encrypt_authenticate_memory.o src/encauth/eax/eax_init.o \
 src/encauth/eax/eax_test.o src/encauth/gcm/gcm_add_aad.o src/encauth/gcm/gcm_add_iv.o \
 src/encauth/gcm/gcm_done.o src/encauth/gcm/gcm_gf_mult.o src/encauth/gcm/gcm_init.o \
-src/encauth/gcm/gcm_memory.o src/encauth/gcm/gcm_process.o src/encauth/gcm/gcm_reset.o \
-src/encauth/gcm/gcm_test.o src/encauth/ocb/ocb_decrypt.o src/encauth/ocb/ocb_decrypt_verify_memory.o \
-src/encauth/ocb/ocb_done_decrypt.o src/encauth/ocb/ocb_done_encrypt.o src/encauth/ocb/ocb_encrypt.o \
+src/encauth/gcm/gcm_memory.o src/encauth/gcm/gcm_mult_h.o src/encauth/gcm/gcm_process.o \
+src/encauth/gcm/gcm_reset.o src/encauth/gcm/gcm_test.o src/encauth/ocb/ocb_decrypt.o \
+src/encauth/ocb/ocb_decrypt_verify_memory.o src/encauth/ocb/ocb_done_decrypt.o \
+src/encauth/ocb/ocb_done_encrypt.o src/encauth/ocb/ocb_encrypt.o \
 src/encauth/ocb/ocb_encrypt_authenticate_memory.o src/encauth/ocb/ocb_init.o src/encauth/ocb/ocb_ntz.o \
 src/encauth/ocb/ocb_shift_xor.o src/encauth/ocb/ocb_test.o src/encauth/ocb/s_ocb_done.o \
 src/hashes/chc/chc.o src/hashes/helper/hash_file.o src/hashes/helper/hash_filehandle.o \
 src/hashes/helper/hash_memory.o src/hashes/helper/hash_memory_multi.o src/hashes/md2.o src/hashes/md4.o \
-src/hashes/md5.o src/hashes/rmd128.o src/hashes/rmd160.o src/hashes/sha1.o src/hashes/sha2/sha256.o \
-src/hashes/sha2/sha512.o src/hashes/tiger.o src/hashes/whirl/whirl.o src/mac/hmac/hmac_done.o \
-src/mac/hmac/hmac_file.o src/mac/hmac/hmac_init.o src/mac/hmac/hmac_memory.o \
+src/hashes/md5.o src/hashes/rmd128.o src/hashes/rmd160.o src/hashes/rmd256.o src/hashes/rmd320.o \
+src/hashes/sha1.o src/hashes/sha2/sha256.o src/hashes/sha2/sha512.o src/hashes/tiger.o \
+src/hashes/whirl/whirl.o src/mac/f9/f9_done.o src/mac/f9/f9_file.o src/mac/f9/f9_init.o \
+src/mac/f9/f9_memory.o src/mac/f9/f9_memory_multi.o src/mac/f9/f9_process.o src/mac/f9/f9_test.o \
+src/mac/hmac/hmac_done.o src/mac/hmac/hmac_file.o src/mac/hmac/hmac_init.o src/mac/hmac/hmac_memory.o \
 src/mac/hmac/hmac_memory_multi.o src/mac/hmac/hmac_process.o src/mac/hmac/hmac_test.o \
 src/mac/omac/omac_done.o src/mac/omac/omac_file.o src/mac/omac/omac_init.o src/mac/omac/omac_memory.o \
 src/mac/omac/omac_memory_multi.o src/mac/omac/omac_process.o src/mac/omac/omac_test.o \
 src/mac/pelican/pelican.o src/mac/pelican/pelican_memory.o src/mac/pelican/pelican_test.o \
 src/mac/pmac/pmac_done.o src/mac/pmac/pmac_file.o src/mac/pmac/pmac_init.o src/mac/pmac/pmac_memory.o \
 src/mac/pmac/pmac_memory_multi.o src/mac/pmac/pmac_ntz.o src/mac/pmac/pmac_process.o \
-src/mac/pmac/pmac_shift_xor.o src/mac/pmac/pmac_test.o src/misc/base64/base64_decode.o \
+src/mac/pmac/pmac_shift_xor.o src/mac/pmac/pmac_test.o src/mac/xcbc/xcbc_done.o \
+src/mac/xcbc/xcbc_file.o src/mac/xcbc/xcbc_init.o src/mac/xcbc/xcbc_memory.o \
+src/mac/xcbc/xcbc_memory_multi.o src/mac/xcbc/xcbc_process.o src/mac/xcbc/xcbc_test.o \
+src/math/fp/ltc_ecc_fp_mulmod.o src/math/gmp_desc.o src/math/ltm_desc.o src/math/multi.o \
+src/math/rand_prime.o src/math/tfm_desc.o src/misc/base64/base64_decode.o \
 src/misc/base64/base64_encode.o src/misc/burn_stack.o src/misc/crypt/crypt.o \
 src/misc/crypt/crypt_argchk.o src/misc/crypt/crypt_cipher_descriptor.o \
 src/misc/crypt/crypt_cipher_is_valid.o src/misc/crypt/crypt_find_cipher.o \
 src/misc/crypt/crypt_find_cipher_any.o src/misc/crypt/crypt_find_cipher_id.o \
 src/misc/crypt/crypt_find_hash.o src/misc/crypt/crypt_find_hash_any.o \
-src/misc/crypt/crypt_find_hash_id.o src/misc/crypt/crypt_find_prng.o \
-src/misc/crypt/crypt_hash_descriptor.o src/misc/crypt/crypt_hash_is_valid.o \
+src/misc/crypt/crypt_find_hash_id.o src/misc/crypt/crypt_find_hash_oid.o \
+src/misc/crypt/crypt_find_prng.o src/misc/crypt/crypt_fsa.o src/misc/crypt/crypt_hash_descriptor.o \
+src/misc/crypt/crypt_hash_is_valid.o src/misc/crypt/crypt_ltc_mp_descriptor.o \
 src/misc/crypt/crypt_prng_descriptor.o src/misc/crypt/crypt_prng_is_valid.o \
 src/misc/crypt/crypt_register_cipher.o src/misc/crypt/crypt_register_hash.o \
 src/misc/crypt/crypt_register_prng.o src/misc/crypt/crypt_unregister_cipher.o \
 src/misc/crypt/crypt_unregister_hash.o src/misc/crypt/crypt_unregister_prng.o \
-src/misc/error_to_string.o src/misc/mpi/is_prime.o src/misc/mpi/mpi_to_ltc_error.o \
-src/misc/mpi/rand_prime.o src/misc/pkcs5/pkcs_5_1.o src/misc/pkcs5/pkcs_5_2.o src/misc/zeromem.o \
+src/misc/error_to_string.o src/misc/pkcs5/pkcs_5_1.o src/misc/pkcs5/pkcs_5_2.o src/misc/zeromem.o \
 src/modes/cbc/cbc_decrypt.o src/modes/cbc/cbc_done.o src/modes/cbc/cbc_encrypt.o \
 src/modes/cbc/cbc_getiv.o src/modes/cbc/cbc_setiv.o src/modes/cbc/cbc_start.o \
 src/modes/cfb/cfb_decrypt.o src/modes/cfb/cfb_done.o src/modes/cfb/cfb_encrypt.o \
 src/modes/cfb/cfb_getiv.o src/modes/cfb/cfb_setiv.o src/modes/cfb/cfb_start.o \
 src/modes/ctr/ctr_decrypt.o src/modes/ctr/ctr_done.o src/modes/ctr/ctr_encrypt.o \
-src/modes/ctr/ctr_getiv.o src/modes/ctr/ctr_setiv.o src/modes/ctr/ctr_start.o \
+src/modes/ctr/ctr_getiv.o src/modes/ctr/ctr_setiv.o src/modes/ctr/ctr_start.o src/modes/ctr/ctr_test.o \
 src/modes/ecb/ecb_decrypt.o src/modes/ecb/ecb_done.o src/modes/ecb/ecb_encrypt.o \
-src/modes/ecb/ecb_start.o src/modes/ofb/ofb_decrypt.o src/modes/ofb/ofb_done.o \
+src/modes/ecb/ecb_start.o src/modes/f8/f8_decrypt.o src/modes/f8/f8_done.o src/modes/f8/f8_encrypt.o \
+src/modes/f8/f8_getiv.o src/modes/f8/f8_setiv.o src/modes/f8/f8_start.o src/modes/f8/f8_test_mode.o \
+src/modes/lrw/lrw_decrypt.o src/modes/lrw/lrw_done.o src/modes/lrw/lrw_encrypt.o \
+src/modes/lrw/lrw_getiv.o src/modes/lrw/lrw_process.o src/modes/lrw/lrw_setiv.o \
+src/modes/lrw/lrw_start.o src/modes/lrw/lrw_test.o src/modes/ofb/ofb_decrypt.o src/modes/ofb/ofb_done.o \
 src/modes/ofb/ofb_encrypt.o src/modes/ofb/ofb_getiv.o src/modes/ofb/ofb_setiv.o \
 src/modes/ofb/ofb_start.o 
 
-HEADERS=src/headers/tommath_superclass.h src/headers/tomcrypt_cfg.h src/headers/tomcrypt_mac.h \
-src/headers/tomcrypt_macros.h src/headers/tomcrypt_custom.h src/headers/tomcrypt_argchk.h \
-src/headers/tomcrypt_cipher.h src/headers/tomcrypt_pk.h src/headers/tommath_class.h \
-src/headers/ltc_tommath.h src/headers/tomcrypt_hash.h src/headers/tomcrypt_misc.h \
-src/headers/tomcrypt.h src/headers/tomcrypt_pkcs.h src/headers/tomcrypt_prng.h testprof/tomcrypt_test.h
+HEADERS=src/headers/tomcrypt_cfg.h src/headers/tomcrypt_mac.h src/headers/tomcrypt_macros.h \
+src/headers/tomcrypt_custom.h src/headers/tomcrypt_argchk.h src/headers/tomcrypt_cipher.h \
+src/headers/tomcrypt_pk.h src/headers/tomcrypt_hash.h src/headers/tomcrypt_math.h \
+src/headers/tomcrypt_misc.h src/headers/tomcrypt.h src/headers/tomcrypt_pkcs.h \
+src/headers/tomcrypt_prng.h testprof/tomcrypt_test.h
+
+#END_INS
 
 TESTOBJECTS=demos/test.o
 HASHOBJECTS=demos/hashsum.o
@@ -158,73 +187,76 @@
 
 #ciphers come in two flavours... enc+dec and enc 
 src/ciphers/aes/aes_enc.o: src/ciphers/aes/aes.c src/ciphers/aes/aes_tab.c
-	$(CC) $(CFLAGS) -DENCRYPT_ONLY -c src/ciphers/aes/aes.c -o src/ciphers/aes/aes_enc.o
+	$(CC) $(CFLAGS) -DENCRYPT_ONLY -c $< -o src/ciphers/aes/aes_enc.o
 
 #These are the rules to make certain object files.
 src/ciphers/aes/aes.o: src/ciphers/aes/aes.c src/ciphers/aes/aes_tab.c
 src/ciphers/twofish/twofish.o: src/ciphers/twofish/twofish.c src/ciphers/twofish/twofish_tab.c
 src/hashes/whirl/whirl.o: src/hashes/whirl/whirl.c src/hashes/whirl/whirltab.c
-src/pk/ecc/ecc.o: src/pk/ecc/ecc.c src/pk/ecc/ecc_sys.c
-src/pk/dh/dh.o: src/pk/dh/dh.c src/pk/dh/dh_sys.c
 src/hashes/sha2/sha512.o: src/hashes/sha2/sha512.c src/hashes/sha2/sha384.c
 src/hashes/sha2/sha256.o: src/hashes/sha2/sha256.c src/hashes/sha2/sha224.c
 
 #This rule makes the libtomcrypt library.
 library: $(LIBNAME)
 
-$(LIBTEST): 
-	cd testprof ; CFLAGS="$(CFLAGS)" make 
+testprof/$(LIBTEST): 
+	cd testprof ; CFLAGS="$(CFLAGS)" LIBTEST_S=$(LIBTEST_S) $(MAKE) 
 
 $(LIBNAME): $(OBJECTS)
 	$(AR) $(ARFLAGS) [email protected] $(OBJECTS) 
-	$(RANLIB) $(LIBNAME)
+	$(RANLIB) [email protected]
 
 #This rule makes the hash program included with libtomcrypt
 hashsum: library $(HASHOBJECTS)
-	$(CC) $(HASHOBJECTS) $(LIBNAME) -o $(HASH) $(WARN)
+	$(CC) $(HASHOBJECTS) $(LIBNAME) $(EXTRALIBS) -o $(HASH) $(WARN)
 
 #makes the crypt program
 crypt: library $(CRYPTOBJECTS)
-	$(CC) $(CRYPTOBJECTS) $(LIBNAME) -o $(CRYPT) $(WARN)
+	$(CC) $(CRYPTOBJECTS) $(LIBNAME) $(EXTRALIBS) -o $(CRYPT) $(WARN)
 
 #makes the small program
 small: library $(SMALLOBJECTS)
-	$(CC) $(SMALLOBJECTS) $(LIBNAME) -o $(SMALL) $(WARN)
+	$(CC) $(SMALLOBJECTS) $(LIBNAME) $(EXTRALIBS) -o $(SMALL) $(WARN)
 	
 tv_gen: library $(TVS)
-	$(CC) $(TVS) $(LIBNAME) -o $(TV)
+	$(CC) $(LDFLAGS) $(TVS) $(LIBNAME) $(EXTRALIBS) -o $(TV)
 
 multi: library $(MULTIS)
-	$(CC) $(MULTIS) $(LIBNAME) -o $(MULTI)
+	$(CC) $(MULTIS) $(LIBNAME) $(EXTRALIBS) -o $(MULTI)
 
-timing: library $(LIBTEST) $(TIMINGS)
-	$(CC) $(TIMINGS) $(LIBTEST) $(LIBNAME) $(EXTRALIBS) -o $(TIMING)
+timing: library testprof/$(LIBTEST) $(TIMINGS)
+	$(CC) $(LDFLAGS) $(TIMINGS) testprof/$(LIBTEST) $(LIBNAME) $(EXTRALIBS) -o $(TIMING)
 
-test: library $(LIBTEST) $(TESTS)
-	$(CC) $(TESTS) $(LIBTEST) $(LIBNAME) -o $(TEST)
-
+test: library testprof/$(LIBTEST) $(TESTS)
+	$(CC) $(LDFLAGS) $(TESTS) testprof/$(LIBTEST) $(LIBNAME) $(EXTRALIBS) -o $(TEST)
 
 #This rule installs the library and the header files. This must be run
 #as root in order to have a high enough permission to write to the correct
 #directories and to set the owner and group to root.
+ifndef NODOCS
 install: library docs
+else
+install: library
+endif
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(LIBPATH)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(INCPATH)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(DATAPATH)
 	install -g $(GROUP) -o $(USER) $(LIBNAME) $(DESTDIR)$(LIBPATH)
 	install -g $(GROUP) -o $(USER) $(HEADERS) $(DESTDIR)$(INCPATH)
+ifndef NODOCS
 	install -g $(GROUP) -o $(USER) doc/crypt.pdf $(DESTDIR)$(DATAPATH)
+endif
 
-install_test: $(LIBTEST)
+install_test: testprof/$(LIBTEST)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(LIBPATH)
 	install -d -g $(GROUP) -o $(USER) $(DESTDIR)$(INCPATH)
-	install -g $(GROUP) -o $(USER) $(LIBTEST) $(DESTDIR)$(LIBPATH)
+	install -g $(GROUP) -o $(USER) testprof/$(LIBTEST) $(DESTDIR)$(LIBPATH)
 
 profile:
-	CFLAGS="$(CFLAGS) -fprofile-generate" make timing EXTRALIBS=-lgcov
+	CFLAGS="$(CFLAGS) -fprofile-generate" $(MAKE) timing EXTRALIBS="$(EXTRALIBS) -lgcov"
 	./timing
 	rm -f timing `find . -type f | grep [.][ao] | xargs`
-	CFLAGS="$(CFLAGS) -fprofile-use" make timing EXTRALIBS=-lgcov
+	CFLAGS="$(CFLAGS) -fprofile-use" $(MAKE) timing EXTRALIBS="$(EXTRALIBS) -lgcov"
 
 
 #This rule cleans the source tree of all compiled code, not including the pdf
@@ -236,7 +268,7 @@
 #build the doxy files (requires Doxygen, tetex and patience)
 doxy:
 	doxygen
-	cd doc/doxygen/latex ; make ; mv -f refman.pdf ../../.
+	cd doc/doxygen/latex ; ${MAKE} ; mv -f refman.pdf ../../.
 	echo The huge doxygen PDF should be available as doc/refman.pdf
 	
 #This builds the crypt.pdf file. Note that the rm -f *.pdf has been removed
@@ -249,6 +281,7 @@
 	latex crypt > /dev/null
 	latex crypt > /dev/null
 	makeindex crypt.idx > /dev/null
+	perl fixupind.pl
 	latex crypt > /dev/null
 	dvipdf crypt
 	mv -ivf crypt.pdf doc/crypt.pdf
@@ -259,6 +292,8 @@
 	latex crypt > /dev/null
 	latex crypt > /dev/null
 	makeindex crypt.idx
+	perl fixupind.pl
+	latex crypt > /dev/null
 	latex crypt > /dev/null
 
 #zipup the project (take that!)
@@ -278,5 +313,5 @@
 
 
 # $Source: /cvs/libtom/libtomcrypt/makefile,v $ 
-# $Revision: 1.70 $ 
-# $Date: 2005/06/19 18:03:24 $ 
+# $Revision: 1.145 $ 
+# $Date: 2006/12/02 19:23:21 $ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libtomcrypt/README	Thu Feb 22 14:53:49 2007 +0000
@@ -0,0 +1,3 @@
+See doc/crypt.pdf
+
+
--- a/libtomcrypt/TODO	Thu Feb 22 14:52:46 2007 +0000
+++ b/libtomcrypt/TODO	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/libtomcrypt/build.sh	Thu Feb 22 14:53:49 2007 +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	Thu Feb 22 14:52:46 2007 +0000
+++ b/libtomcrypt/changes	Thu Feb 22 14:53:49 2007 +0000
@@ -1,3 +1,233 @@
+December 16th, 2006
+v1.16 -- Brian Gladman pointed out that a recent change to GCM broke how the IV was handled.  Currently the code complies against his test vectors
+         so the code should be considered frozen now.
+      -- Trevor from Cryptography Research Inc. submitted patches to convert the ECC code to be generic allowing curve parameters to be submitted
+         at runtime.  
+      -- Fixed various doxygen comments
+      -- Added UTF8 support to the ASN1 code
+      -- Fixed STOREXXH macros for x86 platforms (Fix found at Elliptic Inc.)
+      -- Added makefile.unix which is BSD compatible, you have to manually tweak it since well I don't use it normally
+      -- removed a few lingering memcpy's
+      -- Fixed memory free errors in ecc_sign_hash() that can arise if the mp_init_multi() fails
+      -- Fixed incorrect return value in pkcs_1_pss_decode() which would correctly set res to 0 (indicating an incorrect signature) but 
+         would return CRYPT_OK to the caller
+      -- ltc_ecc_mulmod() could leak memory if mp_init(&mu) failed, fixed.  Would you believe that ltc_ecc_mulmod_timing() had the same
+         bug?  Also fixed.  :-)
+      -- Added Shamir's trick to the ECC side (defined as LTC_ECC_SHAMIR, enabled by default), gets ~1.34x to ~1.40x faster ECC verifications
+      -- Added Brian's vector #46 to the GCM code.  It catches the ctr counter error from v1.15.  Originally I was going to add all of his vectors,
+         but they're not as easy to parse and I got a lot of other things to do.  Regression!
+      -- Various other small fixes to the ECC code to clean up error handling (I think most of that was from the move in 1.06 to the plugins)
+         All of the errors were in cleaning up from heap failures.  So they were not likely to be triggered in normal usage
+         Made similar fixes to the RSA and DSA code (my bad)
+      -- Cryptography Research Inc. contributed a bunch of fixes to silence warnings (with MSVC) w.r.t. assigned data to unsigned char types.
+      -- Martin Marko suggested some fixes to make the RNG build with WinCE.
+      -- Updates to the manual for print (some fixes thanks to Martin Marko)
+      
+
+November 17th, 2006
+v1.15 -- Andreas Lange found that if sha256_init DID fail in fortuna it wouldn't clean up the state correctly.  Thanks.
+         Fortunately sha256_init cannot fail (as of v1.14) :-)
+      -- Andreas Lange contributed RMD-256 and RMD-320 code.
+      -- Removed mutex locks from fortuna_import as they create a deadlock and aren't required anyways [Avi Zelmanovich]
+      -- Added LTC_NO_PROTOTYPES to avoid prototyping functions like memset/memcpy.  Required for fans of GCC 3.3.x
+      -- David Eder caught a off by one overrun bug in pmac_done() which can be exploited if your output tag buffer is 
+         smaller than the block size of the cipher, e.g. if you have a 4-byte buffer and you tell pmac_done that you want
+         a 4-byte TAG it will store 4 bytes but return an outlen of 5.
+      -- Added signatures to the ECC and RSA benchmarks
+      -- Added LTC_PROFILE to run the PK tests only once in the timing demo (so you can capture events properly)
+      -- Andreas contributed PKCS #1 v1.5 code that merged cleanly with the existing PKCS code.  w00t.
+         (update: I had to fix it to include the digestInfo and what not.  Bad Andreas, bad! hehehe)
+      -- Fixed a signed variable error in gcm_process() (hard to trigger bug fortunately)
+      -- Removed all memcmp/memset/memcpy from the source (replaced with X macros)
+      -- Renamed macros HMAC/OMAC/PMAC to have a LTC_ prefix.  If you pass these on the command line please update your makefiles
+      -- Added XCBC-MAC support [RFC 3566]
+      -- fixed LOAD32H and LOAD64H to stop putting out that darn warning :-)
+      -- Added the Korean SEED block cipher [RFC 4269]
+      -- Added LTC_VALGRIND define which makes SOBER-128 and RC4 a pure PRNG (and not a stream cipher).  Useful if you use 
+         Valgrind to debug your code (reported by Andreas Lange)
+      -- Made SOBER-128 more portable by removing the ASCII key in the test function (my bad, sorry).
+      -- Martin Mocko pointed out that if you have no PRNGs defined the lib won't build.  Fixed, also fixed for if you have no
+         hashes defined.
+      -- Sped up F8 mode with LTC_FAST
+      -- Made CTR mode RFC 3686 compliant (increment counter first), to enable, OR the value LTC_CTR_RFC3686 to the "mode"
+         parameter you pass to ctr_start(), otherwise it will be LTC compliant (e.g. encrypt then increment)
+      -- Added ctr_test() to test CTR mode against RFC 3686
+      -- Added crypt_fsa() ... O_o
+      -- Fixed LTC_ECC_TIMING_RESISTANT so it once again builds properly (pt add/dbl are through the plugin now)
+      -- Added ANSI X9.63 (sec 4.3.6) import/export of public keys (cannot export to compressed formats but will import 
+         hybrid compressed)
+      -- Added SECP curves for 112, 128, and 160 bits (only the 'r1' curves)
+      -- Added 3GPP-F9 MAC (thanks to Greg Rose for the test vectors)
+      -- Added the KASUMI block cipher
+      -- Added F9/XCBC/OMAC callbacks to the cipher plugin
+      -- Added RSA PKCS #1 v1.5 signature/encrypt tests to rsa_test.c
+      -- Fix to yarrow_test() to not call yarrow_done() which is invalid in that context (thanks Valgrind)
+      -- Christophe Devine pointed out that Anubis would fail on various 64-bit UNIX boxes when "x>>24" was used as an index, we needed 
+         to mask it with 0xFF.  Thanks.  Fixed.
+
+August 0x1E, 0x07D6
+v1.14 -- Renamed the chaining mode macros from XXX to LTC_XXX_MODE.  Should help avoid polluting the macro name space.
+      -- clean up of SHA-256
+      -- Chris Colman pointed out that der_decode_sequence_* allows LTC_ASN1_SETOF to accept SEQUENCEs and vice versa.
+         Decoder [non-flexi decoder that is] is more strict now and requires a match.
+      -- Steffen Jaeckel pointed out a typo in the user manual (re: rsa_exptmod).  Fixed.  This disproves the notion that
+         nobody reads it.  :-)
+      -- Made GCM a bit more portable w.r.t. handling the CTR IV (e.g. & with 255)
+      -- Add LTC_VERBOSE if you really want to see what test is doing :-)
+      -- Added SSE2 support to GCM [use GCM_TABLES_SSE2 to enable], shaves 2 cycles per byte on Opteron processors
+         Shaved 4 cycles on a Prescott (Intel P4)
+         Requires you align your gcm_state on a 16 byte boundary, see gcm_memory() for more info
+      -- Added missing prototype for f8_test_mode()
+      -- two fixes to CCM for corner cases [L+noncelen > 15] and fixing the CTR pad to encrypt the CBC-MAC tag
+      -- Franz Glasner pointed out the ARGTYPE=4 is not actually valid.  Fixed.
+      -- Fixed bug in f8_start() if your key < saltkey unspecified behaviour occurs.  :-(
+      -- Documented F8 mode.  Yeah, because you read the manual.  
+      -- Minor updates to the technotes.
+
+
+June 17th, 2006
+v1.13 -- Fixed to fortuna_start() to clean up state if an error occurs.  Not really useful at this stage (sha256 can't fail) but useful
+         if I ever make fortuna pluggable
+      -- Mike Marin submitted a whole bunch of patches for fixing up the libs on traditional UNIX platforms.  Go AIX!  Thanks!
+      -- One of bugs found in the multi demo highlights that at least with gcc you need to pass integers with a UL prefix to ensure
+         they're unsigned long
+      -- Updated the FP ECC code to use affine points.  It's teh fast.
+      -- Made it so many functions which return CRYPT_BUFFER_OVERFLOW now also indicate the required buffer size, note that not all functions
+         do this (most do though).
+      -- Added F8 chaining mode.  It's super neato.
+
+May 29th, 2006
+v1.12 -- Fixed OID encoder/decoder/length to properly handle the first two parts of an OID, matches 2002 X.690 now.
+      -- [Wesley Shields] Allows both GMP/LTM and TFM to be defined now.  
+      -- [Wesley Shields] GMP pluggin is cleaner now and doesn't use deprecated symbols. Yipee
+      -- Added count_lsb_bits to get the number of leading LSB zero bits there are.
+      -- Fixed a bug in the INTEGER encoders for values of -(256**k)/2
+      -- Added BOOLEAN type to ASN.1 thingy-ma-do-hicky
+      -- Testprof doesn't strictly require GMP ... oops [Nils Durner]
+      -- Added LTC_CALL and LTC_EXPORT macros in tomcrypt_cfg.h to support various calling and linker conventions
+         (Thanks to John Kirk from Demonware)
+      -- In what has to be the best thing since sliced bread I bring you MECC_FP which is the fixed point
+         ECC point multiplier.  It's fast, it's sexy and what's more it's hella fast [did I mention it's fast?]
+         You can tune it somewhat with FP_LUT (default to 8) for look-up width.
+         Read section 8.2 of the manual for more info.
+         It is disabled by default, you'll have to build LTC with it defined to get it.  
+      -- Fixed bug in ecc_test.c (from testprof) to include the 521 [not 512] bit curve.  :-)
+
+April 4th, 2006
+v1.11 -- Removed printf's from lrw_test ... whoops
+      -- lrw_process now checks the return of the cipher ecb encrypt/decrypt calls
+      -- lrw_start was not using num_rounds ...
+      -- Adam Miller reported a bug in the flexi decoder with elements past the end of a sequence.  Fixed.
+      -- Bruce Guenter suggested I use --tag=CC for libtool builds where the compiler may think it's C++.  (I applied this to LTM and TFM)
+      -- Optimized the ECC for TFM a bit by removing the useless "if" statements (most TFM functions don't return error codes)
+         Actually shaved a good chunk of time off and made the code smaller.  By default with TFM the stock LTC point add/dbl functions 
+         will be totally omitted (ECC-256 make key times on a Prescott for old vs. new are 11.03M vs. 9.59M cycles)
+      -- added missing CVS tags to ltc_ecc_mulmod.c
+      -- corrected typo in tomcrypt_cfg.h about what the file has been called 
+      -- corrected my address in the user manual.  A "bit" out of date.
+      -- added lrw_gen to tv_gen
+      -- added GMP plugin, only tested on a AMD64 and x86_32 Gentoo Linux box so be aware
+      -- made testme.sh runs diff case insensitivityly [whatever...] cuz GMP outputs lowercase satan text
+      -- added LDFLAGS to the makefile to allow cross porting linking options
+      -- added lrw_test() to the header file ... whoops
+      -- changed libtomcrypt.org to libtomcrypt.com .... mumble mumble
+      -- Updates to detect __STRICT_ANSI__ which is defined in --std=c99 modes (note -ansi is not supported as it lacks long long) so you can
+         build LTC out of the box with c99 (note: it'll be slower as there is no asm in this case)
+      -- Updated pelican.c and aes_tab.c to undef tables not-required.  The tables are static so both AES and Pelican MAC would have copies.  Save a few KB in the final binary.
+      -- Added LTC_NO_FAST to the makefile.icc to compensate for the fact ICC v9 can't handle it (Pelican MAC fails for instance)
+
+February 11th, 2006
+v1.10 -- Free ecb/cbc/ctr/lrw structures in timing code by calling the "done" function
+      -- fixed bug in lrw_process() which would always use the slow update ...
+      -- vastly sped up gcm_gf_mult() when LTC_FAST is defined.  This speeds up LRW and GCM state creation, useful for servers with GCM
+      -- Removed NLS since there are some attacks against it.  
+      -- fixed memory leak in rsa_import reported by John Kuhns
+      ++ re-released as the rsa fix was incorrect (bad John bad ... hehehe) and I missed some NULLs in the static descriptor entry for ciphers 
+
+January 26th, 2006
+v1.09 -- Added missing doxygen comments to some of the ASN.1 routines
+      -- Added "easy button" define LTC_EASY and LTC will build with a subset of all the algos.  Reduces build times for typical
+         configurations.  Tunable [see tomcrypt_custom.h]
+      -- Added some error detection to reg_algs() of the testprof.a library to detect when the PRNG is not setup correctly (took me 10 mins to figure out, PITA!)
+      -- Similar fixes to timing demo (MD5 not defined when EASY is defined)
+      -- Added the NLS enc+mac stream cipher from QUALCOMM, disabled for this release, waiting on test vectors
+      -- Finally added an auto-update script for the makefiles.  So when I add new files/dirs it can automatically fix up the makefiles [all four of them...]
+      -- Added LRW to the list of cipher modes supported
+      -- cleaned up ciphers definitions to remove cbc/cfb/ofb/ctr/etc from the namespace when not used.
+
+November 24th, 2005
+v1.08 -- Added SET and SET OF support to the ASN.1 side
+      -- Fixed up X macros, added QSORT to the mix [thanks SET/SETOF]
+      -- Added XMEMCMP to the list of X macros
+      -- In der_decode_sequence() the SHORT_INTEGER type was not being handled correctly [oddly enough it worked just enough to make RSA work ... go figure!]
+      -- Fixed bug in math descriptors where if you hadn't defined MECC (ECC support) you would get linker errors
+      -- Added RSA accelerators to the math descriptors to make it possible to not include the stock routines if you supply your own.
+      -- dsa_decrypt_key() was erroneously dependent on MECC not MDSA ... whoops
+      -- Moved DSA size limits to tomcrypt_pk.h so they're defined with LTC_NO_PK+MDSA
+      -- cleaned up tomcrypt_custom.h to make customizable PK easier (and also cleaned up the error traps so they're correctly reported)
+
+November 18th, 2005
+v1.07 -- Craig Schlenter pointed out the "encrypt" demo doesn't call ctr_start() correctly.  That's because as of a few releases ago
+         I added support to set the mode of the counter at init time
+      -- Fixed some "testprof" make issues
+      -- Added RSA keygen to the math descriptors
+      -- Fixed install_test target ... oops
+      -- made the "ranlib" program renamable useful for cross-compiling
+      -- Made the cipher accelerators return error codes.  :-)
+      -- Made CCM accept a pre-scheduled key to speed it up if you use the same key for multiple packets
+      -- Added "Katja" public key crypto.  It's based on the recent N = p^2q work by Katja.  I added OAEP padding
+         to it.  Note this code has been disabled not because it doesn't work but because it hasn't been thoroughly
+         analyzed.   It does carry some advantages over RSA (slightly smaller public key, faster decrypt) but also
+         some annoying "setup" issues like the primes are smaller which makes ECM factoring more plausible.
+      -- Made makefile accept a NODOCS flag to disable the requirement of tetex to install LTC for you no tetex people... all 3 of ya  :-)
+      -- Cleaned up rsa_export() since "zero" was handled with a SHORT_INTEGER
+      -- Cleaned up the LIBTEST_S definitions in both GNU makefiles.  A few minor touchups as well.
+      -- Made the cipher ecb encrypt/decrypt return an int as well, changed ALL dependent code to check for this.  
+      -- der_decode_choice() would fail to mark a NULL as "used" when decoding.  Fixed
+      -- ecc_decrypt_key() now uses find_hash_oid() to clean up the code ;-)
+      -- Added mp_neg() to the math descriptors.
+      -- Swapped arguments for the pkcs_1_mgf1() function so the hash_idx is the first param (to be more consistent)
+      -- Made the math descriptors buildable when RSA has been undefined
+      -- ECC timing demo now capable of detecting which curves have been defined
+      -- Refactored the ECC code so it's easier to maintain.  (note: the form of this code hasn't really changed since I first added ECC ... :-/)
+      -- Updated the documentation w.r.t. ECC and the accelerators to keep it current
+      -- Fixed bug in ltc_init_multi() which would fail to free all allocated memory on error.
+      -- Fixed bug in ecc_decrypt_key() which could possibly lead to overflows (if MAXBLOCKSIZE > ECC_BUF_SIZE and you have a hash that emits MAXBLOCKSIZE bytes)
+      -- Added encrypt/decrypt to the DSA side (basically DH with DSA parameters)
+      -- Updated makefiles to remove references to the old DH object files and the ecc_sys.o crap ... clean code ahead!
+      -- ecc_import() now checks if the point it reads in lies on the curve (to prevent degenerative points from being used)
+      -- ECC code now ALWAYS uses the accelerator interface.  This allows people who use the accelerators to not have the stock
+         ECC point add/dbl/mul code linked in.  Yeah space savings! Rah Rah Rah.
+      -- Added LTC_MUTEX_* support to Yarrow and Fortuna allowing you to use respective prng_state as a global PRNG state [e.g. thread-safe] if you define one of the LTC_* defines at
+         build time (e.g. LTC_PTHREAD == pthreads)
+      -- Added PPC32 support to the rotate macros (tested on an IBM PPC 405) and LTC_FAST macros (it aint fast but it's faster than stock)
+      -- Added ltc_mp checks in all *_make_key() and *_import() which will help catch newbs who don't register their bignum first :-)
+      -- the UTCTIME type was missing from der_length_sequence() [oops, oh like you've never done that]
+      -- the main makefile allows you to rename the make command [e.g. MAKE=gmake gmake install] so you can build LTC on platforms where the default make command sucks [e.g. BSD]
+      -- Added DER flexi decoder which allows the decoding of arbitrary DER encoded packets without knowing
+         their structure in advance (thanks to MSVC for finding 3 bugs in it just prior to release! ... don't ask)
+
+August 1st, 2005
+v1.06 -- Fixed rand_prime() to accept negative inputs as a signal for BBS primes. [Fredrik Olsson]
+      -- Added fourth ARGCHK type which outputs to stderr and continues.  Useful if you trap sigsegv.   [Valient Gough]
+      -- Removed the DH code from the tree
+      -- Made the ECC code fully public (you can access ecc_mulmod directly now) useful for debuging
+      -- Added ecc test to tv_gen
+      -- Added hmac callback to hash descriptors.
+      -- Fixed two doxy comment errors in the UTCTIME functions
+      -- rsa_import() can now read OpenSSL format DER public keys as well as the PKCS #1 RSAPublicKey format.
+         Note that rsa_export()  **ONLY** writes PKCS #1 formats
+      -- Changed MIN/MAX to only define if not already present.  -- Kirk J from Demonware ... 
+      -- Ported tv_gen to new framework (and yes, I made ecc vectors BEFORE changing the API and YES they match now :-))
+      -- ported testing scripts to support pluggable math.  yipee!
+      -- Wrote a TFM descriptor ... yipee
+      -- Cleaned up LTC_FAST in CBC mode a bit 
+      -- Merged in patches from Michael Brown for the sparc/sparc64 targets
+      -- Added find_hash_oid() to search for a hash by its OID
+      -- Cleaned up a few stray CLEAN_STACKs that should have been LTC_CLEAN_STACK
+      -- Added timing resistant ECC, enable by defining LTC_ECC_TIMING_RESISTANT then use ECC API as normal 
+      -- Updated the ECC documentation as it was a bit out of date
+
 June 27th, 2005
 v1.05
       -- Added Technote #6 which covers the current PK compliance.  
@@ -213,7 +443,7 @@
 v0.99  -- Merged in the latest version of LTM which includes all of the recent bug fixes
        -- Deprecated LTMSSE and removed it (to be replaced with TFM later on)
        -- Stefan Arentz pointed out that mp_s_rmap should be extern
-       -- Kristian Gjøsteen pointed out that there are typos in the 
+       -- Kristian Gj?steen pointed out that there are typos in the 
           "test" makefile and minor issues in Yarrow and Sober [just cosmetics really]
        -- Matthew P. Cashdollar pointed out that "export" is a C++ keyword 
           so changed the PRNG api to use "pexport" and "pimport"
@@ -592,7 +822,7 @@
           as much as possible.  This sped the routine up quite a bit.
        -- Fixed a huge flaw in ecc_verify_hash() where it would return CRYPT_OK on error... Now fixed.
        -- Fixed up config.pl by fixing an invalid query and the file is saved in non-windows [e.g. not CR/LF] format
-          (fix due to Mika Boström)
+          (fix due to Mika Bostr?m)
        -- Merged in LibTomMath for kicks
        -- Changed the build process so that by default "mycrypt_custom.h" is included and provided
           The makefile doesn't include any build options anymore
@@ -1321,6 +1551,6 @@
 v0.01  -- We will call this the first version.
 
 /* $Source: /cvs/libtom/libtomcrypt/changes,v $ */
-/* $Revision: 1.106 $ */
-/* $Date: 2005/06/27 12:37:06 $ */
+/* $Revision: 1.274 $ */
+/* $Date: 2006/12/16 19:08:17 $ */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libtomcrypt/crypt.lof	Thu Feb 22 14:53:49 2007 +0000
@@ -0,0 +1,24 @@
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {2.1}{\ignorespaces Load And Store Macros}}{9}{figure.2.1}
+\contentsline {figure}{\numberline {2.2}{\ignorespaces Rotate Macros}}{9}{figure.2.2}
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {3.1}{\ignorespaces Built--In Software Ciphers}}{19}{figure.3.1}
+\contentsline {figure}{\numberline {3.2}{\ignorespaces Twofish Build Options}}{21}{figure.3.2}
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {4.1}{\ignorespaces Built--In Software Hashes}}{57}{figure.4.1}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {6.1}{\ignorespaces List of Provided PRNGs}}{82}{figure.6.1}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {9.1}{\ignorespaces DSA Key Sizes}}{119}{figure.9.1}
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {10.1}{\ignorespaces List of ASN.1 Supported Types}}{127}{figure.10.1}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
+\contentsline {figure}{\numberline {12.1}{\ignorespaces RSA/DH Key Strength}}{149}{figure.12.1}
+\contentsline {figure}{\numberline {12.2}{\ignorespaces ECC Key Strength}}{149}{figure.12.2}
+\addvspace {10\[email protected] }
+\addvspace {10\[email protected] }
--- a/libtomcrypt/crypt.tex	Thu Feb 22 14:52:46 2007 +0000
+++ b/libtomcrypt/crypt.tex	Thu Feb 22 14:53:49 2007 +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 t