1cac7dca0Sopenharmony_ci// Copyright (c) 2023 Huawei Device Co., Ltd.
2cac7dca0Sopenharmony_ci// Licensed under the Apache License, Version 2.0 (the "License");
3cac7dca0Sopenharmony_ci// you may not use this file except in compliance with the License.
4cac7dca0Sopenharmony_ci// You may obtain a copy of the License at
5cac7dca0Sopenharmony_ci//
6cac7dca0Sopenharmony_ci//     http://www.apache.org/licenses/LICENSE-2.0
7cac7dca0Sopenharmony_ci//
8cac7dca0Sopenharmony_ci// Unless required by applicable law or agreed to in writing, software
9cac7dca0Sopenharmony_ci// distributed under the License is distributed on an "AS IS" BASIS,
10cac7dca0Sopenharmony_ci// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11cac7dca0Sopenharmony_ci// See the License for the specific language governing permissions and
12cac7dca0Sopenharmony_ci// limitations under the License.
13cac7dca0Sopenharmony_ci
14cac7dca0Sopenharmony_ciuse std::io;
15cac7dca0Sopenharmony_ci
16cac7dca0Sopenharmony_ciuse libc::c_int;
17cac7dca0Sopenharmony_ci
18cac7dca0Sopenharmony_cipub(crate) fn socket_new(domain: c_int, socket_type: c_int) -> io::Result<c_int> {
19cac7dca0Sopenharmony_ci    #[cfg(target_os = "linux")]
20cac7dca0Sopenharmony_ci    let socket_type = socket_type | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC;
21cac7dca0Sopenharmony_ci    let socket = syscall!(socket(domain, socket_type, 0))?;
22cac7dca0Sopenharmony_ci
23cac7dca0Sopenharmony_ci    #[cfg(target_os = "macos")]
24cac7dca0Sopenharmony_ci    set_non_block(socket)?;
25cac7dca0Sopenharmony_ci    Ok(socket)
26cac7dca0Sopenharmony_ci}
27cac7dca0Sopenharmony_ci
28cac7dca0Sopenharmony_ci#[cfg(target_os = "macos")]
29cac7dca0Sopenharmony_cipub(crate) fn set_non_block(socket: c_int) -> io::Result<()> {
30cac7dca0Sopenharmony_ci    if let Err(e) = syscall!(setsockopt(
31cac7dca0Sopenharmony_ci        socket,
32cac7dca0Sopenharmony_ci        libc::SOL_SOCKET,
33cac7dca0Sopenharmony_ci        libc::SO_NOSIGPIPE,
34cac7dca0Sopenharmony_ci        &1 as *const libc::c_int as *const libc::c_void,
35cac7dca0Sopenharmony_ci        std::mem::size_of::<libc::c_int>() as libc::socklen_t
36cac7dca0Sopenharmony_ci    )) {
37cac7dca0Sopenharmony_ci        let _ = syscall!(close(socket));
38cac7dca0Sopenharmony_ci        return Err(e);
39cac7dca0Sopenharmony_ci    }
40cac7dca0Sopenharmony_ci
41cac7dca0Sopenharmony_ci    if let Err(e) = syscall!(fcntl(socket, libc::F_SETFL, libc::O_NONBLOCK)) {
42cac7dca0Sopenharmony_ci        let _ = syscall!(close(socket));
43cac7dca0Sopenharmony_ci        return Err(e);
44cac7dca0Sopenharmony_ci    }
45cac7dca0Sopenharmony_ci
46cac7dca0Sopenharmony_ci    if let Err(e) = syscall!(fcntl(socket, libc::F_SETFD, libc::FD_CLOEXEC)) {
47cac7dca0Sopenharmony_ci        let _ = syscall!(close(socket));
48cac7dca0Sopenharmony_ci        return Err(e);
49cac7dca0Sopenharmony_ci    }
50cac7dca0Sopenharmony_ci    Ok(())
51cac7dca0Sopenharmony_ci}
52