-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathYLTelnet.mm
386 lines (354 loc) · 10.9 KB
/
YLTelnet.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
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
//
// YLTelnet.m
// MacBlueTelnet
//
// Created by Yung-Luen Lan on 2006/9/10.
// Copyright 2006 yllan.org. All rights reserved.
//
#import "YLTelnet.h"
#import "YLTerminal.h"
#import "YLSite.h"
#import <sys/types.h>
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <stdlib.h>
#import <netdb.h>
#import <deque>
#ifdef __DUMPPACKET__
const char *_commandName[] = { "SE", "NOP", "DM", "BRK", "IP", "AO", "AYT", "EC", "EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC" };
void dump_packet(unsigned char *s, int length)
{
int i;
char tmp[1024 * 512]; tmp[0] = '\0';
for (i = 0; i < length; i++) {
if (s[i] >= SE) sprintf(tmp, "%s(%s)", tmp, _commandName[s[i] - SE]);
else if (s[i] == 13) sprintf(tmp, "%s(CR)", tmp);
else if (s[i] == 10) sprintf(tmp, "%s(LF)", tmp);
else if (s[i] >= 127 || s[i] < 32) sprintf(tmp, "%s[%#x]", tmp, s[i]);
else sprintf(tmp, "%s%c", tmp, s[i]);
}
NSLog(@"%s", tmp);
}
#endif
@interface YLTelnet (Private)
- (void) connectWithDictionary: (NSDictionary *)d;
- (void) stream: (NSStream *)stream handleEvent: (NSStreamEvent)eventCode;
- (NSString *) lastError;
- (NSHost *) host;
- (void) setHost: (NSHost *)value;
@end
@implementation YLTelnet
- (void) dealloc
{
[self close];
[_host release];
[_sbBuffer release];
[super dealloc];
}
- (void) lookUpDomainName: (NSDictionary *)d
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSString *addr = [d valueForKey: @"addr"];
int port = [[d valueForKey: @"port"] intValue];
NSHost *host = [NSHost hostWithName: addr];
if (host) {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: host, @"host", [NSNumber numberWithInt: port], @"port", nil];
[self performSelectorOnMainThread: @selector(connectWithDictionary:) withObject: dict waitUntilDone: NO];
} else {
[self setIsProcessing: NO];
}
[pool release];
}
- (void) close
{
[self setIsProcessing: NO];
[_inputStream close];
[_inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream release];
_inputStream = nil;
[_outputStream close];
[_outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream release];
_outputStream = nil;
[self setConnected: NO];
[[self terminal] closeConnection];
}
- (void) reconnect
{
if (_host) {
[self close];
[self connectWithDictionary: [NSDictionary dictionaryWithObjectsAndKeys: _host, @"host", [NSNumber numberWithInt: _port], @"port", nil]];
}
}
- (void) connectWithDictionary: (NSDictionary *)d
{
NSHost *host = [d valueForKey: @"host"];
int port = [[d valueForKey: @"port"] intValue];
if (!host) return;
[self setHost: host];
[_terminal clearAll];
[NSStream getStreamsToHost: host
port: port
inputStream: &_inputStream
outputStream: &_outputStream];
[_inputStream retain];
[_outputStream retain];
[_inputStream setDelegate: self];
[_outputStream setDelegate: self];
[_inputStream scheduleInRunLoop: [NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop: [NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
}
- (BOOL) connectToAddress: (NSString *)addr
{
NSArray *a = [addr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @": "]];
if ([a count] == 2) {
int p = [[a objectAtIndex: 1] intValue];
if (p > 0) {
return [self connectToAddress: [a objectAtIndex: 0] port: p];
} else {
return [self connectToAddress: [a objectAtIndex: 0] port: 23];
}
} else if ([a count] == 1) {
return [self connectToAddress: addr port: 23];
}
return NO;
}
- (BOOL) connectToAddress: (NSString *)addr port: (unsigned int)port
{
if (!addr) return NO;
[self setIsProcessing: YES];
if (port == 23)
[self setConnectionAddress: addr];
else
[self setConnectionAddress: [NSString stringWithFormat: @"%@:%d", addr, port]];
_port = port;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: addr, @"addr", [NSNumber numberWithInt: port], @"port", nil];
[self performSelectorInBackground: @selector(lookUpDomainName:) withObject: dict];
return YES;
}
- (void) stream: (NSStream *)stream handleEvent: (NSStreamEvent)eventCode
{
switch(eventCode) {
case NSStreamEventOpenCompleted: {
[self setConnected: YES];
[self setIsProcessing: NO];
[[self terminal] startConnection];
break;
}
case NSStreamEventHasBytesAvailable: {
uint8_t buf[4096];
while ([(NSInputStream *)stream hasBytesAvailable]) {
NSInteger len = [(NSInputStream *)stream read: buf maxLength: 4096];
if (len > 0) {
[self receiveBytes: buf length: len];
}
}
break;
}
case NSStreamEventHasSpaceAvailable: {
break;
}
case NSStreamEventErrorOccurred: {
[self setIsProcessing: NO];
NSLog(@"Error: %@", [stream streamError]);
}
case NSStreamEventEndEncountered: {
[self setIsProcessing: NO];
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[stream release];
if (stream == _inputStream)
_inputStream = nil;
else if (stream == _outputStream)
_outputStream = nil;
[self setConnected: NO];
[[self terminal] closeConnection];
break;
}
}
}
/* Send telnet command */
- (void) sendCommand: (unsigned char)_command option: (unsigned char)_opt
{
unsigned char b[3];
b[0] = IAC;
b[1] = _command;
b[2] = _opt;
NSData *d = [NSData dataWithBytes: b length: 3];
[self performSelector: @selector(sendData:) withObject: d afterDelay: 0.001];
}
- (void) receiveBytes: (unsigned char *)bytes length: (NSUInteger)length
{
unsigned char *stream = (unsigned char *) bytes;
std::deque<unsigned char> terminalBuf;
/* parse the telnet command. */
int L = length;
#ifdef __DUMPPACKET__
// dump_packet(stream, L);
#endif
while (L--) {
unsigned char c = *stream++;
switch (_state) {
case TOP_LEVEL:
case SEENCR:
if (c == NUL && _state == SEENCR)
_state = TOP_LEVEL;
else if (c == IAC)
_state = SEENIAC;
else {
if (!_synch)
terminalBuf.push_back(c);
else if (c == DM)
_synch = NO;
if (c == CR)
_state = SEENCR;
else
_state = TOP_LEVEL;
}
break;
case SEENIAC:
if (c == DO || c == DONT || c == WILL || c == WONT) {
_typeOfOperation = c;
if (c == DO)
_state = SEENDO;
else if (c == DONT)
_state = SEENDONT;
else if (c == WILL)
_state = SEENWILL;
else if (c == WONT)
_state = SEENWONT;
} else if (c == SB)
_state = SEENSB;
else if (c == DM) {
_synch = NO;
_state = TOP_LEVEL;
} else {
/* ignore everything else; print it if it's IAC */
if (c == IAC) {
// TODO: cwrite(c);
}
_state = TOP_LEVEL;
}
break;
case SEENWILL:
{
if (c == TELOPT_ECHO || c == TELOPT_SGA)
[self sendCommand: DO option: c];
else if (c == TELOPT_BINARY)
[self sendCommand: DO option: c];
else
[self sendCommand: DONT option: c];
_state = TOP_LEVEL;
break;
}
case SEENWONT:
[self sendCommand: DONT option: c];
_state = TOP_LEVEL;
break;
case SEENDO:
{
if (c == TELOPT_TTYPE)
[self sendCommand: WILL option: TELOPT_TTYPE];
else if (c == TELOPT_NAWS) {
unsigned char b[] = {IAC, SB, TELOPT_NAWS, 0, 80, 0, 24, IAC, SE};
[self sendCommand: WILL option: TELOPT_NAWS];
[self performSelector: @selector(sendData:) withObject: [NSData dataWithBytes:b length:9] afterDelay: 0.001];
// [self sendBytes: b length: 9];
} else if (c == TELOPT_BINARY) {
[self sendCommand: WILL option: c];
} else
[self sendCommand: WONT option: c];
_state = TOP_LEVEL;
break;
}
case SEENDONT:
[self sendCommand: WONT option: c];
_state = TOP_LEVEL;
break;
case SEENSB:
_sbOption = c;
[_sbBuffer release];
_sbBuffer = [[NSMutableData data] retain];
_state = SUBNEGOT;
break;
case SUBNEGOT:
if (c == IAC)
_state = SUBNEG_IAC;
else
[_sbBuffer appendBytes: &c length: 1];
break;
case SUBNEG_IAC:
/* [IAC,SB,<option code number>,SEND,IAC],SE */
if (c != SE) {
[_sbBuffer appendBytes: &c length: 1];
_state = SUBNEGOT;
} else {
const unsigned char *buf = (const unsigned char *)[_sbBuffer bytes];
if (_sbOption == TELOPT_TTYPE && [_sbBuffer length] == 1 && buf[0] == TELQUAL_SEND) {
unsigned char b[] = {IAC, SB, TELOPT_TTYPE, TELQUAL_IS, 'v', 't', '1', '0', '0', IAC, SE};
[self performSelector:@selector(sendData:) withObject: [NSData dataWithBytes: b length: 11] afterDelay: 0.001];
// [self sendBytes: b length: 11];
}
_state = TOP_LEVEL;
[_sbBuffer release];
_sbBuffer = nil;
}
break;
}
}
unsigned char chunkBuf[1024];
while (!terminalBuf.empty()) {
int length = 1024;
if (terminalBuf.size() < 1024)
length = terminalBuf.size();
int i;
for (i = 0; i < length; i++) {
chunkBuf[i] = terminalBuf.front();
terminalBuf.pop_front();
}
[_terminal feedBytes: chunkBuf length: length connection: self];
}
}
- (void) sendBytes: (unsigned char *)bytes length: (NSInteger)length
{
if (length <= 0) return;
if (!_outputStream) return;
[_lastTouchDate release];
_lastTouchDate = [[NSDate date] retain];
int status = [_outputStream streamStatus];
if (status == NSStreamStatusNotOpen ||
status == NSStreamStatusError ||
status == NSStreamStatusClosed ||
status == NSStreamStatusAtEnd) return;
int result = [_outputStream write: bytes maxLength: length];
if (result == length) return;
if (result <= 0) {
[self performSelector: @selector(sendData:) withObject: [NSData dataWithBytes: bytes length: length] afterDelay: 0.001];
} else {
[self performSelector: @selector(sendData:) withObject: [NSData dataWithBytes: bytes + result length: length - result] afterDelay: 0.001];
}
}
- (void) sendData: (NSData *)data
{
if (!_outputStream) return;
[self sendBytes: (unsigned char *)[data bytes] length: [data length]];
}
- (NSString *) lastError
{
return @"I don't know what error.";
}
- (NSHost *) host
{
return _host;
}
- (void) setHost: (NSHost *)value
{
if (_host != value) {
[_host release];
_host = [value retain];
}
}
@end