1 // Copyright (C) 2022 The Android Open Source Project
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 //! Provides utilities for sockets.
16
17 use nix::errno::Errno;
18 use nix::fcntl::{fcntl, FdFlag, F_SETFD};
19 use std::ffi::CString;
20 use std::os::unix::io::RawFd;
21 use thiserror::Error;
22
23 /// Errors this crate can generate
24 #[derive(Error, Debug)]
25 pub enum SocketError {
26 /// invalid name parameter
27 #[error("socket name {0} contains NUL byte")]
28 NulError(String),
29
30 /// android_get_control_socket failed to get a fd
31 #[error("android_get_control_socket({0}) failed")]
32 GetControlSocketFailed(String),
33
34 /// Failed to execute fcntl
35 #[error("Failed to execute fcntl {0}")]
36 FcntlFailed(Errno),
37 }
38
39 /// android_get_control_socket - simple helper function to get the file
40 /// descriptor of our init-managed Unix domain socket. `name' is the name of the
41 /// socket, as given in init.rc. Returns -1 on error.
42 /// The returned file descriptor has the flag CLOEXEC set.
android_get_control_socket(name: &str) -> Result<RawFd, SocketError>43 pub fn android_get_control_socket(name: &str) -> Result<RawFd, SocketError> {
44 let cstr = CString::new(name).map_err(|_| SocketError::NulError(name.to_owned()))?;
45 // SAFETY: android_get_control_socket doesn't take ownership of name
46 let fd = unsafe { cutils_bindgen::android_get_control_socket(cstr.as_ptr()) };
47 if fd < 0 {
48 return Err(SocketError::GetControlSocketFailed(name.to_owned()));
49 }
50 // The file descriptor had CLOEXEC disabled to be inherited from the parent.
51 fcntl(fd, F_SETFD(FdFlag::FD_CLOEXEC)).map_err(SocketError::FcntlFailed)?;
52 Ok(fd)
53 }
54