classification
Title: ssl.read/write on closed socket raises AttributeError
Type: enhancement Stage: needs patch
Components: Library (Lib) Versions: Python 3.3
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: cbay, ezio.melotti, pitrou
Priority: normal Keywords:

Created on 2010-07-06 09:52 by cbay, last changed 2012-05-07 11:41 by pitrou.

Messages (2)
msg109379 - (view) Author: Cyril (cbay) Date: 2010-07-06 09:52
This:

import socket, ssl

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s)
ssl_sock.connect(('www.verisign.com', 443))
ssl_sock.close()
ssl_sock.read(1024)

raises:

Traceback (most recent call last):
  File "/tmp/bug.py", line 10, in <module>
    ssl_sock.read(1024)
  File "/path/to/lib/python2.7/ssl.py", line 138, in read
    return self._sslobj.read(len)
AttributeError: 'NoneType' object has no attribute 'read'


I would expect a socket.error instead, which mimics the way regular sockets behave. Indeed, this code:

import socket, ssl

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.verisign.com', 80))
s.close()
s.recv(1024)

raises:

Traceback (most recent call last):
  File "/tmp/bug.py", line 6, in <module>
    s.recv(1024)
  File "/path/to/lib/python2.7/socket.py", line 170, in _dummy
    raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor


I've tested on the latest trunks on both 2.7 and 3.2. I've also tested on 2.6 and 3.1.

I can write a patch that fixes it if the bug is accepted.
msg160140 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2012-05-07 11:41
I don't think mimicking EBADF is very useful. Reading from a closed socket is usually a programming error, so it's not the kind of error you'll want to catch at runtime.

AttributeError may not be very pretty though, so perhaps a ValueError can be raised as with closed files:

>>> f = open("LICENSE")
>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
History
Date User Action Args
2012-05-07 11:41:34pitrousettype: behavior -> enhancement
messages: + msg160140
versions: - Python 2.7, Python 3.2
2012-05-07 11:19:11ezio.melottisetnosy: + pitrou, ezio.melotti
stage: needs patch

versions: + Python 3.3, - Python 2.6, Python 3.1
2010-07-06 09:52:58cbaycreate