util.py 18 KB

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