-
Notifications
You must be signed in to change notification settings - Fork 2
/
ConnectionController.mm
349 lines (286 loc) · 7.47 KB
/
ConnectionController.mm
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
#import "ConnectionController.h"
@interface ConnectionController()
-(const char*)simpleCStringConvert:(NSString*)string;
-(void)sendPingback;
@end
@implementation ConnectionController
#ifdef __DEBUG
const char *connected_host;
int connected_port;
#endif
/* Tool Functions/Methods */
-(const char*)simpleCStringConvert:(NSString*)string
{
return [string cStringUsingEncoding:[NSString defaultCStringEncoding]];
}
/* Connection Handling Section */
-(instancetype)init
{
self = [super init];
self.state = kStateDisconnected;
self.host = @"localhost";
self.port = 6667;
self.nick = @"IRCUser";
self.name = @"IRCUser";
self.pass = @"IRCUserPassword";
self.mode = 0;
self->didSendPong = NO;
self->authenticated = NO;
self->finishedRegistering = NO;
self->isAFK = NO;
return self;
}
-(void)establishConnection
{
CFReadStreamRef ingoingConnectionCF;
CFWriteStreamRef outgoingConnectionCF;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)self.host, self.port, &ingoingConnectionCF, &outgoingConnectionCF);
ingoingConnection = (NSInputStream *)ingoingConnectionCF;
outgoingConnection = (NSOutputStream *)outgoingConnectionCF;
[ingoingConnection setDelegate:self];
[outgoingConnection setDelegate:self];
[ingoingConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outgoingConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[ingoingConnection open];
[outgoingConnection open];
#ifdef __DEBUG
connected_host = [self.host UTF8String];
connected_port = self.port;
#endif
[[NSRunLoop currentRunLoop] run];
}
-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
switch(streamEvent){
case NSStreamEventNone:
[self handleEventNone];
break;
case NSStreamEventOpenCompleted:
[self handleConnected];
break;
case NSStreamEventHasBytesAvailable:
[self handleBytesAvailable];
break;
case NSStreamEventErrorOccurred:
[self handleConnectionError];
break;
case NSStreamEventEndEncountered:
[self handleDisconnected];
break;
case NSStreamEventHasSpaceAvailable:
if(!self->authenticated) {
int result = [self handshake];
if(result == 0) {
#ifdef __DEBUG
fprintf(stdout, "[+] Handshake successful!\n");
#endif
self->authenticated = YES;
[NSTimer scheduledTimerWithTimeInterval:PING_TIME target:self selector:@selector(ping) userInfo:nil repeats:YES];
} else if(result == 1) {
fprintf(stderr, "[!] Handshake has failed. Cooldown for 10 secs...\n");
sleep(10);
} else if(result == -1) {
fprintf(stderr, "[!] Handshake has failed. Please connect to the server first.\n");
}
}
break;
}
}
-(void)handleEventNone
{
return;
}
-(void)handleConnected
{
if(self.state == kStateDisconnected){
#ifdef __DEBUG
fprintf(stdout, "[~] Connected to: %s:%d\n", connected_host, connected_port);
#endif
self.state = kStateConnected;
}
}
-(void)handleBytesAvailable
{
uint8_t buf[2048];
int rLen;
while([ingoingConnection hasBytesAvailable]) {
rLen = [ingoingConnection read:buf maxLength:sizeof(buf)];
if(rLen > 0) {
self->dataStream = [[NSString alloc] initWithBytes:buf length:rLen encoding:NSASCIIStringEncoding];
}
if(self->dataStream) {
if(self.printIncomingStream == YES)
#ifdef __DEBUG
fprintf(stdout, "%s", [self simpleCStringConvert:self->dataStream]);
#endif
[self parseBuffer:self->dataStream];
}
}
}
-(void)handleConnectionError
{
#ifdef __DEBUG
fprintf(stderr, "[!] There was an error while connecting to %s:%d", connected_host, connected_port);
#endif
}
-(void)handleDisconnected
{
#ifdef __DEBUG
fprintf(stdout, "[~] Disconnected from %s:%d", connected_host, connected_port);
#endif
self->authenticated = nil;
self->didSendPong = nil;
self.state = kStateDisconnected;
self->finishedRegistering = NO;
}
-(int)send:(NSString*)cmd
{
if(self.state == kStateConnected){
const uint8_t* buffer = (const uint8_t*)[[NSString stringWithFormat:@"%@%@", cmd, CARRIAGE] UTF8String];
if([outgoingConnection write:buffer maxLength:strlen((char *)buffer)] == 0)
return 0;
else
return 1;
}
return -1;
}
/* Command Section */
-(int)handshake
{
#ifdef __DEBUG
fprintf(stdout, "[+] Sending handshake...\n");
#endif
NSString *hndshk_packet = [[IRCProtocol sharedInstance] craftHandshakePacket:self.nick Password:self.pass Mode:self.mode RealName:self.name];
if([self send:hndshk_packet] == -1) {
fprintf(stderr, "[!] Error: Are you connected?\n");
return -1;
}
return 0;
}
-(int)join:(NSString*)channel
{
if(self->finishedRegistering){
#ifdef __DEBUG
fprintf(stdout, "[+] Joining channel...\n");
#endif
NSString *join_packet = [[IRCProtocol sharedInstance] craftJoinPacket:channel];
if([self send:join_packet] == -1) {
fprintf(stderr, "[!] Error: Are you connected?\n");
return -1;
}
} else{
sleep(3);
[self join:channel];
}
return 0;
}
-(int)quit:(NSString*)reason
{
if(self->finishedRegistering){
#ifdef __DEBUG
fprintf(stdout, "[+] Quitting...\n");
#endif
if([self send:[NSString stringWithFormat:@"QUIT :%@", reason]] == -1) {
fprintf(stderr, "[!] Error: Are you connected?\n");
return -1;
}
}
return 0;
}
-(int)AFK:(NSString*)reason;
{
if(self->finishedRegistering){
#ifdef __DEBUG
fprintf(stdout, "[+] Setting AFK...\n");
#endif
if([self send:[NSString stringWithFormat:@"AWAY :%@", reason]] == -1) {
fprintf(stderr, "[!] Error: Are you connected?\n");
return -1;
}
self->isAFK = YES;
}
return 0;
}
-(int)exitAFK
{
if (!(self->isAFK)) {
return -1;
}
if(self->finishedRegistering){
#ifdef __DEBUG
fprintf(stdout, "[+] Exiting AFK...\n");
#endif
if([self send:@"AWAY"] == -1) {
fprintf(stderr, "[!] Error: Are you connected?\n");
return -1;
}
}
return 0;
}
-(int)ping
{
int conn = [self send:@"PING :hey!"];
if(conn != -1){
return 1;
}
return 0;
}
-(void)parseBuffer:(NSString*)dataStream
{
if(self->didSendPong == NO && self->authenticated == YES){
[self sendPingback];
}
[self clientHasReceivedBytes:[[IRCProtocol sharedInstance] parse:self->dataStream]];
}
-(void)clientHasReceivedBytes:(NSMutableArray*)messageArray
{
if(self.delegate) {
[self.delegate clientHasReceivedBytes:messageArray];
} else {
#ifdef __DEBUG
fprintf(stdout, "[!] No delegate has been set!");
#endif
}
if(self->finishedRegistering == NO) {
for(IRCMessage* msg in messageArray) {
if([msg.command isEqual:@"255"]) {
self->finishedRegistering = YES;
}
}
}
}
-(void)endConnection
{
[ingoingConnection close];
[outgoingConnection close];
[self handleDisconnected];
}
-(void)sendPingback
{
if(self->didSendPong == NO && self->authenticated == YES){
NSArray *arr = [self->dataStream componentsSeparatedByString:@"\n"];
for (int i = 0; i < [arr count]; ++i) {
if ([arr[i] hasPrefix:@"PING"]) {
NSString *pingback = [arr[i] componentsSeparatedByString:@"PING :"][1];
[self send:[NSString stringWithFormat:@"PONG :%@", pingback]];
didSendPong = YES;
}
}
}
}
-(void)leaveChannel:(NSString*)channel{
if(channel){
if(self->finishedRegistering==YES){
[self send:[NSString stringWithFormat:@"PART %@",channel]];
}else{sleep(1);[self leaveChannel:channel];}
}
}
-(void)msg:(NSString*)msg toChannel:(NSString*)channel{
if(msg && channel && self->finishedRegistering == YES){
[self send:[NSString stringWithFormat:@":%@ PRIVMSG %@ :%@",self.nick,channel,msg]];
}
}
-(void)connect{
[NSThread detachNewThreadSelector:@selector(establishConnection) toTarget:self withObject:nil];
}
@end