[New-bugs-announce] [issue14574] SocketServer doesn't handle client disconnects properly

Vlad report at bugs.python.org
Sat Apr 14 01:07:42 CEST 2012

New submission from Vlad <vladandjeric at gmail.com>:

When dealing with a new connection, SocketServer.BaseRequestHandler.__init__ first calls the request handler (self.handle below) and then calls cleanup code which closes the connection (self.finish below).

class BaseRequestHandler:
    def __init__(self, request, client_address, server):
        < ... snip ... >

The issue arises when a client disconnects suddenly during the self.handle() call. The handler may attempt to write data to the disconnected socket.  This will cause an exception (which is correct), but somehow data will still be added to the connection's buffer and self.wfile.closed will be False! As a result, BaseRequestHandler.finish() will attempt to flush the connection's buffer and this will raise another exception which can't be handled without modifying the library code.

Exception happened during processing of request from ('', 62718)
Traceback (most recent call last):
  File "C:\Python27\lib\SocketServer.py", line 284, in _handle_request_noblock
    self.process_request(request, client_address)
  File "C:\Python27\lib\SocketServer.py", line 310, in process_request
    self.finish_request(request, client_address)
  File "C:\Python27\lib\SocketServer.py", line 323, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Python27\lib\SocketServer.py", line 641, in __init__
  File "C:\Python27\lib\SocketServer.py", line 694, in finish
  File "C:\Python27\lib\socket.py", line 303, in flush
error: [Errno 10053] An established connection was aborted by the software in your host machine

I've provided a toy server below, you can reproduce the issue by submitting a request to it with curl and then immediately killing curl:

 curl -d "test"

Toy server code:

import BaseHTTPServer
import SocketServer
import time

class ThreadedHTTPServer(BaseHTTPServer.HTTPServer):

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def do_POST(self):
      length = int(self.headers["Content-Length"])
      request = self.rfile.read(length)

      print "Sleeping. Kill the 'curl' command now."
      print "Woke up. You should see a stack trace from the problematic exception below."

      print "Received POST: " + request
      self.send_response(200) # <------- This somehow adds to the connection's buffer!
    except Exception as e:
      print "Exception: " + str(e)  # <----- This exception is expected

httpd = ThreadedHTTPServer(("", 8000), RequestHandler)

components: Library (Lib)
messages: 158240
nosy: vdjeric
priority: normal
severity: normal
status: open
title: SocketServer doesn't handle client disconnects properly
versions: Python 2.7

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list