30#ifdef OO_DEBUG_MONITOR_ENABLED
49#include <sys/select.h>
50#include <sys/socket.h>
53static int OOConnectTCPSocket(NSString* address, uint16_t port,
int timeoutSeconds);
59#ifdef OO_LOG_DEBUG_PROTOCOL_PACKETS
60static void LogSendPacket(NSDictionary* packet);
62#define LogSendPacket(packet) \
68static void DecoderError(
void* cbInfo,
OOALStringRef errorDesc);
75@interface OODebugTCPConsoleClient (OOPrivate)
77- (void)closeConnection;
79- (BOOL)sendBytes:(const
void*)bytes count:(
size_t)count;
80- (void)sendDictionary:(NSDictionary*)dictionary;
82- (void)sendPacket:(NSString*)packetType
83 withParameters:(NSDictionary*)parameters;
85- (void)sendPacket:(NSString*)packetType
87 forParameter:(NSString*)paramKey;
90- (void)dispatchPacket:(NSDictionary*)packet ofType:(NSString*)packetType;
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;
101- (void)disconnectFromServerWithMessage:(NSString*)message;
102- (void)breakConnectionWithMessage:(NSString*)message;
103- (void)breakConnectionWithBadStream:(NSStream*)stream;
107@implementation OODebugTCPConsoleClient
111 return [
self initWithAddress:nil port:0];
114- (id)initWithAddress:(NSString*)address port:(uint16_t)port
117 NSDictionary* parameters =
nil;
120 address =
@"127.0.0.1";
131 _host = [address copy];
132 int socketFD = OOConnectTCPSocket(_host, port, 3);
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];
142 if (readStream != NULL)
143 CFRelease(readStream);
144 if (writeStream != NULL)
145 CFRelease(writeStream);
150 _host = [NSHost hostWithName:address];
153 [NSStream getStreamsToHost:_host
155 inputStream:&_inStream
156 outputStream:&_outStream];
160 if (_inStream !=
nil && _outStream !=
nil) {
163 [_inStream setDelegate:
self];
164 [_outStream setDelegate:
self];
165 [_inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
166 [_outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
172 NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];
173 NSDate* timeOut = [NSDate dateWithTimeIntervalSinceNow:3];
174 while (_host !=
nil && ([_inStream streamStatus] < 2 || [_outStream streamStatus] < 2) &&
175 [myRunLoop runMode:NSDefaultRunLoopMode
182 if (_decoder != NULL) {
187 parameters = [NSDictionary dictionaryWithObjectsAndKeys:
188 [NSNumber numberWithUnsignedInt:kOOTCPProtocolVersion_1_1_0], kOOTCPProtocolVersion,
189 [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"], kOOTCPOoliteVersion,
191 [
self sendPacket:kOOTCPPacket_RequestConnection
192 withParameters:parameters];
201 OOLog(
@"debugTCP.connect.failed",
@"Failed to connect to debug console at address %@:%i.", address, port);
212 if (StatusIsSendable(_status)) {
213 [
self disconnectFromServerWithMessage:@"TCP console bridge unexpectedly released while active."];
216 [_monitor disconnectDebugger:
self message:@"TCP console bridge unexpectedly released while active."];
219 [
self closeConnection];
227- (BOOL)connectDebugMonitor:(in OODebugMonitor*)debugMonitor
228 errorMessage:(out NSString**)message
232 *message =
@"Connection refused.";
237 *message =
@"Cannot reconnect after disconnecting.";
241 _monitor = debugMonitor;
246- (void)disconnectDebugMonitor:(in OODebugMonitor*)debugMonitor
247 message:(in NSString*)message
249 [
self disconnectFromServerWithMessage:message];
253- (oneway void)debugMonitor:(in OODebugMonitor*)debugMonitor
254 jsConsoleOutput:(in NSString*)output
255 colorKey:(in NSString*)colorKey
256 emphasisRange:(in NSRange)emphasisRange
258 NSMutableDictionary* parameters =
nil;
259 NSArray* range =
nil;
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],
269 [parameters setObject:range forKey:kOOTCPEmphasisRanges];
272 [
self sendPacket:kOOTCPPacket_ConsoleOutput
273 withParameters:parameters];
276- (oneway void)debugMonitorClearConsole:(in OODebugMonitor*)debugMonitor
278 [
self sendPacket:kOOTCPPacket_ClearConsole
282- (oneway void)debugMonitorShowConsole:(in OODebugMonitor*)debugMonitor
284 [
self sendPacket:kOOTCPPacket_ShowConsole
288- (oneway void)debugMonitor:(in OODebugMonitor*)debugMonitor
289 noteConfiguration:(in NSDictionary*)configuration
291 [
self sendPacket:kOOTCPPacket_NoteConfiguration
292 withValue:configuration
293 forParameter:kOOTCPConfiguration];
296- (oneway void)debugMonitor:(in OODebugMonitor*)debugMonitor
297 noteChangedConfigrationValue:(in
id)newValue
298 forKey:(in NSString*)key
300 if (newValue !=
nil) {
301 [
self sendPacket:kOOTCPPacket_NoteConfiguration
302 withValue:[NSDictionary dictionaryWithObject:newValue forKey:key]
303 forParameter:kOOTCPConfiguration];
305 [
self sendPacket:kOOTCPPacket_NoteConfiguration
306 withValue:[NSArray arrayWithObject:key]
307 forParameter:kOOTCPRemovedConfigurationKeys];
311- (void)
stream:(NSStream*)stream handleEvent:(NSStreamEvent)eventCode
316 if (
stream == _inStream && eventCode == NSStreamEventHasBytesAvailable) {
318 }
else if (eventCode == NSStreamEventErrorOccurred) {
319 [
self breakConnectionWithBadStream:stream];
320 }
else if (eventCode == NSStreamEventErrorOccurred) {
321 [
self breakConnectionWithMessage:[NSString stringWithFormat:
322 @"Console closed the connection."]];
328@implementation OODebugTCPConsoleClient (OOPrivate)
330- (void)closeConnection
333 [_inStream setDelegate:nil];
338 [_outStream setDelegate:nil];
339 [_outStream release];
346- (BOOL)sendBytes:(const
void*)bytes count:(
size_t)count
348 if (bytes == NULL ||
count == 0)
350 if (!StatusIsSendable(_status) || _outStream ==
nil)
354 NSInteger written = [_outStream write:bytes maxLength:count];
365- (void)sendDictionary:(NSDictionary*)dictionary
368 NSString* errorDesc = NULL;
370 const uint8_t* bytes = NULL;
374 if (dictionary ==
nil || !StatusIsSendable(_status))
377 data = [NSPropertyListSerialization dataFromPropertyList:dictionary
378 format:NSPropertyListXMLFormat_v1_0
379 errorDescription:&errorDesc];
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];
389 LogSendPacket(dictionary);
391 count = [data length];
394 header = htonl(
count);
396 bytes = [data bytes];
402 if (![
self sendBytes:&header
count:
sizeof header]) {
403 OOLog(
@"debugTCP.send.warning",
@"%@",
@"Error sending packet header, retrying.");
405 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.008]];
406 if (![
self sendBytes:&header
count:
sizeof header]) {
409 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.016]];
410 if (![
self sendBytes:&header
count:
sizeof header]) {
416 if (sentOK && ![
self sendBytes:bytes
count:
count]) {
417 OOLog(
@"debugTCP.send.warning",
@"%@",
@"Error sending packet body, retrying.");
419 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.008]];
426 OOLog(
@"debugTCP.send.error",
@"The following packet could not be sent: %@", dictionary);
427 if (![[OODebugMonitor sharedDebugMonitor] TCPIgnoresDroppedPackets]) {
428 [
self breakConnectionWithBadStream:_outStream];
433- (void)sendPacket:(NSString*)packetType
434 withParameters:(NSDictionary*)parameters
436 NSDictionary* dict =
nil;
438 if (packetType ==
nil)
441 if (parameters !=
nil) {
442 dict = [parameters dictionaryByAddingObject:packetType forKey:kOOTCPPacketType];
444 dict = [NSDictionary dictionaryWithObjectsAndKeys:packetType, kOOTCPPacketType, nil];
447 [
self sendDictionary:dict];
450- (void)sendPacket:(NSString*)packetType
452 forParameter:(NSString*)paramKey
454 if (packetType ==
nil)
459 [
self sendDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
460 packetType, kOOTCPPacketType,
467 enum { kBufferSize = 16 << 10 };
469 uint8_t buffer[kBufferSize];
475 while ([_inStream hasBytesAvailable]) {
476 length = [_inStream read:buffer maxLength:kBufferSize];
479 data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
483 length = [_inStream read:buffer maxLength:kBufferSize];
485 data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
487 length = [_inStream read:buffer maxLength:kBufferSize];
492- (void)dispatchPacket:(NSDictionary*)packet ofType:(NSString*)packetType
494 if (packet ==
nil || packetType ==
nil)
497#define PACKET_CASE(x) \
498 else if ([packetType isEqualToString:kOOTCPPacket_##x]) \
500 [self handle##x##Packet:packet]; \
504 PACKET_CASE(ApproveConnection)
505 PACKET_CASE(RejectConnection)
506 PACKET_CASE(CloseConnection)
507 PACKET_CASE(NoteConfigurationChange)
508 PACKET_CASE(PerformCommand)
509 PACKET_CASE(RequestConfigurationValue)
514 OOLog(
@"debugTCP.protocolError.unknownPacketType",
@"Unhandled packet type %@.", packetType);
518- (void)handleApproveConnectionPacket:(NSDictionary*)packet
520 NSMutableString* connectedMessage =
nil;
521 NSString* consoleIdentity =
nil;
522 NSString* hostName =
nil;
528 connectedMessage = [NSMutableString stringWithString:@"Connected to debug console"];
530 consoleIdentity = [packet oo_stringForKey:kOOTCPConsoleIdentity];
531 if (consoleIdentity !=
nil)
532 [connectedMessage appendFormat:@" \"%@\"", consoleIdentity];
537 hostName = [_host name];
539 if ([hostName length] != 0 && ![hostName isEqual:
@"localhost"] && ![hostName isEqual:
@"127.0.0.1"] && ![hostName isEqual:
@"::1"]) {
540 [connectedMessage appendFormat:@" at %@", hostName];
543 OOLog(
@"debugTCP.connected",
@"%@.", connectedMessage);
549- (void)handleRejectConnectionPacket:(NSDictionary*)packet
551 NSString* message =
nil;
559 message = [packet oo_stringForKey:kOOTCPMessage];
561 message =
@"Console refused connection.";
562 [
self breakConnectionWithMessage:message];
565- (void)handleCloseConnectionPacket:(NSDictionary*)packet
567 NSString* message =
nil;
569 if (!StatusIsSendable(_status)) {
572 message = [packet oo_stringForKey:kOOTCPMessage];
574 message =
@"Console closed connection.";
575 [
self breakConnectionWithMessage:message];
578- (void)handleNoteConfigurationChangePacket:(NSDictionary*)packet
580 NSDictionary* configuration =
nil;
581 NSArray* removed =
nil;
582 NSEnumerator* keyEnum =
nil;
589 configuration = [packet oo_dictionaryForKey:kOOTCPConfiguration];
590 if (configuration !=
nil) {
593 value = [configuration objectForKey:key];
594 [_monitor setConfigurationValue:value forKey:key];
598 removed = [configuration oo_arrayForKey:kOOTCPRemovedConfigurationKeys];
599 for (keyEnum = [removed objectEnumerator]; (key = [keyEnum nextObject]);) {
600 [_monitor setConfigurationValue:nil forKey:key];
604- (void)handlePerformCommandPacket:(NSDictionary*)packet
606 NSString* message =
nil;
608 message = [packet oo_stringForKey:kOOTCPMessage];
610 [_monitor performJSConsoleCommand:message];
613- (void)handleRequestConfigurationValuePacket:(NSDictionary*)packet
618 key = [packet oo_stringForKey:kOOTCPConfigurationKey];
620 value = [_monitor configurationValueForKey:key];
621 [
self debugMonitor:_monitor
622 noteChangedConfigrationValue:value
627- (void)handlePingPacket:(NSDictionary*)packet
631 message = [packet objectForKey:kOOTCPMessage];
632 [
self sendPacket:kOOTCPPacket_Pong
634 forParameter:kOOTCPMessage];
637- (void)handlePongPacket:(NSDictionary*)packet
642- (void)disconnectFromServerWithMessage:(NSString*)message
644 if (StatusIsSendable(_status)) {
645 [
self sendPacket:kOOTCPPacket_CloseConnection
647 forParameter:kOOTCPMessage];
649 [
self closeConnection];
654- (void)breakConnectionWithMessage:(NSString*)message
656 [
self closeConnection];
661 if ([message length] > 0) {
662 OOLog(
@"debugTCP.disconnect",
@"No connection to debug console: \"%@\
"", message);
664 OOLog(
@"debugTCP.disconnect",
@"%@",
@"Debug console not connected.");
669 [_monitor disconnectDebugger:
self message:message];
674- (void)breakConnectionWithBadStream:(NSStream*)stream
676 NSString* errorDesc =
nil;
677 NSError* error =
nil;
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]]];
697static void DecoderError(
void* cbInfo,
OOALStringRef errorDesc)
702#ifdef OO_LOG_DEBUG_PROTOCOL_PACKETS
703void LogOOTCPStreamDecoderPacket(NSDictionary* packet)
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);
713static void LogSendPacket(NSDictionary* packet)
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);
728static int OOConnectTCPSocket(NSString* address, uint16_t port,
int timeoutSeconds)
730 struct addrinfo hints = { 0 };
731 struct addrinfo* addresses = NULL;
732 hints.ai_family = AF_UNSPEC;
733 hints.ai_socktype = SOCK_STREAM;
735 snprintf(portString,
sizeof portString,
"%u", port);
736 if (getaddrinfo([address UTF8String], portString, &hints, &addresses) != 0)
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);
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) {
750 FD_SET(fd, &writeSet);
751 struct timeval timeout = { timeoutSeconds, 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;
757 fcntl(fd, F_SETFL, flags);
763 freeaddrinfo(addresses);
OOTCPClientConnectionStatus
@ kOOTCPClientStartedConnectionStage2
@ kOOTCPClientStartedConnectionStage1
@ kOOTCPClientConnectionRefused
@ kOOTCPClientDisconnected
#define kOOTCPPacket_ApproveConnection
#define kOOTCPPacket_RejectConnection
#define kOOTCPPacket_CloseConnection
#define foreachkey(VAR, DICT)
#define OOLog(class, format,...)
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)