github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/rlimits.cc (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  #include <sys/resource.h>
    16  #include <sys/time.h>
    17  
    18  #include "test/util/capability_util.h"
    19  #include "test/util/test_util.h"
    20  
    21  namespace gvisor {
    22  namespace testing {
    23  
    24  namespace {
    25  
    26  TEST(RlimitTest, SetRlimitHigher) {
    27    SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_RESOURCE)));
    28  
    29    struct rlimit rl = {};
    30    EXPECT_THAT(getrlimit(RLIMIT_NOFILE, &rl), SyscallSucceeds());
    31  
    32    // Lower the rlimit first, as it may be equal to /proc/sys/fs/nr_open, in
    33    // which case even users with CAP_SYS_RESOURCE can't raise it.
    34    rl.rlim_cur--;
    35    rl.rlim_max--;
    36    ASSERT_THAT(setrlimit(RLIMIT_NOFILE, &rl), SyscallSucceeds());
    37  
    38    rl.rlim_max++;
    39    EXPECT_THAT(setrlimit(RLIMIT_NOFILE, &rl), SyscallSucceeds());
    40  }
    41  
    42  TEST(RlimitTest, UnprivilegedSetRlimit) {
    43    // Drop privileges if necessary.
    44    AutoCapability cap(CAP_SYS_RESOURCE, false);
    45  
    46    struct rlimit rl = {};
    47    rl.rlim_cur = 1000;
    48    rl.rlim_max = 20000;
    49    EXPECT_THAT(setrlimit(RLIMIT_NOFILE, &rl), SyscallSucceeds());
    50  
    51    struct rlimit rl2 = {};
    52    EXPECT_THAT(getrlimit(RLIMIT_NOFILE, &rl2), SyscallSucceeds());
    53    EXPECT_EQ(rl.rlim_cur, rl2.rlim_cur);
    54    EXPECT_EQ(rl.rlim_max, rl2.rlim_max);
    55  
    56    rl.rlim_max = 100000;
    57    EXPECT_THAT(setrlimit(RLIMIT_NOFILE, &rl), SyscallFailsWithErrno(EPERM));
    58  }
    59  
    60  TEST(RlimitTest, SetSoftRlimitAboveHard) {
    61    SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_RESOURCE)));
    62  
    63    struct rlimit rl = {};
    64    EXPECT_THAT(getrlimit(RLIMIT_NOFILE, &rl), SyscallSucceeds());
    65  
    66    rl.rlim_cur = rl.rlim_max + 1;
    67    EXPECT_THAT(setrlimit(RLIMIT_NOFILE, &rl), SyscallFailsWithErrno(EINVAL));
    68  }
    69  
    70  }  // namespace
    71  
    72  }  // namespace testing
    73  }  // namespace gvisor