We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Index out of range in create_wsgi_environ
Gunicorn version 19.4.1
aiohttp version 0.19.0
nginx 1.4.6
Ubuntu 14.04

> [2015-12-03 13:24:27 -0500] [12308] [ERROR] Error handling request
> Traceback (most recent call last):
> File "/home/vagrant/.virtualenvs/mighty/lib/python3.4/site-packages/aiohttp/server.py", line 262, in start
>    yield from self.handle_request(message, payload)
>  File "/home/vagrant/.virtualenvs/mighty/lib/python3.4/site-packages/aiohttp/wsgi.py", line 127, in handle_request
>    environ = self.create_wsgi_environ(message, payload)
>  File "/home/vagrant/.virtualenvs/mighty/lib/python3.4/site-packages/aiohttp/wsgi.py", line 93, in     create_wsgi_environ
>    environ['REMOTE_ADDR'] = remote[0]
> IndexError: index out of range

This change occurred in between the two releases https://github.com/KeepSafe/aiohttp/commit/d904071c30737baa7189ed1c842c76954274c129#diff-58081209a1b73c318d74d4fe7ad41460L91
to 
https://github.com/KeepSafe/aiohttp/commit/eb54e6c010f55c02e49a36cb2e74b077f8aa77e4#diff-58081209a1b73c318d74d4fe7ad41460R92
which may be related to the issue

This gunicorn issue from June 2014 is somewhat similar https://github.com/benoitc/gunicorn/issues/785.

Downgrading to aiohttp 0.18.4 fixes the issue.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `aiohttp/wsgi.py`
Content:
```
1 """wsgi server.
2 
3 TODO:
4   * proxy protocol
5   * x-forward security
6   * wsgi file support (os.sendfile)
7 """
8 
9 import asyncio
10 import inspect
11 import io
12 import os
13 import sys
14 from urllib.parse import urlsplit
15 
16 import aiohttp
17 from aiohttp import server, hdrs
18 
19 __all__ = ('WSGIServerHttpProtocol',)
20 
21 
22 class WSGIServerHttpProtocol(server.ServerHttpProtocol):
23     """HTTP Server that implements the Python WSGI protocol.
24 
25     It uses 'wsgi.async' of 'True'. 'wsgi.input' can behave differently
26     depends on 'readpayload' constructor parameter. If readpayload is set to
27     True, wsgi server reads all incoming data into BytesIO object and
28     sends it as 'wsgi.input' environ var. If readpayload is set to false
29     'wsgi.input' is a StreamReader and application should read incoming
30     data with "yield from environ['wsgi.input'].read()". It defaults to False.
31     """
32 
33     SCRIPT_NAME = os.environ.get('SCRIPT_NAME', '')
34 
35     def __init__(self, app, readpayload=False, is_ssl=False, *args, **kw):
36         super().__init__(*args, **kw)
37 
38         self.wsgi = app
39         self.is_ssl = is_ssl
40         self.readpayload = readpayload
41 
42     def create_wsgi_response(self, message):
43         return WsgiResponse(self.writer, message)
44 
45     def create_wsgi_environ(self, message, payload):
46         uri_parts = urlsplit(message.path)
47         url_scheme = 'https' if self.is_ssl else 'http'
48 
49         environ = {
50             'wsgi.input': payload,
51             'wsgi.errors': sys.stderr,
52             'wsgi.version': (1, 0),
53             'wsgi.async': True,
54             'wsgi.multithread': False,
55             'wsgi.multiprocess': False,
56             'wsgi.run_once': False,
57             'wsgi.file_wrapper': FileWrapper,
58             'wsgi.url_scheme': url_scheme,
59             'SERVER_SOFTWARE': aiohttp.HttpMessage.SERVER_SOFTWARE,
60             'REQUEST_METHOD': message.method,
61             'QUERY_STRING': uri_parts.query or '',
62             'RAW_URI': message.path,
63             'SERVER_PROTOCOL': 'HTTP/%s.%s' % message.version
64         }
65 
66         script_name = self.SCRIPT_NAME
67 
68         for hdr_name, hdr_value in message.headers.items():
69             if hdr_name == 'SCRIPT_NAME':
70                 script_name = hdr_value
71             elif hdr_name == 'CONTENT-TYPE':
72                 environ['CONTENT_TYPE'] = hdr_value
73                 continue
74             elif hdr_name == 'CONTENT-LENGTH':
75                 environ['CONTENT_LENGTH'] = hdr_value
76                 continue
77 
78             key = 'HTTP_%s' % hdr_name.replace('-', '_')
79             if key in environ:
80                 hdr_value = '%s,%s' % (environ[key], hdr_value)
81 
82             environ[key] = hdr_value
83 
84         # authors should be aware that REMOTE_HOST and REMOTE_ADDR
85         # may not qualify the remote addr
86         # also SERVER_PORT variable MUST be set to the TCP/IP port number on
87         # which this request is received from the client.
88         # http://www.ietf.org/rfc/rfc3875
89 
90         remote = self.transport.get_extra_info('peername')
91         environ['REMOTE_ADDR'] = remote[0]
92         environ['REMOTE_PORT'] = remote[1]
93 
94         sockname = self.transport.get_extra_info('sockname')
95         environ['SERVER_PORT'] = str(sockname[1])
96         host = message.headers.get("HOST", None)
97         if host:
98             environ['SERVER_NAME'] = host.split(":")[0]
99         else:
100             environ['SERVER_NAME'] = sockname[0]
101 
102         path_info = uri_parts.path
103         if script_name:
104             path_info = path_info.split(script_name, 1)[-1]
105 
106         environ['PATH_INFO'] = path_info
107         environ['SCRIPT_NAME'] = script_name
108 
109         environ['async.reader'] = self.reader
110         environ['async.writer'] = self.writer
111 
112         return environ
113 
114     @asyncio.coroutine
115     def handle_request(self, message, payload):
116         """Handle a single HTTP request"""
117         now = self._loop.time()
118 
119         if self.readpayload:
120             wsgiinput = io.BytesIO()
121             wsgiinput.write((yield from payload.read()))
122             wsgiinput.seek(0)
123             payload = wsgiinput
124 
125         environ = self.create_wsgi_environ(message, payload)
126         response = self.create_wsgi_response(message)
127 
128         riter = self.wsgi(environ, response.start_response)
129         if isinstance(riter, asyncio.Future) or inspect.isgenerator(riter):
130             riter = yield from riter
131 
132         resp = response.response
133         try:
134             for item in riter:
135                 if isinstance(item, asyncio.Future):
136                     item = yield from item
137                 yield from resp.write(item)
138 
139             yield from resp.write_eof()
140         finally:
141             if hasattr(riter, 'close'):
142                 riter.close()
143 
144         if resp.keep_alive():
145             self.keep_alive(True)
146 
147         self.log_access(
148             message, environ, response.response, self._loop.time() - now)
149 
150 
151 class FileWrapper:
152     """Custom file wrapper."""
153 
154     def __init__(self, fobj, chunk_size=8192):
155         self.fobj = fobj
156         self.chunk_size = chunk_size
157         if hasattr(fobj, 'close'):
158             self.close = fobj.close
159 
160     def __iter__(self):
161         return self
162 
163     def __next__(self):
164         data = self.fobj.read(self.chunk_size)
165         if data:
166             return data
167         raise StopIteration
168 
169 
170 class WsgiResponse:
171     """Implementation of start_response() callable as specified by PEP 3333"""
172 
173     status = None
174 
175     HOP_HEADERS = {
176         hdrs.CONNECTION,
177         hdrs.KEEP_ALIVE,
178         hdrs.PROXY_AUTHENTICATE,
179         hdrs.PROXY_AUTHORIZATION,
180         hdrs.TE,
181         hdrs.TRAILER,
182         hdrs.TRANSFER_ENCODING,
183         hdrs.UPGRADE,
184     }
185 
186     def __init__(self, writer, message):
187         self.writer = writer
188         self.message = message
189 
190     def start_response(self, status, headers, exc_info=None):
191         if exc_info:
192             try:
193                 if self.status:
194                     raise exc_info[1]
195             finally:
196                 exc_info = None
197 
198         status_code = int(status.split(' ', 1)[0])
199 
200         self.status = status
201         resp = self.response = aiohttp.Response(
202             self.writer, status_code,
203             self.message.version, self.message.should_close)
204         resp.HOP_HEADERS = self.HOP_HEADERS
205         resp.add_headers(*headers)
206 
207         if resp.has_chunked_hdr:
208             resp.enable_chunked_encoding()
209 
210         # send headers immediately for websocket connection
211         if status_code == 101 and resp.upgrade and resp.websocket:
212             resp.send_headers()
213         else:
214             resp._send_headers = True
215         return self.response.write
216
```
--- 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/aiohttp/wsgi.py b/aiohttp/wsgi.py
--- a/aiohttp/wsgi.py
+++ b/aiohttp/wsgi.py
@@ -88,16 +88,22 @@
         # http://www.ietf.org/rfc/rfc3875
 
         remote = self.transport.get_extra_info('peername')
-        environ['REMOTE_ADDR'] = remote[0]
-        environ['REMOTE_PORT'] = remote[1]
-
-        sockname = self.transport.get_extra_info('sockname')
-        environ['SERVER_PORT'] = str(sockname[1])
-        host = message.headers.get("HOST", None)
-        if host:
-            environ['SERVER_NAME'] = host.split(":")[0]
+        if remote:
+            environ['REMOTE_ADDR'] = remote[0]
+            environ['REMOTE_PORT'] = remote[1]
+            _host, port = self.transport.get_extra_info('sockname')
+            environ['SERVER_PORT'] = str(port)
+            host = message.headers.get("HOST", None)
+            # SERVER_NAME should be set to value of Host header, but this
+            # header is not required. In this case we shoud set it to local
+            # address of socket
+            environ['SERVER_NAME'] = host.split(":")[0] if host else _host
         else:
-            environ['SERVER_NAME'] = sockname[0]
+            # Dealing with unix socket, so request was received from client by
+            # upstream server and this data may be found in the headers
+            for header in ('REMOTE_ADDR', 'REMOTE_PORT',
+                           'SERVER_NAME', 'SERVER_PORT'):
+                environ[header] = message.headers.get(header, '')
 
         path_info = uri_parts.path
         if script_name:

{"golden_diff": "diff --git a/aiohttp/wsgi.py b/aiohttp/wsgi.py\n--- a/aiohttp/wsgi.py\n+++ b/aiohttp/wsgi.py\n@@ -88,16 +88,22 @@\n         # http://www.ietf.org/rfc/rfc3875\n \n         remote = self.transport.get_extra_info('peername')\n-        environ['REMOTE_ADDR'] = remote[0]\n-        environ['REMOTE_PORT'] = remote[1]\n-\n-        sockname = self.transport.get_extra_info('sockname')\n-        environ['SERVER_PORT'] = str(sockname[1])\n-        host = message.headers.get(\"HOST\", None)\n-        if host:\n-            environ['SERVER_NAME'] = host.split(\":\")[0]\n+        if remote:\n+            environ['REMOTE_ADDR'] = remote[0]\n+            environ['REMOTE_PORT'] = remote[1]\n+            _host, port = self.transport.get_extra_info('sockname')\n+            environ['SERVER_PORT'] = str(port)\n+            host = message.headers.get(\"HOST\", None)\n+            # SERVER_NAME should be set to value of Host header, but this\n+            # header is not required. In this case we shoud set it to local\n+            # address of socket\n+            environ['SERVER_NAME'] = host.split(\":\")[0] if host else _host\n         else:\n-            environ['SERVER_NAME'] = sockname[0]\n+            # Dealing with unix socket, so request was received from client by\n+            # upstream server and this data may be found in the headers\n+            for header in ('REMOTE_ADDR', 'REMOTE_PORT',\n+                           'SERVER_NAME', 'SERVER_PORT'):\n+                environ[header] = message.headers.get(header, '')\n \n         path_info = uri_parts.path\n         if script_name:\n", "issue": "Index out of range in create_wsgi_environ\nGunicorn version 19.4.1\naiohttp version 0.19.0\nnginx 1.4.6\nUbuntu 14.04\n\n> [2015-12-03 13:24:27 -0500] [12308] [ERROR] Error handling request\n> Traceback (most recent call last):\n> File \"/home/vagrant/.virtualenvs/mighty/lib/python3.4/site-packages/aiohttp/server.py\", line 262, in start\n>    yield from self.handle_request(message, payload)\n>  File \"/home/vagrant/.virtualenvs/mighty/lib/python3.4/site-packages/aiohttp/wsgi.py\", line 127, in handle_request\n>    environ = self.create_wsgi_environ(message, payload)\n>  File \"/home/vagrant/.virtualenvs/mighty/lib/python3.4/site-packages/aiohttp/wsgi.py\", line 93, in     create_wsgi_environ\n>    environ['REMOTE_ADDR'] = remote[0]\n> IndexError: index out of range\n\nThis change occurred in between the two releases https://github.com/KeepSafe/aiohttp/commit/d904071c30737baa7189ed1c842c76954274c129#diff-58081209a1b73c318d74d4fe7ad41460L91\nto \nhttps://github.com/KeepSafe/aiohttp/commit/eb54e6c010f55c02e49a36cb2e74b077f8aa77e4#diff-58081209a1b73c318d74d4fe7ad41460R92\nwhich may be related to the issue\n\nThis gunicorn issue from June 2014 is somewhat similar https://github.com/benoitc/gunicorn/issues/785.\n\nDowngrading to aiohttp 0.18.4 fixes the issue.\n\n", "before_files": [{"content": "\"\"\"wsgi server.\n\nTODO:\n  * proxy protocol\n  * x-forward security\n  * wsgi file support (os.sendfile)\n\"\"\"\n\nimport asyncio\nimport inspect\nimport io\nimport os\nimport sys\nfrom urllib.parse import urlsplit\n\nimport aiohttp\nfrom aiohttp import server, hdrs\n\n__all__ = ('WSGIServerHttpProtocol',)\n\n\nclass WSGIServerHttpProtocol(server.ServerHttpProtocol):\n    \"\"\"HTTP Server that implements the Python WSGI protocol.\n\n    It uses 'wsgi.async' of 'True'. 'wsgi.input' can behave differently\n    depends on 'readpayload' constructor parameter. If readpayload is set to\n    True, wsgi server reads all incoming data into BytesIO object and\n    sends it as 'wsgi.input' environ var. If readpayload is set to false\n    'wsgi.input' is a StreamReader and application should read incoming\n    data with \"yield from environ['wsgi.input'].read()\". It defaults to False.\n    \"\"\"\n\n    SCRIPT_NAME = os.environ.get('SCRIPT_NAME', '')\n\n    def __init__(self, app, readpayload=False, is_ssl=False, *args, **kw):\n        super().__init__(*args, **kw)\n\n        self.wsgi = app\n        self.is_ssl = is_ssl\n        self.readpayload = readpayload\n\n    def create_wsgi_response(self, message):\n        return WsgiResponse(self.writer, message)\n\n    def create_wsgi_environ(self, message, payload):\n        uri_parts = urlsplit(message.path)\n        url_scheme = 'https' if self.is_ssl else 'http'\n\n        environ = {\n            'wsgi.input': payload,\n            'wsgi.errors': sys.stderr,\n            'wsgi.version': (1, 0),\n            'wsgi.async': True,\n            'wsgi.multithread': False,\n            'wsgi.multiprocess': False,\n            'wsgi.run_once': False,\n            'wsgi.file_wrapper': FileWrapper,\n            'wsgi.url_scheme': url_scheme,\n            'SERVER_SOFTWARE': aiohttp.HttpMessage.SERVER_SOFTWARE,\n            'REQUEST_METHOD': message.method,\n            'QUERY_STRING': uri_parts.query or '',\n            'RAW_URI': message.path,\n            'SERVER_PROTOCOL': 'HTTP/%s.%s' % message.version\n        }\n\n        script_name = self.SCRIPT_NAME\n\n        for hdr_name, hdr_value in message.headers.items():\n            if hdr_name == 'SCRIPT_NAME':\n                script_name = hdr_value\n            elif hdr_name == 'CONTENT-TYPE':\n                environ['CONTENT_TYPE'] = hdr_value\n                continue\n            elif hdr_name == 'CONTENT-LENGTH':\n                environ['CONTENT_LENGTH'] = hdr_value\n                continue\n\n            key = 'HTTP_%s' % hdr_name.replace('-', '_')\n            if key in environ:\n                hdr_value = '%s,%s' % (environ[key], hdr_value)\n\n            environ[key] = hdr_value\n\n        # authors should be aware that REMOTE_HOST and REMOTE_ADDR\n        # may not qualify the remote addr\n        # also SERVER_PORT variable MUST be set to the TCP/IP port number on\n        # which this request is received from the client.\n        # http://www.ietf.org/rfc/rfc3875\n\n        remote = self.transport.get_extra_info('peername')\n        environ['REMOTE_ADDR'] = remote[0]\n        environ['REMOTE_PORT'] = remote[1]\n\n        sockname = self.transport.get_extra_info('sockname')\n        environ['SERVER_PORT'] = str(sockname[1])\n        host = message.headers.get(\"HOST\", None)\n        if host:\n            environ['SERVER_NAME'] = host.split(\":\")[0]\n        else:\n            environ['SERVER_NAME'] = sockname[0]\n\n        path_info = uri_parts.path\n        if script_name:\n            path_info = path_info.split(script_name, 1)[-1]\n\n        environ['PATH_INFO'] = path_info\n        environ['SCRIPT_NAME'] = script_name\n\n        environ['async.reader'] = self.reader\n        environ['async.writer'] = self.writer\n\n        return environ\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        \"\"\"Handle a single HTTP request\"\"\"\n        now = self._loop.time()\n\n        if self.readpayload:\n            wsgiinput = io.BytesIO()\n            wsgiinput.write((yield from payload.read()))\n            wsgiinput.seek(0)\n            payload = wsgiinput\n\n        environ = self.create_wsgi_environ(message, payload)\n        response = self.create_wsgi_response(message)\n\n        riter = self.wsgi(environ, response.start_response)\n        if isinstance(riter, asyncio.Future) or inspect.isgenerator(riter):\n            riter = yield from riter\n\n        resp = response.response\n        try:\n            for item in riter:\n                if isinstance(item, asyncio.Future):\n                    item = yield from item\n                yield from resp.write(item)\n\n            yield from resp.write_eof()\n        finally:\n            if hasattr(riter, 'close'):\n                riter.close()\n\n        if resp.keep_alive():\n            self.keep_alive(True)\n\n        self.log_access(\n            message, environ, response.response, self._loop.time() - now)\n\n\nclass FileWrapper:\n    \"\"\"Custom file wrapper.\"\"\"\n\n    def __init__(self, fobj, chunk_size=8192):\n        self.fobj = fobj\n        self.chunk_size = chunk_size\n        if hasattr(fobj, 'close'):\n            self.close = fobj.close\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        data = self.fobj.read(self.chunk_size)\n        if data:\n            return data\n        raise StopIteration\n\n\nclass WsgiResponse:\n    \"\"\"Implementation of start_response() callable as specified by PEP 3333\"\"\"\n\n    status = None\n\n    HOP_HEADERS = {\n        hdrs.CONNECTION,\n        hdrs.KEEP_ALIVE,\n        hdrs.PROXY_AUTHENTICATE,\n        hdrs.PROXY_AUTHORIZATION,\n        hdrs.TE,\n        hdrs.TRAILER,\n        hdrs.TRANSFER_ENCODING,\n        hdrs.UPGRADE,\n    }\n\n    def __init__(self, writer, message):\n        self.writer = writer\n        self.message = message\n\n    def start_response(self, status, headers, exc_info=None):\n        if exc_info:\n            try:\n                if self.status:\n                    raise exc_info[1]\n            finally:\n                exc_info = None\n\n        status_code = int(status.split(' ', 1)[0])\n\n        self.status = status\n        resp = self.response = aiohttp.Response(\n            self.writer, status_code,\n            self.message.version, self.message.should_close)\n        resp.HOP_HEADERS = self.HOP_HEADERS\n        resp.add_headers(*headers)\n\n        if resp.has_chunked_hdr:\n            resp.enable_chunked_encoding()\n\n        # send headers immediately for websocket connection\n        if status_code == 101 and resp.upgrade and resp.websocket:\n            resp.send_headers()\n        else:\n            resp._send_headers = True\n        return self.response.write\n", "path": "aiohttp/wsgi.py"}], "after_files": [{"content": "\"\"\"wsgi server.\n\nTODO:\n  * proxy protocol\n  * x-forward security\n  * wsgi file support (os.sendfile)\n\"\"\"\n\nimport asyncio\nimport inspect\nimport io\nimport os\nimport sys\nfrom urllib.parse import urlsplit\n\nimport aiohttp\nfrom aiohttp import server, hdrs\n\n__all__ = ('WSGIServerHttpProtocol',)\n\n\nclass WSGIServerHttpProtocol(server.ServerHttpProtocol):\n    \"\"\"HTTP Server that implements the Python WSGI protocol.\n\n    It uses 'wsgi.async' of 'True'. 'wsgi.input' can behave differently\n    depends on 'readpayload' constructor parameter. If readpayload is set to\n    True, wsgi server reads all incoming data into BytesIO object and\n    sends it as 'wsgi.input' environ var. If readpayload is set to false\n    'wsgi.input' is a StreamReader and application should read incoming\n    data with \"yield from environ['wsgi.input'].read()\". It defaults to False.\n    \"\"\"\n\n    SCRIPT_NAME = os.environ.get('SCRIPT_NAME', '')\n\n    def __init__(self, app, readpayload=False, is_ssl=False, *args, **kw):\n        super().__init__(*args, **kw)\n\n        self.wsgi = app\n        self.is_ssl = is_ssl\n        self.readpayload = readpayload\n\n    def create_wsgi_response(self, message):\n        return WsgiResponse(self.writer, message)\n\n    def create_wsgi_environ(self, message, payload):\n        uri_parts = urlsplit(message.path)\n        url_scheme = 'https' if self.is_ssl else 'http'\n\n        environ = {\n            'wsgi.input': payload,\n            'wsgi.errors': sys.stderr,\n            'wsgi.version': (1, 0),\n            'wsgi.async': True,\n            'wsgi.multithread': False,\n            'wsgi.multiprocess': False,\n            'wsgi.run_once': False,\n            'wsgi.file_wrapper': FileWrapper,\n            'wsgi.url_scheme': url_scheme,\n            'SERVER_SOFTWARE': aiohttp.HttpMessage.SERVER_SOFTWARE,\n            'REQUEST_METHOD': message.method,\n            'QUERY_STRING': uri_parts.query or '',\n            'RAW_URI': message.path,\n            'SERVER_PROTOCOL': 'HTTP/%s.%s' % message.version\n        }\n\n        script_name = self.SCRIPT_NAME\n\n        for hdr_name, hdr_value in message.headers.items():\n            if hdr_name == 'SCRIPT_NAME':\n                script_name = hdr_value\n            elif hdr_name == 'CONTENT-TYPE':\n                environ['CONTENT_TYPE'] = hdr_value\n                continue\n            elif hdr_name == 'CONTENT-LENGTH':\n                environ['CONTENT_LENGTH'] = hdr_value\n                continue\n\n            key = 'HTTP_%s' % hdr_name.replace('-', '_')\n            if key in environ:\n                hdr_value = '%s,%s' % (environ[key], hdr_value)\n\n            environ[key] = hdr_value\n\n        # authors should be aware that REMOTE_HOST and REMOTE_ADDR\n        # may not qualify the remote addr\n        # also SERVER_PORT variable MUST be set to the TCP/IP port number on\n        # which this request is received from the client.\n        # http://www.ietf.org/rfc/rfc3875\n\n        remote = self.transport.get_extra_info('peername')\n        if remote:\n            environ['REMOTE_ADDR'] = remote[0]\n            environ['REMOTE_PORT'] = remote[1]\n            _host, port = self.transport.get_extra_info('sockname')\n            environ['SERVER_PORT'] = str(port)\n            host = message.headers.get(\"HOST\", None)\n            # SERVER_NAME should be set to value of Host header, but this\n            # header is not required. In this case we shoud set it to local\n            # address of socket\n            environ['SERVER_NAME'] = host.split(\":\")[0] if host else _host\n        else:\n            # Dealing with unix socket, so request was received from client by\n            # upstream server and this data may be found in the headers\n            for header in ('REMOTE_ADDR', 'REMOTE_PORT',\n                           'SERVER_NAME', 'SERVER_PORT'):\n                environ[header] = message.headers.get(header, '')\n\n        path_info = uri_parts.path\n        if script_name:\n            path_info = path_info.split(script_name, 1)[-1]\n\n        environ['PATH_INFO'] = path_info\n        environ['SCRIPT_NAME'] = script_name\n\n        environ['async.reader'] = self.reader\n        environ['async.writer'] = self.writer\n\n        return environ\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        \"\"\"Handle a single HTTP request\"\"\"\n        now = self._loop.time()\n\n        if self.readpayload:\n            wsgiinput = io.BytesIO()\n            wsgiinput.write((yield from payload.read()))\n            wsgiinput.seek(0)\n            payload = wsgiinput\n\n        environ = self.create_wsgi_environ(message, payload)\n        response = self.create_wsgi_response(message)\n\n        riter = self.wsgi(environ, response.start_response)\n        if isinstance(riter, asyncio.Future) or inspect.isgenerator(riter):\n            riter = yield from riter\n\n        resp = response.response\n        try:\n            for item in riter:\n                if isinstance(item, asyncio.Future):\n                    item = yield from item\n                yield from resp.write(item)\n\n            yield from resp.write_eof()\n        finally:\n            if hasattr(riter, 'close'):\n                riter.close()\n\n        if resp.keep_alive():\n            self.keep_alive(True)\n\n        self.log_access(\n            message, environ, response.response, self._loop.time() - now)\n\n\nclass FileWrapper:\n    \"\"\"Custom file wrapper.\"\"\"\n\n    def __init__(self, fobj, chunk_size=8192):\n        self.fobj = fobj\n        self.chunk_size = chunk_size\n        if hasattr(fobj, 'close'):\n            self.close = fobj.close\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        data = self.fobj.read(self.chunk_size)\n        if data:\n            return data\n        raise StopIteration\n\n\nclass WsgiResponse:\n    \"\"\"Implementation of start_response() callable as specified by PEP 3333\"\"\"\n\n    status = None\n\n    HOP_HEADERS = {\n        hdrs.CONNECTION,\n        hdrs.KEEP_ALIVE,\n        hdrs.PROXY_AUTHENTICATE,\n        hdrs.PROXY_AUTHORIZATION,\n        hdrs.TE,\n        hdrs.TRAILER,\n        hdrs.TRANSFER_ENCODING,\n        hdrs.UPGRADE,\n    }\n\n    def __init__(self, writer, message):\n        self.writer = writer\n        self.message = message\n\n    def start_response(self, status, headers, exc_info=None):\n        if exc_info:\n            try:\n                if self.status:\n                    raise exc_info[1]\n            finally:\n                exc_info = None\n\n        status_code = int(status.split(' ', 1)[0])\n\n        self.status = status\n        resp = self.response = aiohttp.Response(\n            self.writer, status_code,\n            self.message.version, self.message.should_close)\n        resp.HOP_HEADERS = self.HOP_HEADERS\n        resp.add_headers(*headers)\n\n        if resp.has_chunked_hdr:\n            resp.enable_chunked_encoding()\n\n        # send headers immediately for websocket connection\n        if status_code == 101 and resp.upgrade and resp.websocket:\n            resp.send_headers()\n        else:\n            resp._send_headers = True\n        return self.response.write\n", "path": "aiohttp/wsgi.py"}]}