util.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. #
  2. # This file is part of gunicorn released under the MIT license.
  3. # See the NOTICE for more information.
  4. import ast
  5. import email.utils
  6. import errno
  7. import fcntl
  8. import html
  9. import importlib
  10. import inspect
  11. import io
  12. import logging
  13. import os
  14. import pwd
  15. import random
  16. import re
  17. import socket
  18. import sys
  19. import textwrap
  20. import time
  21. import traceback
  22. import warnings
  23. try:
  24. import importlib.metadata as importlib_metadata
  25. except (ModuleNotFoundError, ImportError):
  26. import importlib_metadata
  27. from gunicorn.errors import AppImportError
  28. from gunicorn.workers import SUPPORTED_WORKERS
  29. import urllib.parse
  30. REDIRECT_TO = getattr(os, 'devnull', '/dev/null')
  31. # Server and Date aren't technically hop-by-hop
  32. # headers, but they are in the purview of the
  33. # origin server which the WSGI spec says we should
  34. # act like. So we drop them and add our own.
  35. #
  36. # In the future, concatenation server header values
  37. # might be better, but nothing else does it and
  38. # dropping them is easier.
  39. hop_headers = set("""
  40. connection keep-alive proxy-authenticate proxy-authorization
  41. te trailers transfer-encoding upgrade
  42. server date
  43. """.split())
  44. try:
  45. from setproctitle import setproctitle
  46. def _setproctitle(title):
  47. setproctitle("gunicorn: %s" % title)
  48. except ImportError:
  49. def _setproctitle(title):
  50. pass
  51. def load_entry_point(distribution, group, name):
  52. dist_obj = importlib_metadata.distribution(distribution)
  53. eps = [ep for ep in dist_obj.entry_points
  54. if ep.group == group and ep.name == name]
  55. if not eps:
  56. raise ImportError("Entry point %r not found" % ((group, name),))
  57. return eps[0].load()
  58. def load_class(uri, default="gunicorn.workers.sync.SyncWorker",
  59. section="gunicorn.workers"):
  60. if inspect.isclass(uri):
  61. return uri
  62. if uri.startswith("egg:"):
  63. # uses entry points
  64. entry_str = uri.split("egg:")[1]
  65. try:
  66. dist, name = entry_str.rsplit("#", 1)
  67. except ValueError:
  68. dist = entry_str
  69. name = default
  70. try:
  71. return load_entry_point(dist, section, name)
  72. except Exception:
  73. exc = traceback.format_exc()
  74. msg = "class uri %r invalid or not found: \n\n[%s]"
  75. raise RuntimeError(msg % (uri, exc))
  76. else:
  77. components = uri.split('.')
  78. if len(components) == 1:
  79. while True:
  80. if uri.startswith("#"):
  81. uri = uri[1:]
  82. if uri in SUPPORTED_WORKERS:
  83. components = SUPPORTED_WORKERS[uri].split(".")
  84. break
  85. try:
  86. return load_entry_point(
  87. "gunicorn", section, uri
  88. )
  89. except Exception:
  90. exc = traceback.format_exc()
  91. msg = "class uri %r invalid or not found: \n\n[%s]"
  92. raise RuntimeError(msg % (uri, exc))
  93. klass = components.pop(-1)
  94. try:
  95. mod = importlib.import_module('.'.join(components))
  96. except Exception:
  97. exc = traceback.format_exc()
  98. msg = "class uri %r invalid or not found: \n\n[%s]"
  99. raise RuntimeError(msg % (uri, exc))
  100. return getattr(mod, klass)
  101. positionals = (
  102. inspect.Parameter.POSITIONAL_ONLY,
  103. inspect.Parameter.POSITIONAL_OR_KEYWORD,
  104. )
  105. def get_arity(f):
  106. sig = inspect.signature(f)
  107. arity = 0
  108. for param in sig.parameters.values():
  109. if param.kind in positionals:
  110. arity += 1
  111. return arity
  112. def get_username(uid):
  113. """ get the username for a user id"""
  114. return pwd.getpwuid(uid).pw_name
  115. def set_owner_process(uid, gid, initgroups=False):
  116. """ set user and group of workers processes """
  117. if gid:
  118. if uid:
  119. try:
  120. username = get_username(uid)
  121. except KeyError:
  122. initgroups = False
  123. # versions of python < 2.6.2 don't manage unsigned int for
  124. # groups like on osx or fedora
  125. gid = abs(gid) & 0x7FFFFFFF
  126. if initgroups:
  127. os.initgroups(username, gid)
  128. elif gid != os.getgid():
  129. os.setgid(gid)
  130. if uid and uid != os.getuid():
  131. os.setuid(uid)
  132. def chown(path, uid, gid):
  133. os.chown(path, uid, gid)
  134. if sys.platform.startswith("win"):
  135. def _waitfor(func, pathname, waitall=False):
  136. # Perform the operation
  137. func(pathname)
  138. # Now setup the wait loop
  139. if waitall:
  140. dirname = pathname
  141. else:
  142. dirname, name = os.path.split(pathname)
  143. dirname = dirname or '.'
  144. # Check for `pathname` to be removed from the filesystem.
  145. # The exponential backoff of the timeout amounts to a total
  146. # of ~1 second after which the deletion is probably an error
  147. # anyway.
  148. # Testing on a i7@4.3GHz shows that usually only 1 iteration is
  149. # required when contention occurs.
  150. timeout = 0.001
  151. while timeout < 1.0:
  152. # Note we are only testing for the existence of the file(s) in
  153. # the contents of the directory regardless of any security or
  154. # access rights. If we have made it this far, we have sufficient
  155. # permissions to do that much using Python's equivalent of the
  156. # Windows API FindFirstFile.
  157. # Other Windows APIs can fail or give incorrect results when
  158. # dealing with files that are pending deletion.
  159. L = os.listdir(dirname)
  160. if not L if waitall else name in L:
  161. return
  162. # Increase the timeout and try again
  163. time.sleep(timeout)
  164. timeout *= 2
  165. warnings.warn('tests may fail, delete still pending for ' + pathname,
  166. RuntimeWarning, stacklevel=4)
  167. def _unlink(filename):
  168. _waitfor(os.unlink, filename)
  169. else:
  170. _unlink = os.unlink
  171. def unlink(filename):
  172. try:
  173. _unlink(filename)
  174. except OSError as error:
  175. # The filename need not exist.
  176. if error.errno not in (errno.ENOENT, errno.ENOTDIR):
  177. raise
  178. def is_ipv6(addr):
  179. try:
  180. socket.inet_pton(socket.AF_INET6, addr)
  181. except OSError: # not a valid address
  182. return False
  183. except ValueError: # ipv6 not supported on this platform
  184. return False
  185. return True
  186. def parse_address(netloc, default_port='8000'):
  187. if re.match(r'unix:(//)?', netloc):
  188. return re.split(r'unix:(//)?', netloc)[-1]
  189. if netloc.startswith("fd://"):
  190. fd = netloc[5:]
  191. try:
  192. return int(fd)
  193. except ValueError:
  194. raise RuntimeError("%r is not a valid file descriptor." % fd) from None
  195. if netloc.startswith("tcp://"):
  196. netloc = netloc.split("tcp://")[1]
  197. host, port = netloc, default_port
  198. if '[' in netloc and ']' in netloc:
  199. host = netloc.split(']')[0][1:]
  200. port = (netloc.split(']:') + [default_port])[1]
  201. elif ':' in netloc:
  202. host, port = (netloc.split(':') + [default_port])[:2]
  203. elif netloc == "":
  204. host, port = "0.0.0.0", default_port
  205. try:
  206. port = int(port)
  207. except ValueError:
  208. raise RuntimeError("%r is not a valid port number." % port)
  209. return host.lower(), port
  210. def close_on_exec(fd):
  211. flags = fcntl.fcntl(fd, fcntl.F_GETFD)
  212. flags |= fcntl.FD_CLOEXEC
  213. fcntl.fcntl(fd, fcntl.F_SETFD, flags)
  214. def set_non_blocking(fd):
  215. flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK
  216. fcntl.fcntl(fd, fcntl.F_SETFL, flags)
  217. def close(sock):
  218. try:
  219. sock.close()
  220. except OSError:
  221. pass
  222. try:
  223. from os import closerange
  224. except ImportError:
  225. def closerange(fd_low, fd_high):
  226. # Iterate through and close all file descriptors.
  227. for fd in range(fd_low, fd_high):
  228. try:
  229. os.close(fd)
  230. except OSError: # ERROR, fd wasn't open to begin with (ignored)
  231. pass
  232. def write_chunk(sock, data):
  233. if isinstance(data, str):
  234. data = data.encode('utf-8')
  235. chunk_size = "%X\r\n" % len(data)
  236. chunk = b"".join([chunk_size.encode('utf-8'), data, b"\r\n"])
  237. sock.sendall(chunk)
  238. def write(sock, data, chunked=False):
  239. if chunked:
  240. return write_chunk(sock, data)
  241. sock.sendall(data)
  242. def write_nonblock(sock, data, chunked=False):
  243. timeout = sock.gettimeout()
  244. if timeout != 0.0:
  245. try:
  246. sock.setblocking(0)
  247. return write(sock, data, chunked)
  248. finally:
  249. sock.setblocking(1)
  250. else:
  251. return write(sock, data, chunked)
  252. def write_error(sock, status_int, reason, mesg):
  253. html_error = textwrap.dedent("""\
  254. <html>
  255. <head>
  256. <title>%(reason)s</title>
  257. </head>
  258. <body>
  259. <h1><p>%(reason)s</p></h1>
  260. %(mesg)s
  261. </body>
  262. </html>
  263. """) % {"reason": reason, "mesg": html.escape(mesg)}
  264. http = textwrap.dedent("""\
  265. HTTP/1.1 %s %s\r
  266. Connection: close\r
  267. Content-Type: text/html\r
  268. Content-Length: %d\r
  269. \r
  270. %s""") % (str(status_int), reason, len(html_error), html_error)
  271. write_nonblock(sock, http.encode('latin1'))
  272. def _called_with_wrong_args(f):
  273. """Check whether calling a function raised a ``TypeError`` because
  274. the call failed or because something in the function raised the
  275. error.
  276. :param f: The function that was called.
  277. :return: ``True`` if the call failed.
  278. """
  279. tb = sys.exc_info()[2]
  280. try:
  281. while tb is not None:
  282. if tb.tb_frame.f_code is f.__code__:
  283. # In the function, it was called successfully.
  284. return False
  285. tb = tb.tb_next
  286. # Didn't reach the function.
  287. return True
  288. finally:
  289. # Delete tb to break a circular reference in Python 2.
  290. # https://docs.python.org/2/library/sys.html#sys.exc_info
  291. del tb
  292. def import_app(module):
  293. parts = module.split(":", 1)
  294. if len(parts) == 1:
  295. obj = "application"
  296. else:
  297. module, obj = parts[0], parts[1]
  298. try:
  299. mod = importlib.import_module(module)
  300. except ImportError:
  301. if module.endswith(".py") and os.path.exists(module):
  302. msg = "Failed to find application, did you mean '%s:%s'?"
  303. raise ImportError(msg % (module.rsplit(".", 1)[0], obj))
  304. raise
  305. # Parse obj as a single expression to determine if it's a valid
  306. # attribute name or function call.
  307. try:
  308. expression = ast.parse(obj, mode="eval").body
  309. except SyntaxError:
  310. raise AppImportError(
  311. "Failed to parse %r as an attribute name or function call." % obj
  312. )
  313. if isinstance(expression, ast.Name):
  314. name = expression.id
  315. args = kwargs = None
  316. elif isinstance(expression, ast.Call):
  317. # Ensure the function name is an attribute name only.
  318. if not isinstance(expression.func, ast.Name):
  319. raise AppImportError("Function reference must be a simple name: %r" % obj)
  320. name = expression.func.id
  321. # Parse the positional and keyword arguments as literals.
  322. try:
  323. args = [ast.literal_eval(arg) for arg in expression.args]
  324. kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expression.keywords}
  325. except ValueError:
  326. # literal_eval gives cryptic error messages, show a generic
  327. # message with the full expression instead.
  328. raise AppImportError(
  329. "Failed to parse arguments as literal values: %r" % obj
  330. )
  331. else:
  332. raise AppImportError(
  333. "Failed to parse %r as an attribute name or function call." % obj
  334. )
  335. is_debug = logging.root.level == logging.DEBUG
  336. try:
  337. app = getattr(mod, name)
  338. except AttributeError:
  339. if is_debug:
  340. traceback.print_exception(*sys.exc_info())
  341. raise AppImportError("Failed to find attribute %r in %r." % (name, module))
  342. # If the expression was a function call, call the retrieved object
  343. # to get the real application.
  344. if args is not None:
  345. try:
  346. app = app(*args, **kwargs)
  347. except TypeError as e:
  348. # If the TypeError was due to bad arguments to the factory
  349. # function, show Python's nice error message without a
  350. # traceback.
  351. if _called_with_wrong_args(app):
  352. raise AppImportError(
  353. "".join(traceback.format_exception_only(TypeError, e)).strip()
  354. )
  355. # Otherwise it was raised from within the function, show the
  356. # full traceback.
  357. raise
  358. if app is None:
  359. raise AppImportError("Failed to find application object: %r" % obj)
  360. if not callable(app):
  361. raise AppImportError("Application object must be callable.")
  362. return app
  363. def getcwd():
  364. # get current path, try to use PWD env first
  365. try:
  366. a = os.stat(os.environ['PWD'])
  367. b = os.stat(os.getcwd())
  368. if a.st_ino == b.st_ino and a.st_dev == b.st_dev:
  369. cwd = os.environ['PWD']
  370. else:
  371. cwd = os.getcwd()
  372. except Exception:
  373. cwd = os.getcwd()
  374. return cwd
  375. def http_date(timestamp=None):
  376. """Return the current date and time formatted for a message header."""
  377. if timestamp is None:
  378. timestamp = time.time()
  379. s = email.utils.formatdate(timestamp, localtime=False, usegmt=True)
  380. return s
  381. def is_hoppish(header):
  382. return header.lower().strip() in hop_headers
  383. def daemonize(enable_stdio_inheritance=False):
  384. """\
  385. Standard daemonization of a process.
  386. http://www.faqs.org/faqs/unix-faq/programmer/faq/ section 1.7
  387. """
  388. if 'GUNICORN_FD' not in os.environ:
  389. if os.fork():
  390. os._exit(0)
  391. os.setsid()
  392. if os.fork():
  393. os._exit(0)
  394. os.umask(0o22)
  395. # In both the following any file descriptors above stdin
  396. # stdout and stderr are left untouched. The inheritance
  397. # option simply allows one to have output go to a file
  398. # specified by way of shell redirection when not wanting
  399. # to use --error-log option.
  400. if not enable_stdio_inheritance:
  401. # Remap all of stdin, stdout and stderr on to
  402. # /dev/null. The expectation is that users have
  403. # specified the --error-log option.
  404. closerange(0, 3)
  405. fd_null = os.open(REDIRECT_TO, os.O_RDWR)
  406. # PEP 446, make fd for /dev/null inheritable
  407. os.set_inheritable(fd_null, True)
  408. # expect fd_null to be always 0 here, but in-case not ...
  409. if fd_null != 0:
  410. os.dup2(fd_null, 0)
  411. os.dup2(fd_null, 1)
  412. os.dup2(fd_null, 2)
  413. else:
  414. fd_null = os.open(REDIRECT_TO, os.O_RDWR)
  415. # Always redirect stdin to /dev/null as we would
  416. # never expect to need to read interactive input.
  417. if fd_null != 0:
  418. os.close(0)
  419. os.dup2(fd_null, 0)
  420. # If stdout and stderr are still connected to
  421. # their original file descriptors we check to see
  422. # if they are associated with terminal devices.
  423. # When they are we map them to /dev/null so that
  424. # are still detached from any controlling terminal
  425. # properly. If not we preserve them as they are.
  426. #
  427. # If stdin and stdout were not hooked up to the
  428. # original file descriptors, then all bets are
  429. # off and all we can really do is leave them as
  430. # they were.
  431. #
  432. # This will allow 'gunicorn ... > output.log 2>&1'
  433. # to work with stdout/stderr going to the file
  434. # as expected.
  435. #
  436. # Note that if using --error-log option, the log
  437. # file specified through shell redirection will
  438. # only be used up until the log file specified
  439. # by the option takes over. As it replaces stdout
  440. # and stderr at the file descriptor level, then
  441. # anything using stdout or stderr, including having
  442. # cached a reference to them, will still work.
  443. def redirect(stream, fd_expect):
  444. try:
  445. fd = stream.fileno()
  446. if fd == fd_expect and stream.isatty():
  447. os.close(fd)
  448. os.dup2(fd_null, fd)
  449. except AttributeError:
  450. pass
  451. redirect(sys.stdout, 1)
  452. redirect(sys.stderr, 2)
  453. def seed():
  454. try:
  455. random.seed(os.urandom(64))
  456. except NotImplementedError:
  457. random.seed('%s.%s' % (time.time(), os.getpid()))
  458. def check_is_writable(path):
  459. try:
  460. with open(path, 'a') as f:
  461. f.close()
  462. except OSError as e:
  463. raise RuntimeError("Error: '%s' isn't writable [%r]" % (path, e))
  464. def to_bytestring(value, encoding="utf8"):
  465. """Converts a string argument to a byte string"""
  466. if isinstance(value, bytes):
  467. return value
  468. if not isinstance(value, str):
  469. raise TypeError('%r is not a string' % value)
  470. return value.encode(encoding)
  471. def has_fileno(obj):
  472. if not hasattr(obj, "fileno"):
  473. return False
  474. # check BytesIO case and maybe others
  475. try:
  476. obj.fileno()
  477. except (AttributeError, OSError, io.UnsupportedOperation):
  478. return False
  479. return True
  480. def warn(msg):
  481. print("!!!", file=sys.stderr)
  482. lines = msg.splitlines()
  483. for i, line in enumerate(lines):
  484. if i == 0:
  485. line = "WARNING: %s" % line
  486. print("!!! %s" % line, file=sys.stderr)
  487. print("!!!\n", file=sys.stderr)
  488. sys.stderr.flush()
  489. def make_fail_app(msg):
  490. msg = to_bytestring(msg)
  491. def app(environ, start_response):
  492. start_response("500 Internal Server Error", [
  493. ("Content-Type", "text/plain"),
  494. ("Content-Length", str(len(msg)))
  495. ])
  496. return [msg]
  497. return app
  498. def split_request_uri(uri):
  499. if uri.startswith("//"):
  500. # When the path starts with //, urlsplit considers it as a
  501. # relative uri while the RFC says we should consider it as abs_path
  502. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  503. # We use temporary dot prefix to workaround this behaviour
  504. parts = urllib.parse.urlsplit("." + uri)
  505. return parts._replace(path=parts.path[1:])
  506. return urllib.parse.urlsplit(uri)
  507. # From six.reraise
  508. def reraise(tp, value, tb=None):
  509. try:
  510. if value is None:
  511. value = tp()
  512. if value.__traceback__ is not tb:
  513. raise value.with_traceback(tb)
  514. raise value
  515. finally:
  516. value = None
  517. tb = None
  518. def bytes_to_str(b):
  519. if isinstance(b, str):
  520. return b
  521. return str(b, 'latin1')
  522. def unquote_to_wsgi_str(string):
  523. return urllib.parse.unquote_to_bytes(string).decode('latin-1')