blob: 0b7a637db3feae6650b40e8fcf7b4e28b64ae8e9 [file] [log] [blame]
Kino Roy29d87732023-02-20 22:32:43 -08001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
21import Darwin
22#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
23import Glibc
24import Dispatch
25#endif
26import Foundation
27
28private struct Sys {
29#if os(Linux)
30 static let read = Glibc.read
31 static let write = Glibc.write
32 static let close = Glibc.close
33 static let socket = Glibc.socket
34 static let connect = Glibc.connect
35 static let bind = Glibc.bind
36 static let recv = Glibc.recv
37#else
38 static let read = Darwin.read
39 static let write = Darwin.write
40 static let close = Darwin.close
41 static let socket = Darwin.socket
42 static let connect = Darwin.connect
43 static let bind = Darwin.bind
44 static let recv = Darwin.recv
45#endif
46}
47
48
49public class UnixSocket {
50 public var fd: Int32
51 private var socketAddress: sockaddr_un
52
53 public init(path: String) {
54 socketAddress = sockaddr_un()
55 socketAddress.sun_family = sa_family_t(AF_UNIX)
56
57 let lengthOfPath = path.withCString { Int(strlen($0)) }
58
59 guard lengthOfPath < MemoryLayout.size(ofValue: socketAddress.sun_path) else {
60 fatalError()
61 }
62
63 _ = withUnsafeMutablePointer(to: &socketAddress.sun_path.0) { ptr in
64 path.withCString {
65 strncpy(ptr, $0, lengthOfPath)
66 }
67 }
68
69#if os(Linux)
70 fd = Sys.socket(AF_UNIX, 1 /*SOCK_STREAM*/, 0);
71#else
72 fd = Sys.socket(AF_UNIX, SOCK_STREAM, 0);
73#endif
74
75 }
76 public func connect() -> Int32 {
77 let socketAddressCasted = withUnsafePointer(to: &socketAddress) {
78 $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
79 return $0
80 }
81 }
82 return Sys.connect(fd, socketAddressCasted, socklen_t(MemoryLayout<sockaddr_un>.size(ofValue: socketAddress)))
83 }
84 public func bind() -> Int32 {
85 let socketAddressCasted = withUnsafePointer(to: &socketAddress) {
86 $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
87 return $0
88 }
89 }
90 return Sys.bind(fd, socketAddressCasted, socklen_t(MemoryLayout<sockaddr_un>.size(ofValue: socketAddress)))
91 }
92}