mirror of
https://github.com/apple/swift-nio
synced 2026-11-23 04:34:23 +00:00
* Move all syscalls that also need to handle errno in an extra file and ensure we not get any problems with invalid errno handling Motivation: Because it is possible ARC cause an syscall and so set the errno value we need to ensure no ARC can ever happen before we were able to read the errno value that was caused by an syscall we made. Modifications: Move all syscalls to an extra file (System.swift) and ensure all exposed methods are marked with `@inline(never)` and not capture any classes. This ensures no ARC can ever happen. Result: Be able to safely read errno if needed. * Comments
56 lines
1.8 KiB
Swift
56 lines
1.8 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
|
import Darwin
|
|
#elseif os(Linux)
|
|
import Glibc
|
|
#endif
|
|
|
|
|
|
// TODO: Handle AF_INET6 as well
|
|
final class ServerSocket: BaseSocket {
|
|
public class func bootstrap(protocolFamily: Int32, host: String, port: Int32) throws -> ServerSocket {
|
|
let socket = try ServerSocket(protocolFamily: protocolFamily)
|
|
try socket.bind(to: SocketAddress.newAddressResolving(host: host, port: port))
|
|
try socket.listen()
|
|
return socket
|
|
}
|
|
|
|
init(protocolFamily: Int32) throws {
|
|
let sock = try BaseSocket.newSocket(protocolFamily: protocolFamily)
|
|
super.init(descriptor: sock)
|
|
}
|
|
|
|
func listen(backlog: Int32 = 128) throws {
|
|
_ = try Posix.listen(descriptor: descriptor, backlog: backlog)
|
|
}
|
|
|
|
func accept() throws -> Socket? {
|
|
var acceptAddr = sockaddr_in()
|
|
var addrSize = socklen_t(MemoryLayout<sockaddr_in>.size)
|
|
|
|
let result = try withUnsafeMutablePointer(to: &acceptAddr) { ptr in
|
|
try ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { ptr in
|
|
try Posix.accept(descriptor: self.descriptor, addr: ptr, len: &addrSize)
|
|
}
|
|
}
|
|
|
|
guard let fd = result else {
|
|
return nil
|
|
}
|
|
return Socket(descriptor: fd)
|
|
}
|
|
}
|