Update from stable branch.
diff --git a/CHANGES b/CHANGES
index bee9941..695ed97 100644
--- a/CHANGES
+++ b/CHANGES
@@ -745,6 +745,10 @@
 
  Changes between 0.9.8j and 0.9.8k  [xx XXX xxxx]
 
+  *) Improve efficiency of mem_gets: don't search whole buffer each time
+     for a '\n'
+     [Jeremy Shapiro <jnshapir@us.ibm.com>]
+
   *) New -hex option for openssl rand.
      [Matthieu Herrb]
 
diff --git a/crypto/bio/bss_mem.c b/crypto/bio/bss_mem.c
index e18f4bc..37d4194 100644
--- a/crypto/bio/bss_mem.c
+++ b/crypto/bio/bss_mem.c
@@ -280,6 +280,7 @@
 
 	BIO_clear_retry_flags(bp);
 	j=bm->length;
+	if ((size-1) < j) j=size-1;
 	if (j <= 0)
 		{
 		*buf='\0';
@@ -288,17 +289,18 @@
 	p=bm->data;
 	for (i=0; i<j; i++)
 		{
-		if (p[i] == '\n') break;
+		if (p[i] == '\n')
+			{
+			i++;
+			break;
+			}
 		}
-	if (i == j)
-		{
-		BIO_set_retry_read(bp);
-		/* return(-1);  change the semantics 0.6.6a */ 
-		}
-	else
-		i++;
-	/* i is the max to copy */
-	if ((size-1) < i) i=size-1;
+
+	/*
+	 * i is now the max num of bytes to copy, either j or up to
+	 * and including the first newline
+	 */ 
+
 	i=mem_read(bp,buf,i);
 	if (i > 0) buf[i]='\0';
 	ret=i;