forked from NozeIO/swift-nio-irc-client-original-fork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIRCClient.swift
653 lines (535 loc) · 20.8 KB
/
IRCClient.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//===----------------------------------------------------------------------===//
//
// This source file is part of the swift-nio-irc open source project
//
// Copyright (c) 2018-2020 ZeeZide GmbH. and the swift-nio-irc project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIOIRC project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
import NIOIRC
import NIOTLS
import NIOSSL
#if canImport(NIOTransportServices)
import NIOTransportServices
#endif
/**
* A simple IRC client based on SwiftNIO.
*
* Checkout swift-nio-irc-eliza or swift-nio-irc-webclient for examples on this.
*
* The basic flow is:
* - create a `IRCClient` object, quite likely w/ custom `IRCClientOptions`
* - implement and assign an `IRCClientDelegate`, which is going to handle
* incoming commands
* - `connect` the client
*/
open class IRCClient : IRCClientMessageTarget {
public let options : IRCClientOptions
public let eventLoop : EventLoop
public var delegate : IRCClientDelegate?
public enum Error : Swift.Error {
case writeError(Swift.Error)
case stopped
case notImplemented
case internalInconsistency
case unexpectedInput
case channelError(Swift.Error)
}
enum State : CustomStringConvertible {
case disconnected
case connecting
case registering(channel: Channel, nick: IRCNickName, userInfo: IRCUserInfo)
case registered (channel: Channel, nick: IRCNickName, userInfo: IRCUserInfo)
case error (Error)
case requestedQuit
case quit
var isRegistered : Bool {
switch self {
case .registered: return true
default: return false
}
}
var nick : IRCNickName? {
@inline(__always) get {
switch self {
case .registering(_, let v, _): return v
case .registered (_, let v, _): return v
default: return nil
}
}
}
var userInfo : IRCUserInfo? {
@inline(__always) get {
switch self {
case .registering(_, _, let v): return v
case .registered (_, _, let v): return v
default: return nil
}
}
}
var channel : Channel? {
@inline(__always) get {
switch self {
case .registering(let channel, _, _): return channel
case .registered (let channel, _, _): return channel
default: return nil
}
}
}
var canStartConnection : Bool {
switch self {
case .disconnected, .error: return true
case .connecting: return false
case .registering: return false
case .registered: return false
case .requestedQuit, .quit: return false
}
}
var description : String {
switch self {
case .disconnected: return "disconnected"
case .connecting: return "connecting..."
case .registering(_, let nick, _): return "registering<\(nick)>..."
case .registered (_, let nick, _): return "registered<\(nick)>"
case .error (let error): return "error<\(error)>"
case .requestedQuit: return "quitting..."
case .quit: return "quit"
}
}
}
private var state : State = .disconnected
private var userMode = IRCUserMode()
var usermask : String? {
guard case .registered(_, let nick, let info) = state else { return nil }
let host = info.servername ?? options.hostname ?? "??"
return "\(nick.stringValue)!~\(info.username)@\(host)"
}
private let bootstrap : NIOClientTCPBootstrapProtocol
public init(options: IRCClientOptions) {
self.options = options
let eventLoop = options.eventLoopGroup.next()
self.eventLoop = eventLoop
// what a mess :-)
#if canImport(NIOTransportServices)
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
var overrideBootstrap : NIOClientTCPBootstrapProtocol?
if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
if options.eventLoopGroup is NIOTSEventLoopGroup {
overrideBootstrap = NIOTSConnectionBootstrap(group: eventLoop)
}
}
#else
let overrideBootstrap : NIOClientTCPBootstrapProtocol? = nil
#endif
#else
let overrideBootstrap : NIOClientTCPBootstrapProtocol? = nil
#endif
// MARK: - connection bootstrap
self.bootstrap = overrideBootstrap ?? ClientBootstrap(group: eventLoop)
_ = bootstrap.channelOption(ChannelOptions.reuseAddr, value: 1)
_ = bootstrap.channelInitializer { [weak self] channel in
// different types of SSL modes
// FIXME: - make this code look less bad
if options.securityOptions.useSecure {
var sslConfig = TLSConfiguration.makeClientConfiguration()
switch options.securityOptions.verficationMode {
case .strict:
sslConfig.certificateVerification = .fullVerification
case .lax:
sslConfig.certificateVerification = .noHostnameVerification
case .noChecks:
sslConfig.certificateVerification = .none
case .none:
break
}
let sslHandler = try! NIOSSLClientHandler(context: try! NIOSSLContext(configuration: sslConfig), serverHostname: options.hostname)
print("what: \(sslHandler)")
_ = channel.pipeline.addHandler(sslHandler, name: "sslHandler")
}
return channel.pipeline
.addHandler(IRCChannelHandler(), name: "de.zeezide.nio.irc.protocol")
.flatMap { [weak self] _ in
guard let me = self else {
let error = channel.eventLoop.makePromise(of: Void.self)
error.fail(Error.internalInconsistency)
return error.futureResult
}
return channel.pipeline
.addHandler(Handler(client: me),
name: "de.zeezide.nio.irc.client")
}
}
}
deinit {
_ = channel?.close(mode: .all)
}
// MARK: - Commands
open func changeNick(_ nick: IRCNickName) {
send(.NICK(nick))
}
// MARK: - Connect
var retryInfo = IRCRetryInfo()
var channel : Channel? { @inline(__always) get { return state.channel } }
open func connect() {
guard eventLoop.inEventLoop else { return eventLoop.execute(self.connect) }
guard state.canStartConnection else { return }
_ = _connect(host: options.hostname ?? "localhost", port: options.port)
}
private func _connect(host: String, port: Int) -> EventLoopFuture<Channel> {
assert(eventLoop.inEventLoop, "threading issue")
assert(state.canStartConnection, "cannot start connection!")
clearListCollectors()
userMode = IRCUserMode()
state = .connecting
retryInfo.attempt += 1
return bootstrap.connect(host: host, port: port)
.map { channel in
self.retryInfo.registerSuccessfulConnect()
guard case .connecting = self.state else {
assertionFailure("called \(#function) but we are not connecting?")
return channel
}
self.state = .registering(channel: channel,
nick: self.options.nickname,
userInfo: self.options.userInfo)
self._register()
return channel
}
}
private func _register() {
assert(eventLoop.inEventLoop, "threading issue")
guard case .registering(_, let nick, let user) = state else {
assertionFailure("called \(#function) but we are not connecting?")
return
}
if let pwd = options.password {
send(.otherCommand("PASS", [ pwd ]))
}
send(.NICK(nick))
send(.USER(user))
}
func _closeOnUnexpectedError(_ error: Swift.Error? = nil) {
assert(eventLoop.inEventLoop, "threading issue")
if let error = error {
self.retryInfo.lastSocketError = error
}
}
open func close() {
guard eventLoop.inEventLoop else { return eventLoop.execute(close) }
_ = channel?.close(mode: .all)
clearListCollectors()
}
// MARK: - Subscriptions
var subscribedChannels = Set<IRCChannelName>()
private func _resubscribe() {
if !subscribedChannels.isEmpty {
// TODO: issues JOIN commands
}
// TODO: we have no queue, right?
// _processQueue()
}
// MARK: - Retry
#if false // TODO: finish Noze port
private func retryConnectAfterFailure() {
let retryHow : IRCRetryResult
if let cb = options.retryStrategy {
retryHow = cb(retryInfo)
}
else {
if retryInfo.attempt < 10 {
retryHow = .retryAfter(TimeInterval(retryInfo.attempt) * 0.200)
}
else {
retryHow = .stop
}
}
switch retryHow {
case .retryAfter(let timeout):
// TBD: special Retry status?
if state != .connecting {
state = .connecting
eventLoop.scheduleTask(in: .milliseconds(timeout * 1000.0)) {
self.state = .disconnected
self.connect()
}
}
case .error(let error):
stop(error: error)
case .stop:
stop(error: IRCClientError.ConnectionQuit)
}
}
#endif
func handleRegistrationDone() {
guard case .registering(let channel, let nick, let user) = state else {
assertionFailure("called \(#function) but we are not registering?")
return
}
state = .registered(channel: channel, nick: nick, userInfo: user)
delegate?.client(self, registered: nick, with: user)
self._resubscribe()
}
func handleRegistrationFailed(with message: IRCMessage) {
guard case .registering(_, let nick, _) = state else {
assertionFailure("called \(#function) but we are not registering?")
return
}
// TODO: send to delegate
print("ERROR: registration of \(nick) failed:", message)
delegate?.clientFailedToRegister(self)
_closeOnUnexpectedError()
}
// MARK: - List Collectors
var messageOfTheDay = ""
func clearListCollectors() {
messageOfTheDay = ""
}
// MARK: - Handler Delegate
func handlerDidDisconnect(_ context: ChannelHandlerContext) { // Q: own
switch state {
case .error, .quit: break // already handled
case .registering, .connecting:
delegate?.clientFailedToRegister(self)
state = .disconnected
default:
state = .disconnected
}
}
func handlerHandleResult(_ message: IRCMessage) { // Q: own
if case .registering = state {
if message.command.signalsSuccessfulRegistration {
handleRegistrationDone()
}
if case .numeric(.errorNicknameInUse, _) = message.command {
print("NEEDS NEW NICK!")
// TODO: recover using a callback
return handleRegistrationFailed(with: message)
}
else if message.command.isErrorReply {
return handleRegistrationFailed(with: message)
}
}
do {
try irc_msgSend(message)
}
catch let error as IRCDispatcherError {
// TBD:
print("handle dispatcher error:", error)
}
catch {
// TBD:
print("handle generic error:", type(of: error), error)
}
}
func handlerCaughtError(_ error: Swift.Error,
in context: ChannelHandlerContext) // Q: own
{
retryInfo.lastSocketError = error
state = .error(.channelError(error))
print("IRCClient error:", error)
}
// MARK: - Handler
final class Handler : ChannelInboundHandler {
typealias InboundIn = IRCMessage
let client : IRCClient
init(client: IRCClient) {
self.client = client
}
func channelActive(context: ChannelHandlerContext) {
}
func channelInactive(context: ChannelHandlerContext) {
client.handlerDidDisconnect(context)
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let value = unwrapInboundIn(data)
client.handlerHandleResult(value)
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
self.client.handlerCaughtError(error, in: context)
context.close(promise: nil)
}
}
// MARK: - Writing
public var origin : String? { return nil }
public func sendMessages<T: Collection>(_ messages: T,
promise: EventLoopPromise<Void>?)
where T.Element == IRCMessage
{
// TBD: this looks a little more difficult than necessary.
guard let channel = channel else {
promise?.fail(Error.stopped)
return
}
guard channel.eventLoop.inEventLoop else {
return channel.eventLoop.execute {
self.sendMessages(messages, promise: promise)
}
}
let count = messages.count
if count == 0 {
promise?.succeed(())
return
}
if count == 1 {
return channel.writeAndFlush(messages.first!, promise: promise)
}
guard let promise = promise else {
for message in messages {
channel.write(message, promise: nil)
}
return channel.flush()
}
EventLoopFuture<Void>
.andAllSucceed(messages.map { channel.write($0) },
on: promise.futureResult.eventLoop)
.cascade(to: promise)
channel.flush()
}
}
extension ChannelOptions {
static let reuseAddr =
ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET),
SO_REUSEADDR)
}
extension IRCCommand {
var isErrorReply : Bool {
guard case .numeric(let code, _) = self else { return false }
return code.rawValue >= 400 // Hmmm
}
var signalsSuccessfulRegistration : Bool {
switch self {
case .MODE: return true // Freenode sends a MODE
case .numeric(let code, _):
switch code {
case .replyWelcome, .replyYourHost, .replyMotD, .replyEndOfMotD:
return true
default:
return false
}
default: return false
}
}
}
extension IRCClient : IRCDispatcher {
public func irc_msgSend(_ message: NIOIRC.IRCMessage) throws {
do {
return try irc_defaultMsgSend(message)
}
catch let error as IRCDispatcherError {
guard case .doesNotRespondTo = error else { throw error }
}
catch { throw error }
switch message.command {
/* Message of the Day coalescing */
case .numeric(.replyMotDStart, let args):
messageOfTheDay = (args.last ?? "") + "\n"
case .numeric(.replyMotD, let args):
messageOfTheDay += (args.last ?? "") + "\n"
case .numeric(.replyEndOfMotD, _):
if !messageOfTheDay.isEmpty {
delegate?.client(self, messageOfTheDay: messageOfTheDay)
}
messageOfTheDay = ""
/* name reply */
// <IRCCmd: 353 args=Guest1,=,#ZeeQL,Guest1> localhost -
// <IRCCmd: 366 args=Guest1,#ZeeQL,End of /NAMES list> localhost -
case .numeric(.replyNameReply, _ /*let args*/):
#if false
// messageOfTheDay += (args.last ?? "") + "\n"
#else
break
#endif
case .numeric(.replyEndOfNames, _):
#if false
if !messageOfTheDay.isEmpty {
delegate?.client(self, messageOfTheDay: messageOfTheDay)
}
messageOfTheDay = ""
#else
break
#endif
case .numeric(.replyTopic, let args):
// :localhost 332 Guest31 #NIO :Welcome to #nio!
guard args.count > 2, let channel = IRCChannelName(args[1]) else {
return print("ERROR: topic args incomplete:", message)
}
delegate?.client(self, changeTopic: args[2], of: channel)
/* join/part, we need the origin here ... (fix dispatcher) */
case .JOIN(let channels, _):
guard let origin = message.origin, let user = IRCUserID(origin) else {
return print("ERROR: JOIN is missing a proper origin:", message)
}
delegate?.client(self, user: user, joined: channels)
case .PART(let channels, let leaveMessage):
guard let origin = message.origin, let user = IRCUserID(origin) else {
return print("ERROR: JOIN is missing a proper origin:", message)
}
delegate?.client(self, user: user, left: channels, with: leaveMessage)
/* unexpected stuff */
case .otherNumeric(let code, let args):
#if false
print("OTHER NUM:", code, args)
#endif
delegate?.client(self, received: message)
default:
#if false
print("OTHER COMMAND:", message.command,
message.origin ?? "-", message.target ?? "-")
#endif
delegate?.client(self, received: message)
}
}
public func doNotice(recipients: [ IRCMessageRecipient ], message: String)
throws
{
delegate?.client(self, notice: message, for: recipients)
}
public func doMessage(sender : IRCUserID?,
recipients : [ IRCMessageRecipient ],
message : String) throws
{
guard let sender = sender else { // should never happen
// assertionFailure("got empty message sender!")
return
}
delegate?.client(self, message: message, from: sender, for: recipients)
}
public func doNick(_ newNick: IRCNickName) throws {
switch state {
case .registering(let channel, let nick, let info):
guard nick != newNick else { return }
state = .registering(channel: channel, nick: newNick, userInfo: info)
case .registered(let channel, let nick, let info):
guard nick != newNick else { return }
state = .registered(channel: channel, nick: newNick, userInfo: info)
default: return // hmm
}
delegate?.client(self, changedNickTo: newNick)
}
public func doMode(nick: IRCNickName, add: IRCUserMode, remove: IRCUserMode)
throws
{
guard let myNick = state.nick, myNick == nick else {
return
}
var newMode = userMode
newMode.subtract(remove)
newMode.formUnion(add)
if newMode != userMode {
userMode = newMode
delegate?.client(self, changedUserModeTo: newMode)
}
}
public func doPing(_ server: String, server2: String? = nil) throws {
let msg : IRCMessage
msg = IRCMessage(origin: origin, // probably wrong
command: .PONG(server: server, server2: server))
sendMessage(msg)
}
}