tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

can_lower_nice_to.cc (1910B)


      1 // Copyright 2018 The Chromium Authors
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "base/posix/can_lower_nice_to.h"
      6 
      7 #include <limits.h>
      8 #include <sys/resource.h>
      9 #include <sys/types.h>
     10 #include <unistd.h>
     11 
     12 #include "build/build_config.h"
     13 
     14 // Not defined on AIX by default.
     15 #if BUILDFLAG(IS_AIX)
     16 #if defined(RLIMIT_NICE)
     17 #error Assumption about OS_AIX is incorrect
     18 #endif
     19 #define RLIMIT_NICE 20
     20 #endif
     21 
     22 namespace base {
     23 namespace internal {
     24 
     25 bool CanLowerNiceTo(int nice_value) {
     26  // On a POSIX system, the nice value of a thread can be lowered 1. by the root
     27  // user, 2. by a user with the CAP_SYS_NICE permission or 3. by any user if
     28  // the target value is within the range allowed by RLIMIT_NICE.
     29 
     30  // 1. Check for root user.
     31  if (geteuid() == 0) {
     32    return true;
     33  }
     34 
     35  // 2. Skip checking the CAP_SYS_NICE permission because it would require
     36  // libcap.so.
     37 
     38  // 3. Check whether the target value is within the range allowed by
     39  // RLIMIT_NICE.
     40  //
     41  // NZERO should be defined in <limits.h> per POSIX, and should be at least 20.
     42  // (NZERO-1) is the highest possible niceness value (i.e. lowest priority).
     43  // Most platforms use NZERO=20.
     44  //
     45  // RLIMIT_NICE tells us how much we can reduce niceness (increase priority) if
     46  // we start at NZERO. For example, if NZERO is 20 and the rlimit is 30, we can
     47  // lower niceness anywhere within the [-10, 19] range (20 - 30 = -10).
     48  //
     49  // So, we are allowed to reduce niceness to a minimum of NZERO - rlimit:
     50  struct rlimit rlim;
     51  if (getrlimit(RLIMIT_NICE, &rlim) != 0) {
     52    return false;
     53  }
     54  const int lowest_nice_allowed = NZERO - static_cast<int>(rlim.rlim_cur);
     55 
     56  // And lowering niceness to |nice_value| is allowed if it is greater than or
     57  // equal to the limit:
     58  return nice_value >= lowest_nice_allowed;
     59 }
     60 
     61 }  // namespace internal
     62 }  // namespace base