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 std::ffi::CString;
18 use std::os::unix::io::RawFd;
19 use thiserror::Error;
20
21 /// Errors this crate can generate
22 #[derive(Error, Debug)]
23 pub enum SocketError {
24 /// invalid name parameter
25 #[error("socket name {0} contains NUL byte")]
26 NulError(String),
27
28 /// android_get_control_socket failed to get a fd
29 #[error("android_get_control_socket({0}) failed")]
30 GetControlSocketFailed(String),
31 }
32
33 /// android_get_control_socket - simple helper function to get the file
34 /// descriptor of our init-managed Unix domain socket. `name' is the name of the
35 /// socket, as given in init.rc. Returns -1 on error.
android_get_control_socket(name: &str) -> Result<RawFd, SocketError>36 pub fn android_get_control_socket(name: &str) -> Result<RawFd, SocketError> {
37 let cstr = CString::new(name).map_err(|_| SocketError::NulError(name.to_owned()))?;
38 // SAFETY: android_get_control_socket doesn't take ownership of name
39 let fd = unsafe { cutils_bindgen::android_get_control_socket(cstr.as_ptr()) };
40 if fd < 0 {
41 return Err(SocketError::GetControlSocketFailed(name.to_owned()));
42 }
43 Ok(fd)
44 }
45