1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use libc;

#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum ResourceLimit {
    Infinity,
    Unknown,
    Value(libc::rlim_t),
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct ResourceLimits {
    pub soft_limit: ResourceLimit,
    pub hard_limit: ResourceLimit,
}

impl From<libc::rlimit> for ResourceLimits {
    fn from(rs: libc::rlimit) -> Self {
        let soft_limit = match rs.rlim_cur {
            libc::RLIM_INFINITY => ResourceLimit::Infinity,
            other => {
                if libc::RLIM_SAVED_MAX != libc::RLIM_INFINITY && other == libc::RLIM_SAVED_MAX {
                    ResourceLimit::Unknown
                } else if libc::RLIM_SAVED_CUR != libc::RLIM_INFINITY
                    && other == libc::RLIM_SAVED_CUR
                {
                    ResourceLimit::Unknown
                } else {
                    ResourceLimit::Value(other)
                }
            }
        };
        let hard_limit = match rs.rlim_max {
            libc::RLIM_INFINITY => ResourceLimit::Infinity,
            other => {
                if libc::RLIM_SAVED_MAX != libc::RLIM_INFINITY && other == libc::RLIM_SAVED_MAX {
                    ResourceLimit::Unknown
                } else if libc::RLIM_SAVED_CUR != libc::RLIM_INFINITY
                    && other == libc::RLIM_SAVED_CUR
                {
                    ResourceLimit::Unknown
                } else {
                    ResourceLimit::Value(other)
                }
            }
        };
        ResourceLimits {
            soft_limit,
            hard_limit,
        }
    }
}

impl Into<libc::rlimit> for ResourceLimits {
    fn into(self: ResourceLimits) -> libc::rlimit {
        let rlim_cur = match self.soft_limit {
            ResourceLimit::Infinity => libc::RLIM_INFINITY,
            ResourceLimit::Unknown => libc::RLIM_SAVED_CUR,
            ResourceLimit::Value(n) => n,
        };
        let rlim_max = match self.hard_limit {
            ResourceLimit::Infinity => libc::RLIM_INFINITY,
            ResourceLimit::Unknown => libc::RLIM_SAVED_MAX,
            ResourceLimit::Value(n) => n,
        };
        libc::rlimit { rlim_cur, rlim_max }
    }
}

pub enum Resource {
    CoreFileSize,
    CPUTime,
    DataSize,
    FileSize,
    OpenFiles,
    StackSize,
    TotalMemory,
}

impl Into<libc::__rlimit_resource_t> for Resource {
    fn into(self: Resource) -> libc::__rlimit_resource_t {
        match self {
            Resource::CoreFileSize => libc::RLIMIT_CORE,
            Resource::CPUTime => libc::RLIMIT_CPU,
            Resource::DataSize => libc::RLIMIT_DATA,
            Resource::FileSize => libc::RLIMIT_FSIZE,
            Resource::OpenFiles => libc::RLIMIT_NOFILE,
            Resource::StackSize => libc::RLIMIT_STACK,
            Resource::TotalMemory => libc::RLIMIT_AS,
        }
    }
}

impl From<libc::__rlimit_resource_t> for Resource {
    fn from(r: libc::__rlimit_resource_t) -> Self {
        match r {
            libc::RLIMIT_CORE => Resource::CoreFileSize,
            libc::RLIMIT_CPU => Resource::CPUTime,
            libc::RLIMIT_DATA => Resource::DataSize,
            libc::RLIMIT_FSIZE => Resource::FileSize,
            libc::RLIMIT_NOFILE => Resource::OpenFiles,
            libc::RLIMIT_STACK => Resource::StackSize,
            libc::RLIMIT_AS => Resource::TotalMemory,
            _ => panic!("Invalid resource type code"),
        }
    }
}

/// An error value returned from the failure of ['get_resource_limit'].
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum GetRLimitError {
    /// [EINVAL] An invalid resource was specified; or in a setrlimit() call,
    /// the new rlim_cur exceeds the new rlim_max.
    Invalid,
    /// [EPERM] The limit specified to setrlimit() would have raised the maximum
    /// limit value, and the calling process does not have appropriate
    /// privileges.
    Permission,
}

impl std::fmt::Display for GetRLimitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Self::Invalid => write!(f, "EINVAL"),
            Self::Permission => write!(f, "EPERM"),
        }
    }
}

impl std::error::Error for GetRLimitError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Self::Invalid => None,
            Self::Permission => None,
        }
    }
}

/// Get the limit values for a particular resource.
pub fn get_resource_limit(resource: Resource) -> Result<ResourceLimits, GetRLimitError> {
    let mut rlimit: libc::rlimit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    unsafe {
        match libc::getrlimit(resource.into(), &mut rlimit) {
            0 => Ok(rlimit.into()),
            -1 => {
                let errno: *mut libc::c_int = libc::__errno_location();
                Err(match *errno {
                    libc::EINVAL => GetRLimitError::Invalid,
                    libc::EPERM => GetRLimitError::Permission,
                    _ => panic!("Invalid error code"),
                })
            }
            _ => panic!("Invalid error return"),
        }
    }
}

/// An error value returned from the failure of ['set_resource_limit'].
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum SetRLimitError {
    /// [EINVAL] The limit specified cannot be lowered because current usage is
    /// already higher than the limit.
    Invalid,
}

/// Set the limit values for a particular resource.
pub fn set_resource_limit(
    resource: Resource,
    r_limit: ResourceLimits,
) -> Result<(), SetRLimitError> {
    unsafe {
        match libc::setrlimit(resource.into(), &r_limit.into()) {
            0 => Ok(()),
            -1 => {
                let errno: *mut libc::c_int = libc::__errno_location();
                Err(match *errno {
                    libc::EINVAL => SetRLimitError::Invalid,
                    _ => panic!("Invalid error code"),
                })
            }
            _ => panic!("Invalid error return"),
        }
    }
}