-
Notifications
You must be signed in to change notification settings - Fork 35
/
Socket.swift
290 lines (234 loc) · 6.79 KB
/
Socket.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#if os(Linux)
import Glibc
private let sock_stream = Int32(SOCK_STREAM.rawValue)
private let system_accept = Glibc.accept
private let system_bind = Glibc.bind
private let system_listen = Glibc.listen
private let system_send = Glibc.send
private let system_write = Glibc.write
private let system_shutdown = Glibc.shutdown
private let system_select = Glibc.select
private let system_pipe = Glibc.pipe
#else
import Darwin.C
private let sock_stream = SOCK_STREAM
private let system_accept = Darwin.accept
private let system_bind = Darwin.bind
private let system_listen = Darwin.listen
private let system_send = Darwin.send
private let system_write = Darwin.write
private let system_shutdown = Darwin.shutdown
private let system_select = Darwin.select
private let system_pipe = Darwin.pipe
#endif
import fd
struct SocketError : Error, CustomStringConvertible {
let function: String
let number: Int32
init(function: String = #function) {
self.function = function
self.number = errno
}
var description: String {
return "Socket.\(function) failed [\(number)]"
}
}
protocol Readable {
func read(_ bytes: Int) throws -> [Int8]
}
class Unreader : Readable {
let reader: Readable
var buffer: [Int8] = []
init(reader: Readable) {
self.reader = reader
}
func read(_ bytes: Int) throws -> [Int8] {
if !buffer.isEmpty {
let buffer = self.buffer
self.buffer = []
return buffer
}
return try reader.read(bytes)
}
func unread(_ buffer: [Int8]) {
self.buffer += buffer
}
}
/// Represents a TCP AF_INET/AF_UNIX socket
final public class Socket : Readable, FileDescriptor, ReadableFileDescriptor, Listener, Connection {
typealias Port = UInt16
public let fileNumber: FileNumber
class func pipe() throws -> (read: Socket, write: Socket) {
var fds: [Int32] = [0, 0]
if system_pipe(&fds) == -1 {
throw SocketError()
}
return (Socket(descriptor: fds[0]), Socket(descriptor: fds[1]))
}
init(family: Int32 = AF_INET) throws {
#if os(Linux)
fileNumber = socket(family, sock_stream, 0)
#else
fileNumber = socket(family, sock_stream, family == AF_UNIX ? 0 : IPPROTO_TCP)
#endif
assert(fileNumber > 0)
var value: Int32 = 1;
guard setsockopt(fileNumber, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(MemoryLayout<Int32>.size)) != -1 else {
throw SocketError(function: "setsockopt()")
}
#if !os(Linux)
guard setsockopt(fileNumber, SOL_SOCKET, SO_NOSIGPIPE, &value, socklen_t(MemoryLayout<Int32>.size)) != -1 else {
throw SocketError(function: "setsockopt()")
}
#endif
}
init(descriptor: FileNumber) {
self.fileNumber = descriptor
}
func listen(_ backlog: Int32) throws {
if system_listen(fileNumber, backlog) == -1 {
throw SocketError()
}
}
func bind(_ address: String, port: Port) throws {
var addr = sockaddr_in()
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = in_port_t(htons(in_port_t(port)))
addr.sin_addr = in_addr(s_addr: address.withCString { inet_addr($0) })
addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
let len = socklen_t(UInt8(MemoryLayout<sockaddr_in>.size))
try withUnsafePointer(to: &addr) {
try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
guard system_bind(fileNumber, $0, len) != -1 else {
throw SocketError()
}
}
}
}
func bind(_ path: String) throws {
var addr = sockaddr_un()
addr.sun_family = sa_family_t(AF_UNIX)
let lengthOfPath = path.withCString { Int(strlen($0)) }
guard lengthOfPath < MemoryLayout.size(ofValue: addr.sun_path) else {
throw SocketError()
}
_ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in
path.withCString {
strncpy(ptr, $0, lengthOfPath)
}
}
try withUnsafePointer(to: &addr) {
try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
guard system_bind(fileNumber, $0, UInt32(MemoryLayout<sockaddr_un>.stride)) != -1 else {
throw SocketError()
}
}
}
}
public func accept() throws -> Connection {
let descriptor = system_accept(fileNumber, nil, nil)
if descriptor == -1 {
throw SocketError()
}
return Socket(descriptor: descriptor)
}
func shutdown() {
_ = system_shutdown(fileNumber, Int32(SHUT_RDWR))
}
func send(_ output: String) {
output.withCString { bytes in
#if os(Linux)
let flags = Int32(MSG_NOSIGNAL)
#else
let flags = Int32(0)
#endif
_ = system_send(fileNumber, bytes, Int(strlen(bytes)), flags)
}
}
func send(_ bytes: [UInt8]) {
#if os(Linux)
let flags = Int32(MSG_NOSIGNAL)
#else
let flags = Int32(0)
#endif
_ = system_send(fileNumber, bytes, bytes.count, flags)
}
func write(_ output: String) {
_ = output.withCString { bytes in
system_write(fileNumber, bytes, Int(strlen(bytes)))
}
}
/// Returns whether the socket is set to non-blocking or blocking
var blocking: Bool {
get {
let flags = fcntl(fileNumber, F_GETFL, 0)
return flags & O_NONBLOCK == 0
}
set {
let flags = fcntl(fileNumber, F_GETFL, 0)
let newFlags: Int32
if newValue {
newFlags = flags & ~O_NONBLOCK
} else {
newFlags = flags | O_NONBLOCK
}
let _ = fcntl(fileNumber, F_SETFL, newFlags)
}
}
/// Returns whether the socket is has the FD_CLOEXEC flag set
var closeOnExec: Bool {
get {
let flags = fcntl(fileNumber, F_GETFL, 0)
return flags & FD_CLOEXEC == 1
}
set {
let flags = fcntl(fileNumber, F_GETFL, 0)
let newFlags: Int32
if newValue {
newFlags = flags ^ FD_CLOEXEC
} else {
newFlags = flags | FD_CLOEXEC
}
let _ = fcntl(fileNumber, F_SETFL, newFlags)
}
}
fileprivate func htons(_ value: CUnsignedShort) -> CUnsignedShort {
return (value << 8) + (value >> 8)
}
}
extension FileDescriptor {
/// Returns whether the socket is set to non-blocking or blocking
var blocking: Bool {
get {
let flags = fcntl(fileNumber, F_GETFL, 0)
return flags & O_NONBLOCK == 0
}
set {
let flags = fcntl(fileNumber, F_GETFL, 0)
let newFlags: Int32
if newValue {
newFlags = flags & ~O_NONBLOCK
} else {
newFlags = flags | O_NONBLOCK
}
let _ = fcntl(fileNumber, F_SETFL, newFlags)
}
}
/// Returns whether the socket is has the FD_CLOEXEC flag set
var closeOnExec: Bool {
get {
let flags = fcntl(fileNumber, F_GETFL, 0)
return flags & FD_CLOEXEC == 1
}
set {
let flags = fcntl(fileNumber, F_GETFL, 0)
let newFlags: Int32
if newValue {
newFlags = flags ^ FD_CLOEXEC
} else {
newFlags = flags | FD_CLOEXEC
}
let _ = fcntl(fileNumber, F_SETFL, newFlags)
}
}
}