- Issue #16039: CVE-2013-1752: Change use of readline in imaplib module to
  limit line length.  Patch by Emil Lind.
diff --git a/Lib/imaplib.py b/Lib/imaplib.py
index 8734a84..bac4c05 100644
--- a/Lib/imaplib.py
+++ b/Lib/imaplib.py
@@ -35,6 +35,15 @@
 IMAP4_SSL_PORT = 993
 AllowedVersions = ('IMAP4REV1', 'IMAP4')        # Most recent first
 
+# Maximal line length when calling readline(). This is to prevent
+# reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1)
+# don't specify a line length. RFC 2683 however suggests limiting client
+# command lines to 1000 octets and server command lines to 8000 octets.
+# We have selected 10000 for some extra margin and since that is supposedly
+# also what UW and Panda IMAP does.
+_MAXLINE = 10000
+
+
 #       Commands
 
 Commands = {
@@ -237,7 +246,10 @@
 
     def readline(self):
         """Read line from remote."""
-        return self.file.readline()
+        line = self.file.readline(_MAXLINE + 1)
+        if len(line) > _MAXLINE:
+            raise self.error("got more than %d bytes" % _MAXLINE) 
+        return line
 
 
     def send(self, data):
diff --git a/Lib/test/test_imaplib.py b/Lib/test/test_imaplib.py
index f288ef0..ba36235 100644
--- a/Lib/test/test_imaplib.py
+++ b/Lib/test/test_imaplib.py
@@ -176,6 +176,16 @@
             self.assertRaises(imaplib.IMAP4.abort,
                               self.imap_class, *server.server_address)
 
+    def test_linetoolong(self):
+        class TooLongHandler(TimeoutStreamRequestHandler):
+            def handle(self):
+                # Send a very long response line
+                self.wfile.write('* OK ' + imaplib._MAXLINE*'x' + '\r\n')
+
+        with self.reaped_server(TooLongHandler) as server:
+            self.assertRaises(imaplib.IMAP4.error,
+                              self.imap_class, *server.server_address)
+
 class ThreadedNetworkedTests(BaseThreadedNetworkedTests):
 
     server_class = SocketServer.TCPServer
diff --git a/Misc/NEWS b/Misc/NEWS
index 833cd05..e6c60b9 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,9 @@
 Library
 -------
 
+- Issue #16039: CVE-2013-1752: Change use of readline in imaplib module to
+  limit line length.  Patch by Emil Lind.
+
 - Issue #14984: On POSIX systems, when netrc is called without a filename
   argument (and therefore is reading the user's $HOME/.netrc file), it now
   enforces the same security rules as typical ftp clients: the .netrc file must