We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
NpipeSocket.makefile crashes when bufsize < 0
**Original report**: https://github.com/docker/compose/issues/3901#issuecomment-244828701

Negative `bufsize` should be handled.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `docker/transport/npipesocket.py`
Content:
```
1 import functools
2 import io
3 
4 import win32file
5 import win32pipe
6 
7 cSECURITY_SQOS_PRESENT = 0x100000
8 cSECURITY_ANONYMOUS = 0
9 cPIPE_READMODE_MESSAGE = 2
10 
11 
12 def check_closed(f):
13     @functools.wraps(f)
14     def wrapped(self, *args, **kwargs):
15         if self._closed:
16             raise RuntimeError(
17                 'Can not reuse socket after connection was closed.'
18             )
19         return f(self, *args, **kwargs)
20     return wrapped
21 
22 
23 class NpipeSocket(object):
24     """ Partial implementation of the socket API over windows named pipes.
25         This implementation is only designed to be used as a client socket,
26         and server-specific methods (bind, listen, accept...) are not
27         implemented.
28     """
29     def __init__(self, handle=None):
30         self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT
31         self._handle = handle
32         self._closed = False
33 
34     def accept(self):
35         raise NotImplementedError()
36 
37     def bind(self, address):
38         raise NotImplementedError()
39 
40     def close(self):
41         self._handle.Close()
42         self._closed = True
43 
44     @check_closed
45     def connect(self, address):
46         win32pipe.WaitNamedPipe(address, self._timeout)
47         handle = win32file.CreateFile(
48             address,
49             win32file.GENERIC_READ | win32file.GENERIC_WRITE,
50             0,
51             None,
52             win32file.OPEN_EXISTING,
53             cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT,
54             0
55         )
56         self.flags = win32pipe.GetNamedPipeInfo(handle)[0]
57 
58         self._handle = handle
59         self._address = address
60 
61     @check_closed
62     def connect_ex(self, address):
63         return self.connect(address)
64 
65     @check_closed
66     def detach(self):
67         self._closed = True
68         return self._handle
69 
70     @check_closed
71     def dup(self):
72         return NpipeSocket(self._handle)
73 
74     @check_closed
75     def fileno(self):
76         return int(self._handle)
77 
78     def getpeername(self):
79         return self._address
80 
81     def getsockname(self):
82         return self._address
83 
84     def getsockopt(self, level, optname, buflen=None):
85         raise NotImplementedError()
86 
87     def ioctl(self, control, option):
88         raise NotImplementedError()
89 
90     def listen(self, backlog):
91         raise NotImplementedError()
92 
93     def makefile(self, mode=None, bufsize=None):
94         if mode.strip('b') != 'r':
95             raise NotImplementedError()
96         rawio = NpipeFileIOBase(self)
97         if bufsize is None:
98             bufsize = io.DEFAULT_BUFFER_SIZE
99         return io.BufferedReader(rawio, buffer_size=bufsize)
100 
101     @check_closed
102     def recv(self, bufsize, flags=0):
103         err, data = win32file.ReadFile(self._handle, bufsize)
104         return data
105 
106     @check_closed
107     def recvfrom(self, bufsize, flags=0):
108         data = self.recv(bufsize, flags)
109         return (data, self._address)
110 
111     @check_closed
112     def recvfrom_into(self, buf, nbytes=0, flags=0):
113         return self.recv_into(buf, nbytes, flags), self._address
114 
115     @check_closed
116     def recv_into(self, buf, nbytes=0):
117         readbuf = buf
118         if not isinstance(buf, memoryview):
119             readbuf = memoryview(buf)
120 
121         err, data = win32file.ReadFile(
122             self._handle,
123             readbuf[:nbytes] if nbytes else readbuf
124         )
125         return len(data)
126 
127     @check_closed
128     def send(self, string, flags=0):
129         err, nbytes = win32file.WriteFile(self._handle, string)
130         return nbytes
131 
132     @check_closed
133     def sendall(self, string, flags=0):
134         return self.send(string, flags)
135 
136     @check_closed
137     def sendto(self, string, address):
138         self.connect(address)
139         return self.send(string)
140 
141     def setblocking(self, flag):
142         if flag:
143             return self.settimeout(None)
144         return self.settimeout(0)
145 
146     def settimeout(self, value):
147         if value is None:
148             self._timeout = win32pipe.NMPWAIT_NOWAIT
149         elif not isinstance(value, (float, int)) or value < 0:
150             raise ValueError('Timeout value out of range')
151         elif value == 0:
152             self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT
153         else:
154             self._timeout = value
155 
156     def gettimeout(self):
157         return self._timeout
158 
159     def setsockopt(self, level, optname, value):
160         raise NotImplementedError()
161 
162     @check_closed
163     def shutdown(self, how):
164         return self.close()
165 
166 
167 class NpipeFileIOBase(io.RawIOBase):
168     def __init__(self, npipe_socket):
169         self.sock = npipe_socket
170 
171     def close(self):
172         super(NpipeFileIOBase, self).close()
173         self.sock = None
174 
175     def fileno(self):
176         return self.sock.fileno()
177 
178     def isatty(self):
179         return False
180 
181     def readable(self):
182         return True
183 
184     def readinto(self, buf):
185         return self.sock.recv_into(buf)
186 
187     def seekable(self):
188         return False
189 
190     def writable(self):
191         return False
192
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/docker/transport/npipesocket.py b/docker/transport/npipesocket.py
--- a/docker/transport/npipesocket.py
+++ b/docker/transport/npipesocket.py
@@ -94,7 +94,7 @@
         if mode.strip('b') != 'r':
             raise NotImplementedError()
         rawio = NpipeFileIOBase(self)
-        if bufsize is None:
+        if bufsize is None or bufsize < 0:
             bufsize = io.DEFAULT_BUFFER_SIZE
         return io.BufferedReader(rawio, buffer_size=bufsize)

{"golden_diff": "diff --git a/docker/transport/npipesocket.py b/docker/transport/npipesocket.py\n--- a/docker/transport/npipesocket.py\n+++ b/docker/transport/npipesocket.py\n@@ -94,7 +94,7 @@\n         if mode.strip('b') != 'r':\n             raise NotImplementedError()\n         rawio = NpipeFileIOBase(self)\n-        if bufsize is None:\n+        if bufsize is None or bufsize < 0:\n             bufsize = io.DEFAULT_BUFFER_SIZE\n         return io.BufferedReader(rawio, buffer_size=bufsize)\n", "issue": "NpipeSocket.makefile crashes when bufsize < 0\n**Original report**: https://github.com/docker/compose/issues/3901#issuecomment-244828701\n\nNegative `bufsize` should be handled.\n\n", "before_files": [{"content": "import functools\nimport io\n\nimport win32file\nimport win32pipe\n\ncSECURITY_SQOS_PRESENT = 0x100000\ncSECURITY_ANONYMOUS = 0\ncPIPE_READMODE_MESSAGE = 2\n\n\ndef check_closed(f):\n    @functools.wraps(f)\n    def wrapped(self, *args, **kwargs):\n        if self._closed:\n            raise RuntimeError(\n                'Can not reuse socket after connection was closed.'\n            )\n        return f(self, *args, **kwargs)\n    return wrapped\n\n\nclass NpipeSocket(object):\n    \"\"\" Partial implementation of the socket API over windows named pipes.\n        This implementation is only designed to be used as a client socket,\n        and server-specific methods (bind, listen, accept...) are not\n        implemented.\n    \"\"\"\n    def __init__(self, handle=None):\n        self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT\n        self._handle = handle\n        self._closed = False\n\n    def accept(self):\n        raise NotImplementedError()\n\n    def bind(self, address):\n        raise NotImplementedError()\n\n    def close(self):\n        self._handle.Close()\n        self._closed = True\n\n    @check_closed\n    def connect(self, address):\n        win32pipe.WaitNamedPipe(address, self._timeout)\n        handle = win32file.CreateFile(\n            address,\n            win32file.GENERIC_READ | win32file.GENERIC_WRITE,\n            0,\n            None,\n            win32file.OPEN_EXISTING,\n            cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT,\n            0\n        )\n        self.flags = win32pipe.GetNamedPipeInfo(handle)[0]\n\n        self._handle = handle\n        self._address = address\n\n    @check_closed\n    def connect_ex(self, address):\n        return self.connect(address)\n\n    @check_closed\n    def detach(self):\n        self._closed = True\n        return self._handle\n\n    @check_closed\n    def dup(self):\n        return NpipeSocket(self._handle)\n\n    @check_closed\n    def fileno(self):\n        return int(self._handle)\n\n    def getpeername(self):\n        return self._address\n\n    def getsockname(self):\n        return self._address\n\n    def getsockopt(self, level, optname, buflen=None):\n        raise NotImplementedError()\n\n    def ioctl(self, control, option):\n        raise NotImplementedError()\n\n    def listen(self, backlog):\n        raise NotImplementedError()\n\n    def makefile(self, mode=None, bufsize=None):\n        if mode.strip('b') != 'r':\n            raise NotImplementedError()\n        rawio = NpipeFileIOBase(self)\n        if bufsize is None:\n            bufsize = io.DEFAULT_BUFFER_SIZE\n        return io.BufferedReader(rawio, buffer_size=bufsize)\n\n    @check_closed\n    def recv(self, bufsize, flags=0):\n        err, data = win32file.ReadFile(self._handle, bufsize)\n        return data\n\n    @check_closed\n    def recvfrom(self, bufsize, flags=0):\n        data = self.recv(bufsize, flags)\n        return (data, self._address)\n\n    @check_closed\n    def recvfrom_into(self, buf, nbytes=0, flags=0):\n        return self.recv_into(buf, nbytes, flags), self._address\n\n    @check_closed\n    def recv_into(self, buf, nbytes=0):\n        readbuf = buf\n        if not isinstance(buf, memoryview):\n            readbuf = memoryview(buf)\n\n        err, data = win32file.ReadFile(\n            self._handle,\n            readbuf[:nbytes] if nbytes else readbuf\n        )\n        return len(data)\n\n    @check_closed\n    def send(self, string, flags=0):\n        err, nbytes = win32file.WriteFile(self._handle, string)\n        return nbytes\n\n    @check_closed\n    def sendall(self, string, flags=0):\n        return self.send(string, flags)\n\n    @check_closed\n    def sendto(self, string, address):\n        self.connect(address)\n        return self.send(string)\n\n    def setblocking(self, flag):\n        if flag:\n            return self.settimeout(None)\n        return self.settimeout(0)\n\n    def settimeout(self, value):\n        if value is None:\n            self._timeout = win32pipe.NMPWAIT_NOWAIT\n        elif not isinstance(value, (float, int)) or value < 0:\n            raise ValueError('Timeout value out of range')\n        elif value == 0:\n            self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT\n        else:\n            self._timeout = value\n\n    def gettimeout(self):\n        return self._timeout\n\n    def setsockopt(self, level, optname, value):\n        raise NotImplementedError()\n\n    @check_closed\n    def shutdown(self, how):\n        return self.close()\n\n\nclass NpipeFileIOBase(io.RawIOBase):\n    def __init__(self, npipe_socket):\n        self.sock = npipe_socket\n\n    def close(self):\n        super(NpipeFileIOBase, self).close()\n        self.sock = None\n\n    def fileno(self):\n        return self.sock.fileno()\n\n    def isatty(self):\n        return False\n\n    def readable(self):\n        return True\n\n    def readinto(self, buf):\n        return self.sock.recv_into(buf)\n\n    def seekable(self):\n        return False\n\n    def writable(self):\n        return False\n", "path": "docker/transport/npipesocket.py"}], "after_files": [{"content": "import functools\nimport io\n\nimport win32file\nimport win32pipe\n\ncSECURITY_SQOS_PRESENT = 0x100000\ncSECURITY_ANONYMOUS = 0\ncPIPE_READMODE_MESSAGE = 2\n\n\ndef check_closed(f):\n    @functools.wraps(f)\n    def wrapped(self, *args, **kwargs):\n        if self._closed:\n            raise RuntimeError(\n                'Can not reuse socket after connection was closed.'\n            )\n        return f(self, *args, **kwargs)\n    return wrapped\n\n\nclass NpipeSocket(object):\n    \"\"\" Partial implementation of the socket API over windows named pipes.\n        This implementation is only designed to be used as a client socket,\n        and server-specific methods (bind, listen, accept...) are not\n        implemented.\n    \"\"\"\n    def __init__(self, handle=None):\n        self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT\n        self._handle = handle\n        self._closed = False\n\n    def accept(self):\n        raise NotImplementedError()\n\n    def bind(self, address):\n        raise NotImplementedError()\n\n    def close(self):\n        self._handle.Close()\n        self._closed = True\n\n    @check_closed\n    def connect(self, address):\n        win32pipe.WaitNamedPipe(address, self._timeout)\n        handle = win32file.CreateFile(\n            address,\n            win32file.GENERIC_READ | win32file.GENERIC_WRITE,\n            0,\n            None,\n            win32file.OPEN_EXISTING,\n            cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT,\n            0\n        )\n        self.flags = win32pipe.GetNamedPipeInfo(handle)[0]\n\n        self._handle = handle\n        self._address = address\n\n    @check_closed\n    def connect_ex(self, address):\n        return self.connect(address)\n\n    @check_closed\n    def detach(self):\n        self._closed = True\n        return self._handle\n\n    @check_closed\n    def dup(self):\n        return NpipeSocket(self._handle)\n\n    @check_closed\n    def fileno(self):\n        return int(self._handle)\n\n    def getpeername(self):\n        return self._address\n\n    def getsockname(self):\n        return self._address\n\n    def getsockopt(self, level, optname, buflen=None):\n        raise NotImplementedError()\n\n    def ioctl(self, control, option):\n        raise NotImplementedError()\n\n    def listen(self, backlog):\n        raise NotImplementedError()\n\n    def makefile(self, mode=None, bufsize=None):\n        if mode.strip('b') != 'r':\n            raise NotImplementedError()\n        rawio = NpipeFileIOBase(self)\n        if bufsize is None or bufsize < 0:\n            bufsize = io.DEFAULT_BUFFER_SIZE\n        return io.BufferedReader(rawio, buffer_size=bufsize)\n\n    @check_closed\n    def recv(self, bufsize, flags=0):\n        err, data = win32file.ReadFile(self._handle, bufsize)\n        return data\n\n    @check_closed\n    def recvfrom(self, bufsize, flags=0):\n        data = self.recv(bufsize, flags)\n        return (data, self._address)\n\n    @check_closed\n    def recvfrom_into(self, buf, nbytes=0, flags=0):\n        return self.recv_into(buf, nbytes, flags), self._address\n\n    @check_closed\n    def recv_into(self, buf, nbytes=0):\n        readbuf = buf\n        if not isinstance(buf, memoryview):\n            readbuf = memoryview(buf)\n\n        err, data = win32file.ReadFile(\n            self._handle,\n            readbuf[:nbytes] if nbytes else readbuf\n        )\n        return len(data)\n\n    @check_closed\n    def send(self, string, flags=0):\n        err, nbytes = win32file.WriteFile(self._handle, string)\n        return nbytes\n\n    @check_closed\n    def sendall(self, string, flags=0):\n        return self.send(string, flags)\n\n    @check_closed\n    def sendto(self, string, address):\n        self.connect(address)\n        return self.send(string)\n\n    def setblocking(self, flag):\n        if flag:\n            return self.settimeout(None)\n        return self.settimeout(0)\n\n    def settimeout(self, value):\n        if value is None:\n            self._timeout = win32pipe.NMPWAIT_NOWAIT\n        elif not isinstance(value, (float, int)) or value < 0:\n            raise ValueError('Timeout value out of range')\n        elif value == 0:\n            self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT\n        else:\n            self._timeout = value\n\n    def gettimeout(self):\n        return self._timeout\n\n    def setsockopt(self, level, optname, value):\n        raise NotImplementedError()\n\n    @check_closed\n    def shutdown(self, how):\n        return self.close()\n\n\nclass NpipeFileIOBase(io.RawIOBase):\n    def __init__(self, npipe_socket):\n        self.sock = npipe_socket\n\n    def close(self):\n        super(NpipeFileIOBase, self).close()\n        self.sock = None\n\n    def fileno(self):\n        return self.sock.fileno()\n\n    def isatty(self):\n        return False\n\n    def readable(self):\n        return True\n\n    def readinto(self, buf):\n        return self.sock.recv_into(buf)\n\n    def seekable(self):\n        return False\n\n    def writable(self):\n        return False\n", "path": "docker/transport/npipesocket.py"}]}