Oolite
Loading...
Searching...
No Matches
OODebugTCPConsoleClient.m
Go to the documentation of this file.
1/*
2
3OODebugTCPConsoleClient.m
4
5
6Oolite Debug Support
7
8Copyright (C) 2009-2013 Jens Ayton and contributors
9
10Permission is hereby granted, free of charge, to any person obtaining a copy
11of this software and associated documentation files (the "Software"), to deal
12in the Software without restriction, including without limitation the rights
13to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14copies of the Software, and to permit persons to whom the Software is
15furnished to do so, subject to the following conditions:
16
17The above copyright notice and this permission notice shall be included in all
18copies or substantial portions of the Software.
19
20THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26SOFTWARE.
27
28*/
29
30#ifdef OO_DEBUG_MONITOR_ENABLED
31
34#import "OODebugMonitor.h"
37#import "OOLogging.h"
38#include <stdint.h>
39
40#if OOLITE_WINDOWS
41#include <winsock2.h>
42#else
43#include <arpa/inet.h> // For htonl
44#endif
45
46#if OOLITE_MAC_OS_X
47#include <fcntl.h>
48#include <netdb.h>
49#include <sys/select.h>
50#include <sys/socket.h>
51#include <unistd.h>
52
53static int OOConnectTCPSocket(NSString* address, uint16_t port, int timeoutSeconds);
54#endif
55
58
59#ifdef OO_LOG_DEBUG_PROTOCOL_PACKETS
60static void LogSendPacket(NSDictionary* packet);
61#else
62#define LogSendPacket(packet) \
63 do { \
64 } while (0)
65#endif
66
67static void DecoderPacket(void* cbInfo, OOALStringRef packetType, OOALDictionaryRef packet);
68static void DecoderError(void* cbInfo, OOALStringRef errorDesc);
69
70OOINLINE BOOL StatusIsSendable(OOTCPClientConnectionStatus status)
71{
73}
74
75@interface OODebugTCPConsoleClient (OOPrivate)
76
77- (void)closeConnection;
78
79- (BOOL)sendBytes:(const void*)bytes count:(size_t)count;
80- (void)sendDictionary:(NSDictionary*)dictionary;
81
82- (void)sendPacket:(NSString*)packetType
83 withParameters:(NSDictionary*)parameters;
84
85- (void)sendPacket:(NSString*)packetType
86 withValue:(id)value
87 forParameter:(NSString*)paramKey;
88
89- (void)readData;
90- (void)dispatchPacket:(NSDictionary*)packet ofType:(NSString*)packetType;
91
92- (void)handleApproveConnectionPacket:(NSDictionary*)packet;
93- (void)handleRejectConnectionPacket:(NSDictionary*)packet;
94- (void)handleCloseConnectionPacket:(NSDictionary*)packet;
95- (void)handleNoteConfigurationChangePacket:(NSDictionary*)packet;
96- (void)handlePerformCommandPacket:(NSDictionary*)packet;
97- (void)handleRequestConfigurationValuePacket:(NSDictionary*)packet;
98- (void)handlePingPacket:(NSDictionary*)packet;
99- (void)handlePongPacket:(NSDictionary*)packet;
100
101- (void)disconnectFromServerWithMessage:(NSString*)message;
102- (void)breakConnectionWithMessage:(NSString*)message;
103- (void)breakConnectionWithBadStream:(NSStream*)stream;
104
105@end
106
107@implementation OODebugTCPConsoleClient
108
109- (id)init
110{
111 return [self initWithAddress:nil port:0];
112}
113
114- (id)initWithAddress:(NSString*)address port:(uint16_t)port
115{
116 BOOL OK = NO;
117 NSDictionary* parameters = nil;
118
119 if (address == nil)
120 address = @"127.0.0.1";
121 if (port == 0)
122 port = kOOTCPConsolePort;
123
124 self = [super init];
125 if (self != nil) {
126#if OOLITE_MAC_OS_X
127 /* Connect a plain socket and wrap it in streams. Letting CFNetwork connect
128 by host name stalled for many seconds on CI virtual machines, and
129 NSHost does blocking DNS lookups.
130 */
131 _host = [address copy];
132 int socketFD = OOConnectTCPSocket(_host, port, 3);
133 if (socketFD >= 0) {
134 CFReadStreamRef readStream = NULL;
135 CFWriteStreamRef writeStream = NULL;
136 CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketFD, &readStream, &writeStream);
137 if (readStream != NULL && writeStream != NULL) {
138 CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
139 _inStream = [(NSInputStream*)readStream autorelease];
140 _outStream = [(NSOutputStream*)writeStream autorelease];
141 } else {
142 if (readStream != NULL)
143 CFRelease(readStream);
144 if (writeStream != NULL)
145 CFRelease(writeStream);
146 close(socketFD);
147 }
148 }
149#else
150 _host = [NSHost hostWithName:address];
151 if (_host != nil) {
152 [_host retain];
153 [NSStream getStreamsToHost:_host
154 port:port
155 inputStream:&_inStream
156 outputStream:&_outStream];
157 }
158#endif
159
160 if (_inStream != nil && _outStream != nil) {
161 [_inStream retain];
162 [_outStream retain];
163 [_inStream setDelegate:self];
164 [_outStream setDelegate:self];
165 [_inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
166 [_outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
167 [_inStream open];
168 [_outStream open];
169
170 // Need to wait for the streams to reach open status before we can send packets
171 // TODO: Might be neater to use the handleEvent callback to flag this.. - Micha 20090425
172 NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];
173 NSDate* timeOut = [NSDate dateWithTimeIntervalSinceNow:3]; // Wait up to 3 seconds
174 while (_host != nil && ([_inStream streamStatus] < 2 || [_outStream streamStatus] < 2) &&
175 [myRunLoop runMode:NSDefaultRunLoopMode
176 beforeDate:timeOut])
177 ; // Wait
178
179 _decoder = OOTCPStreamDecoderCreate(DecoderPacket, DecoderError, NULL, self);
180 }
181
182 if (_decoder != NULL) {
183 OK = YES;
185
186 // Attempt to connect
187 parameters = [NSDictionary dictionaryWithObjectsAndKeys:
188 [NSNumber numberWithUnsignedInt:kOOTCPProtocolVersion_1_1_0], kOOTCPProtocolVersion,
189 [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"], kOOTCPOoliteVersion,
190 nil];
191 [self sendPacket:kOOTCPPacket_RequestConnection
192 withParameters:parameters];
193
196 else
197 OK = NO; // Connection failed.
198 }
199
200 if (!OK) {
201 OOLog(@"debugTCP.connect.failed", @"Failed to connect to debug console at address %@:%i.", address, port);
202 [self release];
203 self = nil;
204 }
205 }
206
207 return self;
208}
209
210- (void)dealloc
211{
212 if (StatusIsSendable(_status)) {
213 [self disconnectFromServerWithMessage:@"TCP console bridge unexpectedly released while active."];
214 }
215 if (_monitor) {
216 [_monitor disconnectDebugger:self message:@"TCP console bridge unexpectedly released while active."];
217 }
218
219 [self closeConnection];
220
222 _decoder = NULL;
223
224 [super dealloc];
225}
226
227- (BOOL)connectDebugMonitor:(in OODebugMonitor*)debugMonitor
228 errorMessage:(out NSString**)message
229{
230 if (_status == kOOTCPClientConnectionRefused) {
231 if (message != NULL)
232 *message = @"Connection refused.";
233 return NO;
234 }
235 if (_status == kOOTCPClientDisconnected) {
236 if (message != NULL)
237 *message = @"Cannot reconnect after disconnecting.";
238 return NO;
239 }
240
241 _monitor = debugMonitor;
242
243 return YES;
244}
245
246- (void)disconnectDebugMonitor:(in OODebugMonitor*)debugMonitor
247 message:(in NSString*)message
248{
249 [self disconnectFromServerWithMessage:message];
250 _monitor = nil;
251}
252
253- (oneway void)debugMonitor:(in OODebugMonitor*)debugMonitor
254 jsConsoleOutput:(in NSString*)output
255 colorKey:(in NSString*)colorKey
256 emphasisRange:(in NSRange)emphasisRange
257{
258 NSMutableDictionary* parameters = nil;
259 NSArray* range = nil;
260
261 parameters = [NSMutableDictionary dictionaryWithCapacity:3];
262 [parameters setObject:output forKey:kOOTCPMessage];
263 [parameters setObject:colorKey ? colorKey : (NSString*)@"general" forKey:kOOTCPColorKey];
264 if (emphasisRange.length != 0) {
265 range = [NSArray arrayWithObjects:
266 [NSNumber numberWithUnsignedInteger:emphasisRange.location],
267 [NSNumber numberWithUnsignedInteger:emphasisRange.length],
268 nil];
269 [parameters setObject:range forKey:kOOTCPEmphasisRanges];
270 }
271
272 [self sendPacket:kOOTCPPacket_ConsoleOutput
273 withParameters:parameters];
274}
275
276- (oneway void)debugMonitorClearConsole:(in OODebugMonitor*)debugMonitor
277{
278 [self sendPacket:kOOTCPPacket_ClearConsole
279 withParameters:nil];
280}
281
282- (oneway void)debugMonitorShowConsole:(in OODebugMonitor*)debugMonitor
283{
284 [self sendPacket:kOOTCPPacket_ShowConsole
285 withParameters:nil];
286}
287
288- (oneway void)debugMonitor:(in OODebugMonitor*)debugMonitor
289 noteConfiguration:(in NSDictionary*)configuration
290{
291 [self sendPacket:kOOTCPPacket_NoteConfiguration
292 withValue:configuration
293 forParameter:kOOTCPConfiguration];
294}
295
296- (oneway void)debugMonitor:(in OODebugMonitor*)debugMonitor
297 noteChangedConfigrationValue:(in id)newValue
298 forKey:(in NSString*)key
299{
300 if (newValue != nil) {
301 [self sendPacket:kOOTCPPacket_NoteConfiguration
302 withValue:[NSDictionary dictionaryWithObject:newValue forKey:key]
303 forParameter:kOOTCPConfiguration];
304 } else {
305 [self sendPacket:kOOTCPPacket_NoteConfiguration
306 withValue:[NSArray arrayWithObject:key]
307 forParameter:kOOTCPRemovedConfigurationKeys];
308 }
309}
310
311- (void)stream:(NSStream*)stream handleEvent:(NSStreamEvent)eventCode
312{
313 if (_status > kOOTCPClientConnected)
314 return;
315
316 if (stream == _inStream && eventCode == NSStreamEventHasBytesAvailable) {
317 [self readData];
318 } else if (eventCode == NSStreamEventErrorOccurred) {
319 [self breakConnectionWithBadStream:stream];
320 } else if (eventCode == NSStreamEventErrorOccurred) {
321 [self breakConnectionWithMessage:[NSString stringWithFormat:
322 @"Console closed the connection."]];
323 }
324}
325
326@end
327
328@implementation OODebugTCPConsoleClient (OOPrivate)
329
330- (void)closeConnection
331{
332 [_inStream close];
333 [_inStream setDelegate:nil];
334 [_inStream release];
335 _inStream = nil;
336
337 [_outStream close];
338 [_outStream setDelegate:nil];
339 [_outStream release];
340 _outStream = nil;
341
342 [_host release];
343 _host = nil;
344}
345
346- (BOOL)sendBytes:(const void*)bytes count:(size_t)count
347{
348 if (bytes == NULL || count == 0)
349 return YES;
350 if (!StatusIsSendable(_status) || _outStream == nil)
351 return NO;
352
353 do {
354 NSInteger written = [_outStream write:bytes maxLength:count];
355 if (written < 1)
356 return NO;
357
358 count -= written;
359 bytes += written;
360 } while (count > 0);
361
362 return YES;
363}
364
365- (void)sendDictionary:(NSDictionary*)dictionary
366{
367 NSData* data = nil;
368 NSString* errorDesc = NULL;
369 size_t count;
370 const uint8_t* bytes = NULL;
371 uint32_t header;
372 bool sentOK = YES;
373
374 if (dictionary == nil || !StatusIsSendable(_status))
375 return;
376
377 data = [NSPropertyListSerialization dataFromPropertyList:dictionary
378 format:NSPropertyListXMLFormat_v1_0
379 errorDescription:&errorDesc];
380
381 if (data == nil) {
382 OOLog(@"debugTCP.conversionFailure", @"Could not convert dictionary to data for transmission to debug console: %@", errorDesc != NULL ? errorDesc : (NSString*)@"unknown error.");
383#if OOLITE_RELEASE_PLIST_ERROR_STRINGS
384 [errorDesc autorelease];
385#endif
386 return;
387 }
388
389 LogSendPacket(dictionary);
390
391 count = [data length];
392 if (count == 0)
393 return;
394 header = htonl(count);
395
396 bytes = [data bytes];
397
398 /* In testing, all bad stream errors were caused by the python console
399 rejecting headers. Made the protocol a bit more fault tolerant.
400 -- Kaks 2012.03.24
401 */
402 if (![self sendBytes:&header count:sizeof header]) {
403 OOLog(@"debugTCP.send.warning", @"%@", @"Error sending packet header, retrying.");
404 // wait 8 milliseconds, resend the header
405 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.008]];
406 if (![self sendBytes:&header count:sizeof header]) {
407 // OOLog(@"debugTCP.send.warning", @"Error sending packet header, retrying one more time.");
408 // wait 16 milliseconds, try to resend the header one last time!
409 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.016]];
410 if (![self sendBytes:&header count:sizeof header]) {
411 sentOK = NO;
412 }
413 }
414 }
415
416 if (sentOK && ![self sendBytes:bytes count:count]) {
417 OOLog(@"debugTCP.send.warning", @"%@", @"Error sending packet body, retrying.");
418 // wait 8 milliseconds, try again.
419 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.008]];
420 if (![self sendBytes:bytes count:count]) {
421 sentOK = NO;
422 }
423 }
424
425 if (!sentOK) {
426 OOLog(@"debugTCP.send.error", @"The following packet could not be sent: %@", dictionary);
427 if (![[OODebugMonitor sharedDebugMonitor] TCPIgnoresDroppedPackets]) {
428 [self breakConnectionWithBadStream:_outStream];
429 }
430 }
431}
432
433- (void)sendPacket:(NSString*)packetType
434 withParameters:(NSDictionary*)parameters
435{
436 NSDictionary* dict = nil;
437
438 if (packetType == nil)
439 return;
440
441 if (parameters != nil) {
442 dict = [parameters dictionaryByAddingObject:packetType forKey:kOOTCPPacketType];
443 } else {
444 dict = [NSDictionary dictionaryWithObjectsAndKeys:packetType, kOOTCPPacketType, nil];
445 }
446
447 [self sendDictionary:dict];
448}
449
450- (void)sendPacket:(NSString*)packetType
451 withValue:(id)value
452 forParameter:(NSString*)paramKey
453{
454 if (packetType == nil)
455 return;
456 if (paramKey == nil)
457 value = nil;
458
459 [self sendDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
460 packetType, kOOTCPPacketType,
461 value, paramKey,
462 nil]];
463}
464
465- (void)readData
466{
467 enum { kBufferSize = 16 << 10 };
468
469 uint8_t buffer[kBufferSize];
470 NSInteger length;
471 NSData* data;
472
473#if OOLITE_MAC_OS_X
474 // Only read while data is available: Apple's socket streams block in -read:maxLength: otherwise.
475 while ([_inStream hasBytesAvailable]) {
476 length = [_inStream read:buffer maxLength:kBufferSize];
477 if (length <= 0)
478 break;
479 data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
480 OOTCPStreamDecoderReceiveData(_decoder, data);
481 }
482#else
483 length = [_inStream read:buffer maxLength:kBufferSize];
484 while (length > 0) {
485 data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
486 OOTCPStreamDecoderReceiveData(_decoder, data);
487 length = [_inStream read:buffer maxLength:kBufferSize];
488 }
489#endif
490}
491
492- (void)dispatchPacket:(NSDictionary*)packet ofType:(NSString*)packetType
493{
494 if (packet == nil || packetType == nil)
495 return;
496
497#define PACKET_CASE(x) \
498 else if ([packetType isEqualToString:kOOTCPPacket_##x]) \
499 { \
500 [self handle##x##Packet:packet]; \
501 }
502
503 if (0) { }
504 PACKET_CASE(ApproveConnection)
505 PACKET_CASE(RejectConnection)
506 PACKET_CASE(CloseConnection)
507 PACKET_CASE(NoteConfigurationChange)
508 PACKET_CASE(PerformCommand)
509 PACKET_CASE(RequestConfigurationValue)
510 PACKET_CASE(Ping)
511 PACKET_CASE(Pong)
512 else
513 {
514 OOLog(@"debugTCP.protocolError.unknownPacketType", @"Unhandled packet type %@.", packetType);
515 }
516}
517
518- (void)handleApproveConnectionPacket:(NSDictionary*)packet
519{
520 NSMutableString* connectedMessage = nil;
521 NSString* consoleIdentity = nil;
522 NSString* hostName = nil;
523
525 _status = kOOTCPClientConnected;
526
527 // Build "Connected..." message with two optional parts, console identity and host name.
528 connectedMessage = [NSMutableString stringWithString:@"Connected to debug console"];
529
530 consoleIdentity = [packet oo_stringForKey:kOOTCPConsoleIdentity];
531 if (consoleIdentity != nil)
532 [connectedMessage appendFormat:@" \"%@\"", consoleIdentity];
533
534#if OOLITE_MAC_OS_X
535 hostName = _host;
536#else
537 hostName = [_host name];
538#endif
539 if ([hostName length] != 0 && ![hostName isEqual:@"localhost"] && ![hostName isEqual:@"127.0.0.1"] && ![hostName isEqual:@"::1"]) {
540 [connectedMessage appendFormat:@" at %@", hostName];
541 }
542
543 OOLog(@"debugTCP.connected", @"%@.", connectedMessage);
544 } else {
545 OOLog(@"debugTCP.protocolError.outOfOrder", @"Got %@ packet from debug console in wrong context.", kOOTCPPacket_ApproveConnection);
546 }
547}
548
549- (void)handleRejectConnectionPacket:(NSDictionary*)packet
550{
551 NSString* message = nil;
552
555 } else {
556 OOLog(@"debugTCP.protocolError.outOfOrder", @"Got %@ packet from debug console in wrong context.", kOOTCPPacket_RejectConnection);
557 }
558
559 message = [packet oo_stringForKey:kOOTCPMessage];
560 if (message == nil)
561 message = @"Console refused connection.";
562 [self breakConnectionWithMessage:message];
563}
564
565- (void)handleCloseConnectionPacket:(NSDictionary*)packet
566{
567 NSString* message = nil;
568
569 if (!StatusIsSendable(_status)) {
570 OOLog(@"debugTCP.protocolError.outOfOrder", @"Got %@ packet from debug console in wrong context.", kOOTCPPacket_CloseConnection);
571 }
572 message = [packet oo_stringForKey:kOOTCPMessage];
573 if (message == nil)
574 message = @"Console closed connection.";
575 [self breakConnectionWithMessage:message];
576}
577
578- (void)handleNoteConfigurationChangePacket:(NSDictionary*)packet
579{
580 NSDictionary* configuration = nil;
581 NSArray* removed = nil;
582 NSEnumerator* keyEnum = nil;
583 NSString* key = nil;
584 id value = nil;
585
586 if (_monitor == nil)
587 return;
588
589 configuration = [packet oo_dictionaryForKey:kOOTCPConfiguration];
590 if (configuration != nil) {
591 foreachkey(key, configuration)
592 {
593 value = [configuration objectForKey:key];
594 [_monitor setConfigurationValue:value forKey:key];
595 }
596 }
597
598 removed = [configuration oo_arrayForKey:kOOTCPRemovedConfigurationKeys];
599 for (keyEnum = [removed objectEnumerator]; (key = [keyEnum nextObject]);) {
600 [_monitor setConfigurationValue:nil forKey:key];
601 }
602}
603
604- (void)handlePerformCommandPacket:(NSDictionary*)packet
605{
606 NSString* message = nil;
607
608 message = [packet oo_stringForKey:kOOTCPMessage];
609 if (message != nil)
610 [_monitor performJSConsoleCommand:message];
611}
612
613- (void)handleRequestConfigurationValuePacket:(NSDictionary*)packet
614{
615 NSString* key = nil;
616 id value = nil;
617
618 key = [packet oo_stringForKey:kOOTCPConfigurationKey];
619 if (key != nil) {
620 value = [_monitor configurationValueForKey:key];
621 [self debugMonitor:_monitor
622 noteChangedConfigrationValue:value
623 forKey:key];
624 }
625}
626
627- (void)handlePingPacket:(NSDictionary*)packet
628{
629 id message = nil;
630
631 message = [packet objectForKey:kOOTCPMessage];
632 [self sendPacket:kOOTCPPacket_Pong
633 withValue:message
634 forParameter:kOOTCPMessage];
635}
636
637- (void)handlePongPacket:(NSDictionary*)packet
638{
639 // Do nothing; we don't currently send pings.
640}
641
642- (void)disconnectFromServerWithMessage:(NSString*)message
643{
644 if (StatusIsSendable(_status)) {
645 [self sendPacket:kOOTCPPacket_CloseConnection
646 withValue:message
647 forParameter:kOOTCPMessage];
648 }
649 [self closeConnection];
650
651 _status = kOOTCPClientDisconnected;
652}
653
654- (void)breakConnectionWithMessage:(NSString*)message
655{
656 [self closeConnection];
657
658 if (_status != kOOTCPClientConnectionRefused)
659 _status = kOOTCPClientDisconnected;
660
661 if ([message length] > 0) {
662 OOLog(@"debugTCP.disconnect", @"No connection to debug console: \"%@\"", message);
663 } else {
664 OOLog(@"debugTCP.disconnect", @"%@", @"Debug console not connected.");
665 }
666
667#if 0
668 // Disconnecting causes crashiness for reasons I don't understand, and isn't very important anyway.
669 [_monitor disconnectDebugger:self message:message];
670 _monitor = nil;
671#endif
672}
673
674- (void)breakConnectionWithBadStream:(NSStream*)stream
675{
676 NSString* errorDesc = nil;
677 NSError* error = nil;
678
679 error = [stream streamError];
680 errorDesc = [error localizedDescription];
681 if (errorDesc == nil)
682 errorDesc = [error description];
683 if (errorDesc == nil)
684 errorDesc = @"bad stream.";
685 [self breakConnectionWithMessage:[NSString stringWithFormat:
686 @"Connection to debug console failed: '%@' (outStream status: %zu, inStream status: %zu).",
687 errorDesc, [_outStream streamStatus], [_inStream streamStatus]]];
688}
689
690@end
691
692static void DecoderPacket(void* cbInfo, OOALStringRef packetType, OOALDictionaryRef packet)
693{
694 [(OODebugTCPConsoleClient*)cbInfo dispatchPacket:packet ofType:packetType];
695}
696
697static void DecoderError(void* cbInfo, OOALStringRef errorDesc)
698{
699 [(OODebugTCPConsoleClient*)cbInfo breakConnectionWithMessage:errorDesc];
700}
701
702#ifdef OO_LOG_DEBUG_PROTOCOL_PACKETS
703void LogOOTCPStreamDecoderPacket(NSDictionary* packet)
704{
705 NSData* data = nil;
706 NSString* xml = nil;
707
708 data = [NSPropertyListSerialization dataFromPropertyList:packet format:NSPropertyListXMLFormat_v1_0 errorDescription:NULL];
709 xml = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
710 OOLog(@"debugTCP.receive", @"Received packet:\n%@", xml);
711}
712
713static void LogSendPacket(NSDictionary* packet)
714{
715 NSData* data = nil;
716 NSString* xml = nil;
717
718 data = [NSPropertyListSerialization dataFromPropertyList:packet format:NSPropertyListXMLFormat_v1_0 errorDescription:NULL];
719 xml = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
720 OOLog(@"debugTCP.send", @"Sent packet:\n%@", xml);
721}
722#endif
723
724#if OOLITE_MAC_OS_X
725/* Returns a connected TCP socket, or -1. The connection attempt is
726 non-blocking so an unreachable host fails after timeoutSeconds.
727*/
728static int OOConnectTCPSocket(NSString* address, uint16_t port, int timeoutSeconds)
729{
730 struct addrinfo hints = { 0 };
731 struct addrinfo* addresses = NULL;
732 hints.ai_family = AF_UNSPEC;
733 hints.ai_socktype = SOCK_STREAM;
734 char portString[8];
735 snprintf(portString, sizeof portString, "%u", port);
736 if (getaddrinfo([address UTF8String], portString, &hints, &addresses) != 0)
737 return -1;
738
739 int result = -1;
740 for (struct addrinfo* candidate = addresses; candidate != NULL && result < 0; candidate = candidate->ai_next) {
741 int fd = socket(candidate->ai_family, candidate->ai_socktype, candidate->ai_protocol);
742 if (fd < 0)
743 continue;
744 int flags = fcntl(fd, F_GETFL, 0);
745 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
746 BOOL connected = connect(fd, candidate->ai_addr, candidate->ai_addrlen) == 0;
747 if (!connected && errno == EINPROGRESS) {
748 fd_set writeSet;
749 FD_ZERO(&writeSet);
750 FD_SET(fd, &writeSet);
751 struct timeval timeout = { timeoutSeconds, 0 };
752 int socketError = 0;
753 socklen_t length = sizeof socketError;
754 connected = select(fd + 1, NULL, &writeSet, NULL, &timeout) == 1 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &socketError, &length) == 0 && socketError == 0;
755 }
756 if (connected) {
757 fcntl(fd, F_SETFL, flags);
758 result = fd;
759 } else {
760 close(fd);
761 }
762 }
763 freeaddrinfo(addresses);
764 return result;
765}
766#endif
767
768#endif /* OO_DEBUG_MONITOR_ENABLED */
OOTCPClientConnectionStatus
@ kOOTCPClientStartedConnectionStage2
@ kOOTCPClientConnected
@ kOOTCPClientStartedConnectionStage1
@ kOOTCPClientConnectionRefused
@ kOOTCPClientDisconnected
#define kOOTCPPacket_ApproveConnection
#define kOOTCPPacket_RejectConnection
#define kOOTCPPacket_CloseConnection
#define foreachkey(VAR, DICT)
#define OOINLINE
#define OOLog(class, format,...)
Definition OOLogging.h:84
unsigned count
return nil
const struct NSString * OOALStringRef
const struct NSDictionary * OOALDictionaryRef
OOTCPStreamDecoderRef OOTCPStreamDecoderCreate(OOTCPStreamDecoderPacketCallback packetCB, OOTCPStreamDecoderErrorCallback errorCB, OOTCPStreamDecoderFinalizeCallback finalizeCB, void *cbInfo)
void OOTCPStreamDecoderDestroy(OOTCPStreamDecoderRef decoder)
void OOTCPStreamDecoderReceiveData(OOTCPStreamDecoderRef decoder, OOALDataRef data)
voidpf stream
Definition ioapi.h:126