@@ -185,7 +185,11 @@ def _instrument(self, response, key, conn, count, keep):
185185 a connection is never reused.
186186 """
187187
188- state = {"handled" : False }
188+ # 'eof' is raised only on a genuine end-of-body (observed while reading), never
189+ # merely because close() nulled the file object; the socket is handed back to the
190+ # pool solely on that signal, so a half-read response can never be reused (which
191+ # would splice its leftover bytes onto the next request - response desynchronization)
192+ state = {"handled" : False , "reading" : False , "eof" : False }
189193 _read = response .read
190194 _close = response .close
191195
@@ -200,7 +204,7 @@ def drained():
200204
201205 def settle ():
202206 # Once (and only once) the body is fully drained, decide the socket's fate
203- if state ["handled" ] or not drained () :
207+ if state ["handled" ] or not state [ "eof" ] :
204208 return
205209 state ["handled" ] = True
206210 if keep :
@@ -212,12 +216,23 @@ def settle():
212216 pass
213217
214218 def read (* args , ** kwargs ):
215- data = _read (* args , ** kwargs )
219+ state ["reading" ] = True
220+ try :
221+ data = _read (* args , ** kwargs )
222+ finally :
223+ state ["reading" ] = False
224+ if drained ():
225+ state ["eof" ] = True
216226 settle ()
217227 return data
218228
219229 def close ():
220- # Note: on Python 2 httplib.read() calls close() itself upon EOF
230+ # Note: on Python 2 httplib.read() calls close() itself upon EOF, i.e. from inside
231+ # our read(); such an in-read close marks a real end-of-body. An external close()
232+ # on a not-yet-drained body means the caller abandoned it (e.g. sqlmap hitting a
233+ # size cap), so the socket must be dropped rather than returned to the pool.
234+ if state ["reading" ]:
235+ state ["eof" ] = True
221236 _close ()
222237 settle ()
223238 if not state ["handled" ]:
@@ -228,6 +243,7 @@ def close():
228243 except Exception :
229244 pass
230245
246+ response ._keepaliveManaged = True
231247 response .read = read
232248 response .close = close
233249
0 commit comments