We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Wrong HTTP status code on Request Header Fields Too Large
When the request header gets too large (e.g. a lot of cookies), gunicorn returns HTTP 400 instead of HTTP 431, which can mask the real problem through proxies. Gunicorn should return the right HTTP error code.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `gunicorn/workers/base.py`
Content:
```
1 # -*- coding: utf-8 -
2 #
3 # This file is part of gunicorn released under the MIT license.
4 # See the NOTICE for more information.
5 
6 import io
7 import os
8 import signal
9 import sys
10 import time
11 import traceback
12 from datetime import datetime
13 from random import randint
14 from ssl import SSLError
15 
16 from gunicorn import util
17 from gunicorn.http.errors import (
18     ForbiddenProxyRequest, InvalidHeader,
19     InvalidHeaderName, InvalidHTTPVersion,
20     InvalidProxyLine, InvalidRequestLine,
21     InvalidRequestMethod, InvalidSchemeHeaders,
22     LimitRequestHeaders, LimitRequestLine,
23 )
24 from gunicorn.http.wsgi import Response, default_environ
25 from gunicorn.reloader import reloader_engines
26 from gunicorn.workers.workertmp import WorkerTmp
27 
28 
29 class Worker(object):
30 
31     SIGNALS = [getattr(signal, "SIG%s" % x) for x in (
32         "ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD".split()
33     )]
34 
35     PIPE = []
36 
37     def __init__(self, age, ppid, sockets, app, timeout, cfg, log):
38         """\
39         This is called pre-fork so it shouldn't do anything to the
40         current process. If there's a need to make process wide
41         changes you'll want to do that in ``self.init_process()``.
42         """
43         self.age = age
44         self.pid = "[booting]"
45         self.ppid = ppid
46         self.sockets = sockets
47         self.app = app
48         self.timeout = timeout
49         self.cfg = cfg
50         self.booted = False
51         self.aborted = False
52         self.reloader = None
53 
54         self.nr = 0
55 
56         if cfg.max_requests > 0:
57             jitter = randint(0, cfg.max_requests_jitter)
58             self.max_requests = cfg.max_requests + jitter
59         else:
60             self.max_requests = sys.maxsize
61 
62         self.alive = True
63         self.log = log
64         self.tmp = WorkerTmp(cfg)
65 
66     def __str__(self):
67         return "<Worker %s>" % self.pid
68 
69     def notify(self):
70         """\
71         Your worker subclass must arrange to have this method called
72         once every ``self.timeout`` seconds. If you fail in accomplishing
73         this task, the master process will murder your workers.
74         """
75         self.tmp.notify()
76 
77     def run(self):
78         """\
79         This is the mainloop of a worker process. You should override
80         this method in a subclass to provide the intended behaviour
81         for your particular evil schemes.
82         """
83         raise NotImplementedError()
84 
85     def init_process(self):
86         """\
87         If you override this method in a subclass, the last statement
88         in the function should be to call this method with
89         super().init_process() so that the ``run()`` loop is initiated.
90         """
91 
92         # set environment' variables
93         if self.cfg.env:
94             for k, v in self.cfg.env.items():
95                 os.environ[k] = v
96 
97         util.set_owner_process(self.cfg.uid, self.cfg.gid,
98                                initgroups=self.cfg.initgroups)
99 
100         # Reseed the random number generator
101         util.seed()
102 
103         # For waking ourselves up
104         self.PIPE = os.pipe()
105         for p in self.PIPE:
106             util.set_non_blocking(p)
107             util.close_on_exec(p)
108 
109         # Prevent fd inheritance
110         for s in self.sockets:
111             util.close_on_exec(s)
112         util.close_on_exec(self.tmp.fileno())
113 
114         self.wait_fds = self.sockets + [self.PIPE[0]]
115 
116         self.log.close_on_exec()
117 
118         self.init_signals()
119 
120         # start the reloader
121         if self.cfg.reload:
122             def changed(fname):
123                 self.log.info("Worker reloading: %s modified", fname)
124                 self.alive = False
125                 os.write(self.PIPE[1], b"1")
126                 self.cfg.worker_int(self)
127                 time.sleep(0.1)
128                 sys.exit(0)
129 
130             reloader_cls = reloader_engines[self.cfg.reload_engine]
131             self.reloader = reloader_cls(extra_files=self.cfg.reload_extra_files,
132                                          callback=changed)
133 
134         self.load_wsgi()
135         if self.reloader:
136             self.reloader.start()
137 
138         self.cfg.post_worker_init(self)
139 
140         # Enter main run loop
141         self.booted = True
142         self.run()
143 
144     def load_wsgi(self):
145         try:
146             self.wsgi = self.app.wsgi()
147         except SyntaxError as e:
148             if not self.cfg.reload:
149                 raise
150 
151             self.log.exception(e)
152 
153             # fix from PR #1228
154             # storing the traceback into exc_tb will create a circular reference.
155             # per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
156             # delete the traceback after use.
157             try:
158                 _, exc_val, exc_tb = sys.exc_info()
159                 self.reloader.add_extra_file(exc_val.filename)
160 
161                 tb_string = io.StringIO()
162                 traceback.print_tb(exc_tb, file=tb_string)
163                 self.wsgi = util.make_fail_app(tb_string.getvalue())
164             finally:
165                 del exc_tb
166 
167     def init_signals(self):
168         # reset signaling
169         for s in self.SIGNALS:
170             signal.signal(s, signal.SIG_DFL)
171         # init new signaling
172         signal.signal(signal.SIGQUIT, self.handle_quit)
173         signal.signal(signal.SIGTERM, self.handle_exit)
174         signal.signal(signal.SIGINT, self.handle_quit)
175         signal.signal(signal.SIGWINCH, self.handle_winch)
176         signal.signal(signal.SIGUSR1, self.handle_usr1)
177         signal.signal(signal.SIGABRT, self.handle_abort)
178 
179         # Don't let SIGTERM and SIGUSR1 disturb active requests
180         # by interrupting system calls
181         signal.siginterrupt(signal.SIGTERM, False)
182         signal.siginterrupt(signal.SIGUSR1, False)
183 
184         if hasattr(signal, 'set_wakeup_fd'):
185             signal.set_wakeup_fd(self.PIPE[1])
186 
187     def handle_usr1(self, sig, frame):
188         self.log.reopen_files()
189 
190     def handle_exit(self, sig, frame):
191         self.alive = False
192 
193     def handle_quit(self, sig, frame):
194         self.alive = False
195         # worker_int callback
196         self.cfg.worker_int(self)
197         time.sleep(0.1)
198         sys.exit(0)
199 
200     def handle_abort(self, sig, frame):
201         self.alive = False
202         self.cfg.worker_abort(self)
203         sys.exit(1)
204 
205     def handle_error(self, req, client, addr, exc):
206         request_start = datetime.now()
207         addr = addr or ('', -1)  # unix socket case
208         if isinstance(exc, (
209             InvalidRequestLine, InvalidRequestMethod,
210             InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,
211             LimitRequestLine, LimitRequestHeaders,
212             InvalidProxyLine, ForbiddenProxyRequest,
213             InvalidSchemeHeaders,
214             SSLError,
215         )):
216 
217             status_int = 400
218             reason = "Bad Request"
219 
220             if isinstance(exc, InvalidRequestLine):
221                 mesg = "Invalid Request Line '%s'" % str(exc)
222             elif isinstance(exc, InvalidRequestMethod):
223                 mesg = "Invalid Method '%s'" % str(exc)
224             elif isinstance(exc, InvalidHTTPVersion):
225                 mesg = "Invalid HTTP Version '%s'" % str(exc)
226             elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)):
227                 mesg = "%s" % str(exc)
228                 if not req and hasattr(exc, "req"):
229                     req = exc.req  # for access log
230             elif isinstance(exc, LimitRequestLine):
231                 mesg = "%s" % str(exc)
232             elif isinstance(exc, LimitRequestHeaders):
233                 mesg = "Error parsing headers: '%s'" % str(exc)
234             elif isinstance(exc, InvalidProxyLine):
235                 mesg = "'%s'" % str(exc)
236             elif isinstance(exc, ForbiddenProxyRequest):
237                 reason = "Forbidden"
238                 mesg = "Request forbidden"
239                 status_int = 403
240             elif isinstance(exc, InvalidSchemeHeaders):
241                 mesg = "%s" % str(exc)
242             elif isinstance(exc, SSLError):
243                 reason = "Forbidden"
244                 mesg = "'%s'" % str(exc)
245                 status_int = 403
246 
247             msg = "Invalid request from ip={ip}: {error}"
248             self.log.debug(msg.format(ip=addr[0], error=str(exc)))
249         else:
250             if hasattr(req, "uri"):
251                 self.log.exception("Error handling request %s", req.uri)
252             status_int = 500
253             reason = "Internal Server Error"
254             mesg = ""
255 
256         if req is not None:
257             request_time = datetime.now() - request_start
258             environ = default_environ(req, client, self.cfg)
259             environ['REMOTE_ADDR'] = addr[0]
260             environ['REMOTE_PORT'] = str(addr[1])
261             resp = Response(req, client, self.cfg)
262             resp.status = "%s %s" % (status_int, reason)
263             resp.response_length = len(mesg)
264             self.log.access(resp, req, environ, request_time)
265 
266         try:
267             util.write_error(client, status_int, reason, mesg)
268         except Exception:
269             self.log.debug("Failed to send error message.")
270 
271     def handle_winch(self, sig, fname):
272         # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.
273         self.log.debug("worker: SIGWINCH ignored.")
274
```
--- 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/gunicorn/workers/base.py b/gunicorn/workers/base.py
--- a/gunicorn/workers/base.py
+++ b/gunicorn/workers/base.py
@@ -230,7 +230,9 @@
             elif isinstance(exc, LimitRequestLine):
                 mesg = "%s" % str(exc)
             elif isinstance(exc, LimitRequestHeaders):
+                reason = "Request Header Fields Too Large"
                 mesg = "Error parsing headers: '%s'" % str(exc)
+                status_int = 431
             elif isinstance(exc, InvalidProxyLine):
                 mesg = "'%s'" % str(exc)
             elif isinstance(exc, ForbiddenProxyRequest):

{"golden_diff": "diff --git a/gunicorn/workers/base.py b/gunicorn/workers/base.py\n--- a/gunicorn/workers/base.py\n+++ b/gunicorn/workers/base.py\n@@ -230,7 +230,9 @@\n             elif isinstance(exc, LimitRequestLine):\n                 mesg = \"%s\" % str(exc)\n             elif isinstance(exc, LimitRequestHeaders):\n+                reason = \"Request Header Fields Too Large\"\n                 mesg = \"Error parsing headers: '%s'\" % str(exc)\n+                status_int = 431\n             elif isinstance(exc, InvalidProxyLine):\n                 mesg = \"'%s'\" % str(exc)\n             elif isinstance(exc, ForbiddenProxyRequest):\n", "issue": "Wrong HTTP status code on Request Header Fields Too Large\nWhen the request header gets too large (e.g. a lot of cookies), gunicorn returns HTTP 400 instead of HTTP 431, which can mask the real problem through proxies. Gunicorn should return the right HTTP error code.\n", "before_files": [{"content": "# -*- coding: utf-8 -\n#\n# This file is part of gunicorn released under the MIT license.\n# See the NOTICE for more information.\n\nimport io\nimport os\nimport signal\nimport sys\nimport time\nimport traceback\nfrom datetime import datetime\nfrom random import randint\nfrom ssl import SSLError\n\nfrom gunicorn import util\nfrom gunicorn.http.errors import (\n    ForbiddenProxyRequest, InvalidHeader,\n    InvalidHeaderName, InvalidHTTPVersion,\n    InvalidProxyLine, InvalidRequestLine,\n    InvalidRequestMethod, InvalidSchemeHeaders,\n    LimitRequestHeaders, LimitRequestLine,\n)\nfrom gunicorn.http.wsgi import Response, default_environ\nfrom gunicorn.reloader import reloader_engines\nfrom gunicorn.workers.workertmp import WorkerTmp\n\n\nclass Worker(object):\n\n    SIGNALS = [getattr(signal, \"SIG%s\" % x) for x in (\n        \"ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD\".split()\n    )]\n\n    PIPE = []\n\n    def __init__(self, age, ppid, sockets, app, timeout, cfg, log):\n        \"\"\"\\\n        This is called pre-fork so it shouldn't do anything to the\n        current process. If there's a need to make process wide\n        changes you'll want to do that in ``self.init_process()``.\n        \"\"\"\n        self.age = age\n        self.pid = \"[booting]\"\n        self.ppid = ppid\n        self.sockets = sockets\n        self.app = app\n        self.timeout = timeout\n        self.cfg = cfg\n        self.booted = False\n        self.aborted = False\n        self.reloader = None\n\n        self.nr = 0\n\n        if cfg.max_requests > 0:\n            jitter = randint(0, cfg.max_requests_jitter)\n            self.max_requests = cfg.max_requests + jitter\n        else:\n            self.max_requests = sys.maxsize\n\n        self.alive = True\n        self.log = log\n        self.tmp = WorkerTmp(cfg)\n\n    def __str__(self):\n        return \"<Worker %s>\" % self.pid\n\n    def notify(self):\n        \"\"\"\\\n        Your worker subclass must arrange to have this method called\n        once every ``self.timeout`` seconds. If you fail in accomplishing\n        this task, the master process will murder your workers.\n        \"\"\"\n        self.tmp.notify()\n\n    def run(self):\n        \"\"\"\\\n        This is the mainloop of a worker process. You should override\n        this method in a subclass to provide the intended behaviour\n        for your particular evil schemes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def init_process(self):\n        \"\"\"\\\n        If you override this method in a subclass, the last statement\n        in the function should be to call this method with\n        super().init_process() so that the ``run()`` loop is initiated.\n        \"\"\"\n\n        # set environment' variables\n        if self.cfg.env:\n            for k, v in self.cfg.env.items():\n                os.environ[k] = v\n\n        util.set_owner_process(self.cfg.uid, self.cfg.gid,\n                               initgroups=self.cfg.initgroups)\n\n        # Reseed the random number generator\n        util.seed()\n\n        # For waking ourselves up\n        self.PIPE = os.pipe()\n        for p in self.PIPE:\n            util.set_non_blocking(p)\n            util.close_on_exec(p)\n\n        # Prevent fd inheritance\n        for s in self.sockets:\n            util.close_on_exec(s)\n        util.close_on_exec(self.tmp.fileno())\n\n        self.wait_fds = self.sockets + [self.PIPE[0]]\n\n        self.log.close_on_exec()\n\n        self.init_signals()\n\n        # start the reloader\n        if self.cfg.reload:\n            def changed(fname):\n                self.log.info(\"Worker reloading: %s modified\", fname)\n                self.alive = False\n                os.write(self.PIPE[1], b\"1\")\n                self.cfg.worker_int(self)\n                time.sleep(0.1)\n                sys.exit(0)\n\n            reloader_cls = reloader_engines[self.cfg.reload_engine]\n            self.reloader = reloader_cls(extra_files=self.cfg.reload_extra_files,\n                                         callback=changed)\n\n        self.load_wsgi()\n        if self.reloader:\n            self.reloader.start()\n\n        self.cfg.post_worker_init(self)\n\n        # Enter main run loop\n        self.booted = True\n        self.run()\n\n    def load_wsgi(self):\n        try:\n            self.wsgi = self.app.wsgi()\n        except SyntaxError as e:\n            if not self.cfg.reload:\n                raise\n\n            self.log.exception(e)\n\n            # fix from PR #1228\n            # storing the traceback into exc_tb will create a circular reference.\n            # per https://docs.python.org/2/library/sys.html#sys.exc_info warning,\n            # delete the traceback after use.\n            try:\n                _, exc_val, exc_tb = sys.exc_info()\n                self.reloader.add_extra_file(exc_val.filename)\n\n                tb_string = io.StringIO()\n                traceback.print_tb(exc_tb, file=tb_string)\n                self.wsgi = util.make_fail_app(tb_string.getvalue())\n            finally:\n                del exc_tb\n\n    def init_signals(self):\n        # reset signaling\n        for s in self.SIGNALS:\n            signal.signal(s, signal.SIG_DFL)\n        # init new signaling\n        signal.signal(signal.SIGQUIT, self.handle_quit)\n        signal.signal(signal.SIGTERM, self.handle_exit)\n        signal.signal(signal.SIGINT, self.handle_quit)\n        signal.signal(signal.SIGWINCH, self.handle_winch)\n        signal.signal(signal.SIGUSR1, self.handle_usr1)\n        signal.signal(signal.SIGABRT, self.handle_abort)\n\n        # Don't let SIGTERM and SIGUSR1 disturb active requests\n        # by interrupting system calls\n        signal.siginterrupt(signal.SIGTERM, False)\n        signal.siginterrupt(signal.SIGUSR1, False)\n\n        if hasattr(signal, 'set_wakeup_fd'):\n            signal.set_wakeup_fd(self.PIPE[1])\n\n    def handle_usr1(self, sig, frame):\n        self.log.reopen_files()\n\n    def handle_exit(self, sig, frame):\n        self.alive = False\n\n    def handle_quit(self, sig, frame):\n        self.alive = False\n        # worker_int callback\n        self.cfg.worker_int(self)\n        time.sleep(0.1)\n        sys.exit(0)\n\n    def handle_abort(self, sig, frame):\n        self.alive = False\n        self.cfg.worker_abort(self)\n        sys.exit(1)\n\n    def handle_error(self, req, client, addr, exc):\n        request_start = datetime.now()\n        addr = addr or ('', -1)  # unix socket case\n        if isinstance(exc, (\n            InvalidRequestLine, InvalidRequestMethod,\n            InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,\n            LimitRequestLine, LimitRequestHeaders,\n            InvalidProxyLine, ForbiddenProxyRequest,\n            InvalidSchemeHeaders,\n            SSLError,\n        )):\n\n            status_int = 400\n            reason = \"Bad Request\"\n\n            if isinstance(exc, InvalidRequestLine):\n                mesg = \"Invalid Request Line '%s'\" % str(exc)\n            elif isinstance(exc, InvalidRequestMethod):\n                mesg = \"Invalid Method '%s'\" % str(exc)\n            elif isinstance(exc, InvalidHTTPVersion):\n                mesg = \"Invalid HTTP Version '%s'\" % str(exc)\n            elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)):\n                mesg = \"%s\" % str(exc)\n                if not req and hasattr(exc, \"req\"):\n                    req = exc.req  # for access log\n            elif isinstance(exc, LimitRequestLine):\n                mesg = \"%s\" % str(exc)\n            elif isinstance(exc, LimitRequestHeaders):\n                mesg = \"Error parsing headers: '%s'\" % str(exc)\n            elif isinstance(exc, InvalidProxyLine):\n                mesg = \"'%s'\" % str(exc)\n            elif isinstance(exc, ForbiddenProxyRequest):\n                reason = \"Forbidden\"\n                mesg = \"Request forbidden\"\n                status_int = 403\n            elif isinstance(exc, InvalidSchemeHeaders):\n                mesg = \"%s\" % str(exc)\n            elif isinstance(exc, SSLError):\n                reason = \"Forbidden\"\n                mesg = \"'%s'\" % str(exc)\n                status_int = 403\n\n            msg = \"Invalid request from ip={ip}: {error}\"\n            self.log.debug(msg.format(ip=addr[0], error=str(exc)))\n        else:\n            if hasattr(req, \"uri\"):\n                self.log.exception(\"Error handling request %s\", req.uri)\n            status_int = 500\n            reason = \"Internal Server Error\"\n            mesg = \"\"\n\n        if req is not None:\n            request_time = datetime.now() - request_start\n            environ = default_environ(req, client, self.cfg)\n            environ['REMOTE_ADDR'] = addr[0]\n            environ['REMOTE_PORT'] = str(addr[1])\n            resp = Response(req, client, self.cfg)\n            resp.status = \"%s %s\" % (status_int, reason)\n            resp.response_length = len(mesg)\n            self.log.access(resp, req, environ, request_time)\n\n        try:\n            util.write_error(client, status_int, reason, mesg)\n        except Exception:\n            self.log.debug(\"Failed to send error message.\")\n\n    def handle_winch(self, sig, fname):\n        # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.\n        self.log.debug(\"worker: SIGWINCH ignored.\")\n", "path": "gunicorn/workers/base.py"}], "after_files": [{"content": "# -*- coding: utf-8 -\n#\n# This file is part of gunicorn released under the MIT license.\n# See the NOTICE for more information.\n\nimport io\nimport os\nimport signal\nimport sys\nimport time\nimport traceback\nfrom datetime import datetime\nfrom random import randint\nfrom ssl import SSLError\n\nfrom gunicorn import util\nfrom gunicorn.http.errors import (\n    ForbiddenProxyRequest, InvalidHeader,\n    InvalidHeaderName, InvalidHTTPVersion,\n    InvalidProxyLine, InvalidRequestLine,\n    InvalidRequestMethod, InvalidSchemeHeaders,\n    LimitRequestHeaders, LimitRequestLine,\n)\nfrom gunicorn.http.wsgi import Response, default_environ\nfrom gunicorn.reloader import reloader_engines\nfrom gunicorn.workers.workertmp import WorkerTmp\n\n\nclass Worker(object):\n\n    SIGNALS = [getattr(signal, \"SIG%s\" % x) for x in (\n        \"ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD\".split()\n    )]\n\n    PIPE = []\n\n    def __init__(self, age, ppid, sockets, app, timeout, cfg, log):\n        \"\"\"\\\n        This is called pre-fork so it shouldn't do anything to the\n        current process. If there's a need to make process wide\n        changes you'll want to do that in ``self.init_process()``.\n        \"\"\"\n        self.age = age\n        self.pid = \"[booting]\"\n        self.ppid = ppid\n        self.sockets = sockets\n        self.app = app\n        self.timeout = timeout\n        self.cfg = cfg\n        self.booted = False\n        self.aborted = False\n        self.reloader = None\n\n        self.nr = 0\n\n        if cfg.max_requests > 0:\n            jitter = randint(0, cfg.max_requests_jitter)\n            self.max_requests = cfg.max_requests + jitter\n        else:\n            self.max_requests = sys.maxsize\n\n        self.alive = True\n        self.log = log\n        self.tmp = WorkerTmp(cfg)\n\n    def __str__(self):\n        return \"<Worker %s>\" % self.pid\n\n    def notify(self):\n        \"\"\"\\\n        Your worker subclass must arrange to have this method called\n        once every ``self.timeout`` seconds. If you fail in accomplishing\n        this task, the master process will murder your workers.\n        \"\"\"\n        self.tmp.notify()\n\n    def run(self):\n        \"\"\"\\\n        This is the mainloop of a worker process. You should override\n        this method in a subclass to provide the intended behaviour\n        for your particular evil schemes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def init_process(self):\n        \"\"\"\\\n        If you override this method in a subclass, the last statement\n        in the function should be to call this method with\n        super().init_process() so that the ``run()`` loop is initiated.\n        \"\"\"\n\n        # set environment' variables\n        if self.cfg.env:\n            for k, v in self.cfg.env.items():\n                os.environ[k] = v\n\n        util.set_owner_process(self.cfg.uid, self.cfg.gid,\n                               initgroups=self.cfg.initgroups)\n\n        # Reseed the random number generator\n        util.seed()\n\n        # For waking ourselves up\n        self.PIPE = os.pipe()\n        for p in self.PIPE:\n            util.set_non_blocking(p)\n            util.close_on_exec(p)\n\n        # Prevent fd inheritance\n        for s in self.sockets:\n            util.close_on_exec(s)\n        util.close_on_exec(self.tmp.fileno())\n\n        self.wait_fds = self.sockets + [self.PIPE[0]]\n\n        self.log.close_on_exec()\n\n        self.init_signals()\n\n        # start the reloader\n        if self.cfg.reload:\n            def changed(fname):\n                self.log.info(\"Worker reloading: %s modified\", fname)\n                self.alive = False\n                os.write(self.PIPE[1], b\"1\")\n                self.cfg.worker_int(self)\n                time.sleep(0.1)\n                sys.exit(0)\n\n            reloader_cls = reloader_engines[self.cfg.reload_engine]\n            self.reloader = reloader_cls(extra_files=self.cfg.reload_extra_files,\n                                         callback=changed)\n\n        self.load_wsgi()\n        if self.reloader:\n            self.reloader.start()\n\n        self.cfg.post_worker_init(self)\n\n        # Enter main run loop\n        self.booted = True\n        self.run()\n\n    def load_wsgi(self):\n        try:\n            self.wsgi = self.app.wsgi()\n        except SyntaxError as e:\n            if not self.cfg.reload:\n                raise\n\n            self.log.exception(e)\n\n            # fix from PR #1228\n            # storing the traceback into exc_tb will create a circular reference.\n            # per https://docs.python.org/2/library/sys.html#sys.exc_info warning,\n            # delete the traceback after use.\n            try:\n                _, exc_val, exc_tb = sys.exc_info()\n                self.reloader.add_extra_file(exc_val.filename)\n\n                tb_string = io.StringIO()\n                traceback.print_tb(exc_tb, file=tb_string)\n                self.wsgi = util.make_fail_app(tb_string.getvalue())\n            finally:\n                del exc_tb\n\n    def init_signals(self):\n        # reset signaling\n        for s in self.SIGNALS:\n            signal.signal(s, signal.SIG_DFL)\n        # init new signaling\n        signal.signal(signal.SIGQUIT, self.handle_quit)\n        signal.signal(signal.SIGTERM, self.handle_exit)\n        signal.signal(signal.SIGINT, self.handle_quit)\n        signal.signal(signal.SIGWINCH, self.handle_winch)\n        signal.signal(signal.SIGUSR1, self.handle_usr1)\n        signal.signal(signal.SIGABRT, self.handle_abort)\n\n        # Don't let SIGTERM and SIGUSR1 disturb active requests\n        # by interrupting system calls\n        signal.siginterrupt(signal.SIGTERM, False)\n        signal.siginterrupt(signal.SIGUSR1, False)\n\n        if hasattr(signal, 'set_wakeup_fd'):\n            signal.set_wakeup_fd(self.PIPE[1])\n\n    def handle_usr1(self, sig, frame):\n        self.log.reopen_files()\n\n    def handle_exit(self, sig, frame):\n        self.alive = False\n\n    def handle_quit(self, sig, frame):\n        self.alive = False\n        # worker_int callback\n        self.cfg.worker_int(self)\n        time.sleep(0.1)\n        sys.exit(0)\n\n    def handle_abort(self, sig, frame):\n        self.alive = False\n        self.cfg.worker_abort(self)\n        sys.exit(1)\n\n    def handle_error(self, req, client, addr, exc):\n        request_start = datetime.now()\n        addr = addr or ('', -1)  # unix socket case\n        if isinstance(exc, (\n            InvalidRequestLine, InvalidRequestMethod,\n            InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,\n            LimitRequestLine, LimitRequestHeaders,\n            InvalidProxyLine, ForbiddenProxyRequest,\n            InvalidSchemeHeaders,\n            SSLError,\n        )):\n\n            status_int = 400\n            reason = \"Bad Request\"\n\n            if isinstance(exc, InvalidRequestLine):\n                mesg = \"Invalid Request Line '%s'\" % str(exc)\n            elif isinstance(exc, InvalidRequestMethod):\n                mesg = \"Invalid Method '%s'\" % str(exc)\n            elif isinstance(exc, InvalidHTTPVersion):\n                mesg = \"Invalid HTTP Version '%s'\" % str(exc)\n            elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)):\n                mesg = \"%s\" % str(exc)\n                if not req and hasattr(exc, \"req\"):\n                    req = exc.req  # for access log\n            elif isinstance(exc, LimitRequestLine):\n                mesg = \"%s\" % str(exc)\n            elif isinstance(exc, LimitRequestHeaders):\n                reason = \"Request Header Fields Too Large\"\n                mesg = \"Error parsing headers: '%s'\" % str(exc)\n                status_int = 431\n            elif isinstance(exc, InvalidProxyLine):\n                mesg = \"'%s'\" % str(exc)\n            elif isinstance(exc, ForbiddenProxyRequest):\n                reason = \"Forbidden\"\n                mesg = \"Request forbidden\"\n                status_int = 403\n            elif isinstance(exc, InvalidSchemeHeaders):\n                mesg = \"%s\" % str(exc)\n            elif isinstance(exc, SSLError):\n                reason = \"Forbidden\"\n                mesg = \"'%s'\" % str(exc)\n                status_int = 403\n\n            msg = \"Invalid request from ip={ip}: {error}\"\n            self.log.debug(msg.format(ip=addr[0], error=str(exc)))\n        else:\n            if hasattr(req, \"uri\"):\n                self.log.exception(\"Error handling request %s\", req.uri)\n            status_int = 500\n            reason = \"Internal Server Error\"\n            mesg = \"\"\n\n        if req is not None:\n            request_time = datetime.now() - request_start\n            environ = default_environ(req, client, self.cfg)\n            environ['REMOTE_ADDR'] = addr[0]\n            environ['REMOTE_PORT'] = str(addr[1])\n            resp = Response(req, client, self.cfg)\n            resp.status = \"%s %s\" % (status_int, reason)\n            resp.response_length = len(mesg)\n            self.log.access(resp, req, environ, request_time)\n\n        try:\n            util.write_error(client, status_int, reason, mesg)\n        except Exception:\n            self.log.debug(\"Failed to send error message.\")\n\n    def handle_winch(self, sig, fname):\n        # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.\n        self.log.debug(\"worker: SIGWINCH ignored.\")\n", "path": "gunicorn/workers/base.py"}]}