platforms.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. # -*- coding: utf-8 -*-
  2. """Platforms.
  3. Utilities dealing with platform specifics: signals, daemonization,
  4. users, groups, and so on.
  5. """
  6. import atexit
  7. import errno
  8. import math
  9. import numbers
  10. import os
  11. import platform as _platform
  12. import signal as _signal
  13. import sys
  14. import warnings
  15. from billiard.compat import get_fdmax, close_open_fds
  16. # fileno used to be in this module
  17. from kombu.utils.compat import maybe_fileno
  18. from kombu.utils.encoding import safe_str
  19. from contextlib import contextmanager
  20. from .exceptions import SecurityError
  21. from .local import try_import
  22. try:
  23. from billiard.process import current_process
  24. except ImportError: # pragma: no cover
  25. current_process = None
  26. _setproctitle = try_import('setproctitle')
  27. resource = try_import('resource')
  28. pwd = try_import('pwd')
  29. grp = try_import('grp')
  30. mputil = try_import('multiprocessing.util')
  31. __all__ = [
  32. 'EX_OK', 'EX_FAILURE', 'EX_UNAVAILABLE', 'EX_USAGE', 'SYSTEM',
  33. 'IS_macOS', 'IS_WINDOWS', 'SIGMAP', 'pyimplementation', 'LockFailed',
  34. 'get_fdmax', 'Pidfile', 'create_pidlock', 'close_open_fds',
  35. 'DaemonContext', 'detached', 'parse_uid', 'parse_gid', 'setgroups',
  36. 'initgroups', 'setgid', 'setuid', 'maybe_drop_privileges', 'signals',
  37. 'signal_name', 'set_process_title', 'set_mp_process_title',
  38. 'get_errno_name', 'ignore_errno', 'fd_by_path', 'isatty',
  39. ]
  40. # exitcodes
  41. EX_OK = getattr(os, 'EX_OK', 0)
  42. EX_FAILURE = 1
  43. EX_UNAVAILABLE = getattr(os, 'EX_UNAVAILABLE', 69)
  44. EX_USAGE = getattr(os, 'EX_USAGE', 64)
  45. EX_CANTCREAT = getattr(os, 'EX_CANTCREAT', 73)
  46. SYSTEM = _platform.system()
  47. IS_macOS = SYSTEM == 'Darwin'
  48. IS_WINDOWS = SYSTEM == 'Windows'
  49. DAEMON_WORKDIR = '/'
  50. PIDFILE_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY
  51. PIDFILE_MODE = ((os.R_OK | os.W_OK) << 6) | ((os.R_OK) << 3) | ((os.R_OK))
  52. PIDLOCKED = """ERROR: Pidfile ({0}) already exists.
  53. Seems we're already running? (pid: {1})"""
  54. C_FORCE_ROOT = os.environ.get('C_FORCE_ROOT', False)
  55. ROOT_DISALLOWED = """\
  56. Running a worker with superuser privileges when the
  57. worker accepts messages serialized with pickle is a very bad idea!
  58. If you really want to continue then you have to set the C_FORCE_ROOT
  59. environment variable (but please think about this before you do).
  60. User information: uid={uid} euid={euid} gid={gid} egid={egid}
  61. """
  62. ROOT_DISCOURAGED = """\
  63. You're running the worker with superuser privileges: this is
  64. absolutely not recommended!
  65. Please specify a different user using the -u option.
  66. User information: uid={uid} euid={euid} gid={gid} egid={egid}
  67. """
  68. SIGNAMES = {
  69. sig for sig in dir(_signal)
  70. if sig.startswith('SIG') and '_' not in sig
  71. }
  72. SIGMAP = {getattr(_signal, name): name for name in SIGNAMES}
  73. def isatty(fh):
  74. """Return true if the process has a controlling terminal."""
  75. try:
  76. return fh.isatty()
  77. except AttributeError:
  78. pass
  79. def pyimplementation():
  80. """Return string identifying the current Python implementation."""
  81. if hasattr(_platform, 'python_implementation'):
  82. return _platform.python_implementation()
  83. elif sys.platform.startswith('java'):
  84. return 'Jython ' + sys.platform
  85. elif hasattr(sys, 'pypy_version_info'):
  86. v = '.'.join(str(p) for p in sys.pypy_version_info[:3])
  87. if sys.pypy_version_info[3:]:
  88. v += '-' + ''.join(str(p) for p in sys.pypy_version_info[3:])
  89. return 'PyPy ' + v
  90. else:
  91. return 'CPython'
  92. class LockFailed(Exception):
  93. """Raised if a PID lock can't be acquired."""
  94. class Pidfile:
  95. """Pidfile.
  96. This is the type returned by :func:`create_pidlock`.
  97. See Also:
  98. Best practice is to not use this directly but rather use
  99. the :func:`create_pidlock` function instead:
  100. more convenient and also removes stale pidfiles (when
  101. the process holding the lock is no longer running).
  102. """
  103. #: Path to the pid lock file.
  104. path = None
  105. def __init__(self, path):
  106. self.path = os.path.abspath(path)
  107. def acquire(self):
  108. """Acquire lock."""
  109. try:
  110. self.write_pid()
  111. except FileExistsError as exc:
  112. raise LockFailed(str(exc)).with_traceback(sys.exc_info()[2])
  113. return self
  114. __enter__ = acquire
  115. def is_locked(self):
  116. """Return true if the pid lock exists."""
  117. return os.path.exists(self.path)
  118. def release(self, *args):
  119. """Release lock."""
  120. self.remove()
  121. __exit__ = release
  122. def read_pid(self):
  123. """Read and return the current pid."""
  124. with ignore_errno('ENOENT'):
  125. with open(self.path, 'r') as fh:
  126. line = fh.readline()
  127. if line.strip() == line: # must contain '\n'
  128. raise ValueError(
  129. 'Partial or invalid pidfile {0.path}'.format(self))
  130. try:
  131. return int(line.strip())
  132. except ValueError:
  133. raise ValueError(
  134. 'pidfile {0.path} contents invalid.'.format(self))
  135. def remove(self):
  136. """Remove the lock."""
  137. with ignore_errno(errno.ENOENT, errno.EACCES):
  138. os.unlink(self.path)
  139. def remove_if_stale(self):
  140. """Remove the lock if the process isn't running.
  141. I.e. process does not respons to signal.
  142. """
  143. try:
  144. pid = self.read_pid()
  145. except ValueError as exc:
  146. print('Broken pidfile found - Removing it.', file=sys.stderr)
  147. self.remove()
  148. return True
  149. if not pid:
  150. self.remove()
  151. return True
  152. try:
  153. os.kill(pid, 0)
  154. except os.error as exc:
  155. if exc.errno == errno.ESRCH:
  156. print('Stale pidfile exists - Removing it.', file=sys.stderr)
  157. self.remove()
  158. return True
  159. return False
  160. def write_pid(self):
  161. pid = os.getpid()
  162. content = '{0}\n'.format(pid)
  163. pidfile_fd = os.open(self.path, PIDFILE_FLAGS, PIDFILE_MODE)
  164. pidfile = os.fdopen(pidfile_fd, 'w')
  165. try:
  166. pidfile.write(content)
  167. # flush and sync so that the re-read below works.
  168. pidfile.flush()
  169. try:
  170. os.fsync(pidfile_fd)
  171. except AttributeError: # pragma: no cover
  172. pass
  173. finally:
  174. pidfile.close()
  175. rfh = open(self.path)
  176. try:
  177. if rfh.read() != content:
  178. raise LockFailed(
  179. "Inconsistency: Pidfile content doesn't match at re-read")
  180. finally:
  181. rfh.close()
  182. PIDFile = Pidfile # noqa: E305 XXX compat alias
  183. def create_pidlock(pidfile):
  184. """Create and verify pidfile.
  185. If the pidfile already exists the program exits with an error message,
  186. however if the process it refers to isn't running anymore, the pidfile
  187. is deleted and the program continues.
  188. This function will automatically install an :mod:`atexit` handler
  189. to release the lock at exit, you can skip this by calling
  190. :func:`_create_pidlock` instead.
  191. Returns:
  192. Pidfile: used to manage the lock.
  193. Example:
  194. >>> pidlock = create_pidlock('/var/run/app.pid')
  195. """
  196. pidlock = _create_pidlock(pidfile)
  197. atexit.register(pidlock.release)
  198. return pidlock
  199. def _create_pidlock(pidfile):
  200. pidlock = Pidfile(pidfile)
  201. if pidlock.is_locked() and not pidlock.remove_if_stale():
  202. print(PIDLOCKED.format(pidfile, pidlock.read_pid()), file=sys.stderr)
  203. raise SystemExit(EX_CANTCREAT)
  204. pidlock.acquire()
  205. return pidlock
  206. def fd_by_path(paths):
  207. """Return a list of file descriptors.
  208. This method returns list of file descriptors corresponding to
  209. file paths passed in paths variable.
  210. Arguments:
  211. paths: List[str]: List of file paths.
  212. Returns:
  213. List[int]: List of file descriptors.
  214. Example:
  215. >>> keep = fd_by_path(['/dev/urandom', '/my/precious/'])
  216. """
  217. stats = set()
  218. for path in paths:
  219. try:
  220. fd = os.open(path, os.O_RDONLY)
  221. except OSError:
  222. continue
  223. try:
  224. stats.add(os.fstat(fd)[1:3])
  225. finally:
  226. os.close(fd)
  227. def fd_in_stats(fd):
  228. try:
  229. return os.fstat(fd)[1:3] in stats
  230. except OSError:
  231. return False
  232. return [_fd for _fd in range(get_fdmax(2048)) if fd_in_stats(_fd)]
  233. class DaemonContext:
  234. """Context manager daemonizing the process."""
  235. _is_open = False
  236. def __init__(self, pidfile=None, workdir=None, umask=None,
  237. fake=False, after_chdir=None, after_forkers=True,
  238. **kwargs):
  239. if isinstance(umask, str):
  240. # octal or decimal, depending on initial zero.
  241. umask = int(umask, 8 if umask.startswith('0') else 10)
  242. self.workdir = workdir or DAEMON_WORKDIR
  243. self.umask = umask
  244. self.fake = fake
  245. self.after_chdir = after_chdir
  246. self.after_forkers = after_forkers
  247. self.stdfds = (sys.stdin, sys.stdout, sys.stderr)
  248. def redirect_to_null(self, fd):
  249. if fd is not None:
  250. dest = os.open(os.devnull, os.O_RDWR)
  251. os.dup2(dest, fd)
  252. def open(self):
  253. if not self._is_open:
  254. if not self.fake:
  255. self._detach()
  256. os.chdir(self.workdir)
  257. if self.umask is not None:
  258. os.umask(self.umask)
  259. if self.after_chdir:
  260. self.after_chdir()
  261. if not self.fake:
  262. # We need to keep /dev/urandom from closing because
  263. # shelve needs it, and Beat needs shelve to start.
  264. keep = list(self.stdfds) + fd_by_path(['/dev/urandom'])
  265. close_open_fds(keep)
  266. for fd in self.stdfds:
  267. self.redirect_to_null(maybe_fileno(fd))
  268. if self.after_forkers and mputil is not None:
  269. mputil._run_after_forkers()
  270. self._is_open = True
  271. __enter__ = open
  272. def close(self, *args):
  273. if self._is_open:
  274. self._is_open = False
  275. __exit__ = close
  276. def _detach(self):
  277. if os.fork() == 0: # first child
  278. os.setsid() # create new session
  279. if os.fork() > 0: # pragma: no cover
  280. # second child
  281. os._exit(0)
  282. else:
  283. os._exit(0)
  284. return self
  285. def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0,
  286. workdir=None, fake=False, **opts):
  287. """Detach the current process in the background (daemonize).
  288. Arguments:
  289. logfile (str): Optional log file.
  290. The ability to write to this file
  291. will be verified before the process is detached.
  292. pidfile (str): Optional pid file.
  293. The pidfile won't be created,
  294. as this is the responsibility of the child. But the process will
  295. exit if the pid lock exists and the pid written is still running.
  296. uid (int, str): Optional user id or user name to change
  297. effective privileges to.
  298. gid (int, str): Optional group id or group name to change
  299. effective privileges to.
  300. umask (str, int): Optional umask that'll be effective in
  301. the child process.
  302. workdir (str): Optional new working directory.
  303. fake (bool): Don't actually detach, intended for debugging purposes.
  304. **opts (Any): Ignored.
  305. Example:
  306. >>> from celery.platforms import detached, create_pidlock
  307. >>> with detached(
  308. ... logfile='/var/log/app.log',
  309. ... pidfile='/var/run/app.pid',
  310. ... uid='nobody'):
  311. ... # Now in detached child process with effective user set to nobody,
  312. ... # and we know that our logfile can be written to, and that
  313. ... # the pidfile isn't locked.
  314. ... pidlock = create_pidlock('/var/run/app.pid')
  315. ...
  316. ... # Run the program
  317. ... program.run(logfile='/var/log/app.log')
  318. """
  319. if not resource:
  320. raise RuntimeError('This platform does not support detach.')
  321. workdir = os.getcwd() if workdir is None else workdir
  322. signals.reset('SIGCLD') # Make sure SIGCLD is using the default handler.
  323. maybe_drop_privileges(uid=uid, gid=gid)
  324. def after_chdir_do():
  325. # Since without stderr any errors will be silently suppressed,
  326. # we need to know that we have access to the logfile.
  327. logfile and open(logfile, 'a').close()
  328. # Doesn't actually create the pidfile, but makes sure it's not stale.
  329. if pidfile:
  330. _create_pidlock(pidfile).release()
  331. return DaemonContext(
  332. umask=umask, workdir=workdir, fake=fake, after_chdir=after_chdir_do,
  333. )
  334. def parse_uid(uid):
  335. """Parse user id.
  336. Arguments:
  337. uid (str, int): Actual uid, or the username of a user.
  338. Returns:
  339. int: The actual uid.
  340. """
  341. try:
  342. return int(uid)
  343. except ValueError:
  344. try:
  345. return pwd.getpwnam(uid).pw_uid
  346. except (AttributeError, KeyError):
  347. raise KeyError('User does not exist: {0}'.format(uid))
  348. def parse_gid(gid):
  349. """Parse group id.
  350. Arguments:
  351. gid (str, int): Actual gid, or the name of a group.
  352. Returns:
  353. int: The actual gid of the group.
  354. """
  355. try:
  356. return int(gid)
  357. except ValueError:
  358. try:
  359. return grp.getgrnam(gid).gr_gid
  360. except (AttributeError, KeyError):
  361. raise KeyError('Group does not exist: {0}'.format(gid))
  362. def _setgroups_hack(groups):
  363. # :fun:`setgroups` may have a platform-dependent limit,
  364. # and it's not always possible to know in advance what this limit
  365. # is, so we use this ugly hack stolen from glibc.
  366. groups = groups[:]
  367. while 1:
  368. try:
  369. return os.setgroups(groups)
  370. except ValueError: # error from Python's check.
  371. if len(groups) <= 1:
  372. raise
  373. groups[:] = groups[:-1]
  374. except OSError as exc: # error from the OS.
  375. if exc.errno != errno.EINVAL or len(groups) <= 1:
  376. raise
  377. groups[:] = groups[:-1]
  378. def setgroups(groups):
  379. """Set active groups from a list of group ids."""
  380. max_groups = None
  381. try:
  382. max_groups = os.sysconf('SC_NGROUPS_MAX')
  383. except Exception: # pylint: disable=broad-except
  384. pass
  385. try:
  386. return _setgroups_hack(groups[:max_groups])
  387. except PermissionError:
  388. if any(group not in groups for group in os.getgroups()):
  389. # we shouldn't be allowed to change to this group.
  390. raise
  391. def initgroups(uid, gid):
  392. """Init process group permissions.
  393. Compat version of :func:`os.initgroups` that was first
  394. added to Python 2.7.
  395. """
  396. if not pwd: # pragma: no cover
  397. return
  398. username = pwd.getpwuid(uid)[0]
  399. if hasattr(os, 'initgroups'): # Python 2.7+
  400. return os.initgroups(username, gid)
  401. groups = [gr.gr_gid for gr in grp.getgrall()
  402. if username in gr.gr_mem]
  403. setgroups(groups)
  404. def setgid(gid):
  405. """Version of :func:`os.setgid` supporting group names."""
  406. os.setgid(parse_gid(gid))
  407. def setuid(uid):
  408. """Version of :func:`os.setuid` supporting usernames."""
  409. os.setuid(parse_uid(uid))
  410. def maybe_drop_privileges(uid=None, gid=None):
  411. """Change process privileges to new user/group.
  412. If UID and GID is specified, the real user/group is changed.
  413. If only UID is specified, the real user is changed, and the group is
  414. changed to the users primary group.
  415. If only GID is specified, only the group is changed.
  416. """
  417. if sys.platform == 'win32':
  418. return
  419. if os.geteuid():
  420. # no point trying to setuid unless we're root.
  421. if not os.getuid():
  422. raise SecurityError('contact support')
  423. uid = uid and parse_uid(uid)
  424. gid = gid and parse_gid(gid)
  425. if uid:
  426. _setuid(uid, gid)
  427. else:
  428. gid and setgid(gid)
  429. if uid and not os.getuid() and not os.geteuid():
  430. raise SecurityError('Still root uid after drop privileges!')
  431. if gid and not os.getgid() and not os.getegid():
  432. raise SecurityError('Still root gid after drop privileges!')
  433. def _setuid(uid, gid):
  434. # If GID isn't defined, get the primary GID of the user.
  435. if not gid and pwd:
  436. gid = pwd.getpwuid(uid).pw_gid
  437. # Must set the GID before initgroups(), as setgid()
  438. # is known to zap the group list on some platforms.
  439. # setgid must happen before setuid (otherwise the setgid operation
  440. # may fail because of insufficient privileges and possibly stay
  441. # in a privileged group).
  442. setgid(gid)
  443. initgroups(uid, gid)
  444. # at last:
  445. setuid(uid)
  446. # ... and make sure privileges cannot be restored:
  447. try:
  448. setuid(0)
  449. except PermissionError:
  450. # we should get here: cannot restore privileges,
  451. # everything was fine.
  452. pass
  453. else:
  454. raise SecurityError(
  455. 'non-root user able to restore privileges after setuid.')
  456. class Signals:
  457. """Convenience interface to :mod:`signals`.
  458. If the requested signal isn't supported on the current platform,
  459. the operation will be ignored.
  460. Example:
  461. >>> from celery.platforms import signals
  462. >>> from proj.handlers import my_handler
  463. >>> signals['INT'] = my_handler
  464. >>> signals['INT']
  465. my_handler
  466. >>> signals.supported('INT')
  467. True
  468. >>> signals.signum('INT')
  469. 2
  470. >>> signals.ignore('USR1')
  471. >>> signals['USR1'] == signals.ignored
  472. True
  473. >>> signals.reset('USR1')
  474. >>> signals['USR1'] == signals.default
  475. True
  476. >>> from proj.handlers import exit_handler, hup_handler
  477. >>> signals.update(INT=exit_handler,
  478. ... TERM=exit_handler,
  479. ... HUP=hup_handler)
  480. """
  481. ignored = _signal.SIG_IGN
  482. default = _signal.SIG_DFL
  483. if hasattr(_signal, 'setitimer'):
  484. def arm_alarm(self, seconds):
  485. _signal.setitimer(_signal.ITIMER_REAL, seconds)
  486. else: # pragma: no cover
  487. try:
  488. from itimer import alarm as _itimer_alarm # noqa
  489. except ImportError:
  490. def arm_alarm(self, seconds): # noqa
  491. _signal.alarm(math.ceil(seconds))
  492. else: # pragma: no cover
  493. def arm_alarm(self, seconds): # noqa
  494. return _itimer_alarm(seconds) # noqa
  495. def reset_alarm(self):
  496. return _signal.alarm(0)
  497. def supported(self, name):
  498. """Return true value if signal by ``name`` exists on this platform."""
  499. try:
  500. return self.signum(name)
  501. except AttributeError:
  502. pass
  503. def signum(self, name):
  504. """Get signal number by name."""
  505. if isinstance(name, numbers.Integral):
  506. return name
  507. if not isinstance(name, str) or not name.isupper():
  508. raise TypeError('signal name must be uppercase string.')
  509. if not name.startswith('SIG'):
  510. name = 'SIG' + name
  511. return getattr(_signal, name)
  512. def reset(self, *signal_names):
  513. """Reset signals to the default signal handler.
  514. Does nothing if the platform has no support for signals,
  515. or the specified signal in particular.
  516. """
  517. self.update((sig, self.default) for sig in signal_names)
  518. def ignore(self, *names):
  519. """Ignore signal using :const:`SIG_IGN`.
  520. Does nothing if the platform has no support for signals,
  521. or the specified signal in particular.
  522. """
  523. self.update((sig, self.ignored) for sig in names)
  524. def __getitem__(self, name):
  525. return _signal.getsignal(self.signum(name))
  526. def __setitem__(self, name, handler):
  527. """Install signal handler.
  528. Does nothing if the current platform has no support for signals,
  529. or the specified signal in particular.
  530. """
  531. try:
  532. _signal.signal(self.signum(name), handler)
  533. except (AttributeError, ValueError):
  534. pass
  535. def update(self, _d_=None, **sigmap):
  536. """Set signal handlers from a mapping."""
  537. for name, handler in dict(_d_ or {}, **sigmap).items():
  538. self[name] = handler
  539. signals = Signals()
  540. get_signal = signals.signum # compat
  541. install_signal_handler = signals.__setitem__ # compat
  542. reset_signal = signals.reset # compat
  543. ignore_signal = signals.ignore # compat
  544. def signal_name(signum):
  545. """Return name of signal from signal number."""
  546. return SIGMAP[signum][3:]
  547. def strargv(argv):
  548. arg_start = 2 if 'manage' in argv[0] else 1
  549. if len(argv) > arg_start:
  550. return ' '.join(argv[arg_start:])
  551. return ''
  552. def set_process_title(progname, info=None):
  553. """Set the :command:`ps` name for the currently running process.
  554. Only works if :pypi:`setproctitle` is installed.
  555. """
  556. proctitle = '[{0}]'.format(progname)
  557. proctitle = '{0} {1}'.format(proctitle, info) if info else proctitle
  558. if _setproctitle:
  559. _setproctitle.setproctitle(safe_str(proctitle))
  560. return proctitle
  561. if os.environ.get('NOSETPS'): # pragma: no cover
  562. def set_mp_process_title(*a, **k):
  563. """Disabled feature."""
  564. pass
  565. else:
  566. def set_mp_process_title(progname, info=None, hostname=None): # noqa
  567. """Set the :command:`ps` name from the current process name.
  568. Only works if :pypi:`setproctitle` is installed.
  569. """
  570. if hostname:
  571. progname = '{0}: {1}'.format(progname, hostname)
  572. name = current_process().name if current_process else 'MainProcess'
  573. return set_process_title('{0}:{1}'.format(progname, name), info=info)
  574. def get_errno_name(n):
  575. """Get errno for string (e.g., ``ENOENT``)."""
  576. if isinstance(n, str):
  577. return getattr(errno, n)
  578. return n
  579. @contextmanager
  580. def ignore_errno(*errnos, **kwargs):
  581. """Context manager to ignore specific POSIX error codes.
  582. Takes a list of error codes to ignore: this can be either
  583. the name of the code, or the code integer itself::
  584. >>> with ignore_errno('ENOENT'):
  585. ... with open('foo', 'r') as fh:
  586. ... return fh.read()
  587. >>> with ignore_errno(errno.ENOENT, errno.EPERM):
  588. ... pass
  589. Arguments:
  590. types (Tuple[Exception]): A tuple of exceptions to ignore
  591. (when the errno matches). Defaults to :exc:`Exception`.
  592. """
  593. types = kwargs.get('types') or (Exception,)
  594. errnos = [get_errno_name(errno) for errno in errnos]
  595. try:
  596. yield
  597. except types as exc:
  598. if not hasattr(exc, 'errno'):
  599. raise
  600. if exc.errno not in errnos:
  601. raise
  602. def check_privileges(accept_content):
  603. uid = os.getuid() if hasattr(os, 'getuid') else 65535
  604. gid = os.getgid() if hasattr(os, 'getgid') else 65535
  605. euid = os.geteuid() if hasattr(os, 'geteuid') else 65535
  606. egid = os.getegid() if hasattr(os, 'getegid') else 65535
  607. if hasattr(os, 'fchown'):
  608. if not all(hasattr(os, attr)
  609. for attr in ['getuid', 'getgid', 'geteuid', 'getegid']):
  610. raise SecurityError('suspicious platform, contact support')
  611. if not uid or not gid or not euid or not egid:
  612. if ('pickle' in accept_content or
  613. 'application/x-python-serialize' in accept_content):
  614. if not C_FORCE_ROOT:
  615. try:
  616. print(ROOT_DISALLOWED.format(
  617. uid=uid, euid=euid, gid=gid, egid=egid,
  618. ), file=sys.stderr)
  619. finally:
  620. os._exit(1)
  621. warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format(
  622. uid=uid, euid=euid, gid=gid, egid=egid,
  623. )))