3 * Copyright (c) 2007 - 2011, Blue Static <http://www.bluestatic.org>
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17 #import "NetworkConnection.h"
18 #import "NetworkConnectionPrivate.h"
20 #import <sys/socket.h>
21 #import <netinet/in.h>
23 #import "AppDelegate.h"
24 #import "LoggingController.h"
25 #include "NetworkCallbackController.h"
27 // Other Run Loop Callbacks ////////////////////////////////////////////////////
29 void PerformQuitSignal(void* info)
31 NetworkConnection* obj = (NetworkConnection*)info;
32 [obj performQuitSignal];
35 ////////////////////////////////////////////////////////////////////////////////
37 @implementation NetworkConnection
39 @synthesize port = port_;
40 @synthesize connected = connected_;
41 @synthesize delegate = delegate_;
43 @synthesize socket = socket_;
44 @synthesize readStream = readStream_;
45 @synthesize lastReadTransaction = lastReadTransaction_;
46 @synthesize currentPacket = currentPacket_;
47 @synthesize writeStream = writeStream_;
48 @synthesize lastWrittenTransaction = lastWrittenTransaction_;
49 @synthesize queuedWrites = queuedWrites_;
51 - (id)initWithPort:(NSUInteger)aPort
53 if (self = [super init])
62 self.currentPacket = nil;
67 * Kicks off the socket on another thread.
71 if (thread_ && !connected_) {
72 // A thread has been detached but the socket has yet to connect. Do not
73 // spawn a new thread otherwise multiple threads will be blocked on the same
77 [NSThread detachNewThreadSelector:@selector(runNetworkThread) toTarget:self withObject:nil];
81 * Creates, connects to, and schedules a CFSocket.
83 - (void)runNetworkThread
85 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
87 thread_ = [NSThread currentThread];
88 runLoop_ = [NSRunLoop currentRunLoop];
89 callbackController_ = new NetworkCallbackController(self);
91 // Pass ourselves to the callback so we don't have to use ugly globals.
92 CFSocketContext context = { 0 };
93 context.info = callbackController_;
95 // Create the address structure.
96 struct sockaddr_in address;
97 memset(&address, 0, sizeof(address));
98 address.sin_len = sizeof(address);
99 address.sin_family = AF_INET;
100 address.sin_port = htons(port_);
101 address.sin_addr.s_addr = htonl(INADDR_ANY);
103 // Create the socket signature.
104 CFSocketSignature signature;
105 signature.protocolFamily = PF_INET;
106 signature.socketType = SOCK_STREAM;
107 signature.protocol = IPPROTO_TCP;
108 signature.address = (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)];
111 socket_ = CFSocketCreateWithSocketSignature(kCFAllocatorDefault,
112 &signature, // Socket signature.
113 kCFSocketAcceptCallBack, // Callback types.
114 &NetworkCallbackController::SocketAcceptCallback, // Callout function pointer.
115 &context); // Context to pass to callout.
117 [self errorEncountered:@"Could not open socket."];
122 // Allow old, yet-to-be recycled sockets to be reused.
124 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
125 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(BOOL));
127 // Schedule the socket on the run loop.
128 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 0);
129 CFRunLoopAddSource([runLoop_ getCFRunLoop], source, kCFRunLoopCommonModes);
132 // Create a source that is used to quit.
133 CFRunLoopSourceContext quitContext = { 0 };
134 quitContext.info = self;
135 quitContext.perform = PerformQuitSignal;
136 quitSource_ = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &quitContext);
137 CFRunLoopAddSource([runLoop_ getCFRunLoop], quitSource_, kCFRunLoopCommonModes);
143 delete callbackController_;
144 callbackController_ = NULL;
146 CFRunLoopSourceInvalidate(quitSource_);
147 CFRelease(quitSource_);
154 * Called by SocketWrapper after the connection is successful. This immediately calls
155 * -[SocketWrapper receive] to clear the way for communication, though the information
156 * could be useful server information that we don't use right now.
158 - (void)socketDidAccept
162 lastReadTransaction_ = 0;
163 lastWrittenTransaction_ = 0;
164 self.queuedWrites = [NSMutableArray array];
165 writeQueueLock_ = [NSRecursiveLock new];
166 if ([delegate_ respondsToSelector:@selector(connectionDidAccept:)])
167 [delegate_ performSelectorOnMainThread:@selector(connectionDidAccept:)
173 * Closes a socket and releases the ref.
180 if (runLoop_ && quitSource_) {
181 CFRunLoopSourceSignal(quitSource_);
182 CFRunLoopWakeUp([runLoop_ getCFRunLoop]);
187 * Quits the run loop and stops the thread.
189 - (void)performQuitSignal
191 self.queuedWrites = nil;
193 [writeQueueLock_ release];
196 CFRunLoopStop([runLoop_ getCFRunLoop]);
199 // The socket goes down, so do the streams, which clean themselves up.
201 NSLog(@"invalidating socket");
202 CFSocketInvalidate(socket_);
209 * Notification that the socket disconnected.
211 - (void)socketDisconnected
213 if ([delegate_ respondsToSelector:@selector(connectionDidClose:)])
214 [delegate_ connectionDidClose:self];
218 * Writes a command into the write stream. If the stream is ready for writing,
219 * we do so immediately. If not, the command is queued and will be written
220 * when the stream is ready.
222 - (void)send:(NSString*)command
224 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_)) {
225 [self performSend:command];
227 [writeQueueLock_ lock];
228 [queuedWrites_ addObject:command];
229 [writeQueueLock_ unlock];
231 [self sendQueuedWrites];
235 * This will send a command to the debugger engine. It will append the
236 * transaction ID automatically. It accepts a NSString command along with a
237 * a variable number of arguments to substitute into the command, a la
238 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
240 - (NSNumber*)sendCommandWithFormat:(NSString*)format, ...
242 // Collect varargs and format command.
244 va_start(args, format);
245 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
248 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
249 NSString* taggedCommand = [NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey];
250 [self performSelector:@selector(send:)
252 withObject:taggedCommand
253 waitUntilDone:connected_];
259 * Given a file path, this returns a file:// URI and escapes any spaces for the
262 - (NSString*)escapedURIPath:(NSString*)path
264 // Custon GDBp paths are fine.
265 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
268 // Create a temporary URL that will escape all the nasty characters.
269 NSURL* url = [NSURL fileURLWithPath:path];
270 NSString* urlString = [url absoluteString];
272 // Remove the host because this is a file:// URL;
273 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
275 // Escape % for use in printf-style NSString formatters.
276 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
281 * Returns the transaction_id from an NSXMLDocument.
283 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
285 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
289 * Scans a command string for the transaction ID component. If it is not found,
290 * returns NSNotFound.
292 - (NSInteger)transactionIDFromCommand:(NSString*)command
294 NSRange occurrence = [command rangeOfString:@"-i "];
295 if (occurrence.location == NSNotFound)
297 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
298 return [transaction intValue];
301 // Private /////////////////////////////////////////////////////////////////////
304 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
307 * Receives errors from the SocketWrapper and updates the display
309 - (void)errorEncountered:(NSString*)error
311 if (![delegate_ respondsToSelector:@selector(errorEncountered:)])
313 [delegate_ performSelectorOnMainThread:@selector(errorEncountered:)
318 - (LogEntry*)recordSend:(NSString*)command
320 LoggingController* logger = [[AppDelegate instance] loggingController];
321 LogEntry* entry = [LogEntry newSendEntry:command];
322 entry.lastReadTransactionID = lastReadTransaction_;
323 entry.lastWrittenTransactionID = lastWrittenTransaction_;
324 [logger performSelectorOnMainThread:@selector(recordEntry:)
327 return [entry autorelease];
330 - (LogEntry*)recordReceive:(NSString*)command
332 LoggingController* logger = [[AppDelegate instance] loggingController];
333 LogEntry* entry = [LogEntry newReceiveEntry:command];
334 entry.lastReadTransactionID = lastReadTransaction_;
335 entry.lastWrittenTransactionID = lastWrittenTransaction_;
336 [logger performSelectorOnMainThread:@selector(recordEntry:)
339 return [entry autorelease];
342 // Stream Managers /////////////////////////////////////////////////////////////
345 * Callback from the CFReadStream that there is data waiting to be read.
347 - (void)readStreamHasData
349 const NSUInteger kBufferSize = 1024;
350 UInt8 buffer[kBufferSize];
351 CFIndex bufferOffset = 0; // Starting point in |buffer| to work with.
352 CFIndex bytesRead = CFReadStreamRead(readStream_, buffer, kBufferSize);
353 const char* charBuffer = (const char*)buffer;
355 // The read loop works by going through the buffer until all the bytes have
357 while (bufferOffset < bytesRead)
359 // Find the NULL separator, or the end of the string.
360 NSUInteger partLength = 0;
361 for (NSUInteger i = bufferOffset; i < bytesRead && charBuffer[i] != '\0'; ++i, ++partLength) ;
363 // If there is not a current packet, set some state.
364 if (!self.currentPacket)
366 // Read the message header: the size. This will be |partLength| bytes.
367 packetSize_ = atoi(charBuffer + bufferOffset);
368 currentPacketIndex_ = 0;
369 self.currentPacket = [NSMutableString stringWithCapacity:packetSize_];
370 bufferOffset += partLength + 1; // Pass over the NULL byte.
371 continue; // Spin the loop to begin reading actual data.
374 // Substring the byte stream and append it to the packet string.
375 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
376 buffer + bufferOffset, // Byte pointer, offset by start index.
377 partLength, // Length.
378 kCFStringEncodingUTF8,
380 [self.currentPacket appendString:(NSString*)bufferString];
381 CFRelease(bufferString);
384 currentPacketIndex_ += partLength;
385 bufferOffset += partLength + 1;
387 // If this read finished the packet, handle it and reset.
388 if (currentPacketIndex_ >= packetSize_)
390 [self handlePacket:[[currentPacket_ retain] autorelease]];
391 self.currentPacket = nil;
393 currentPacketIndex_ = 0;
399 * Performs the packet handling of a raw string XML packet. From this point on,
400 * the packets are associated with a transaction and are then dispatched.
402 - (void)handlePacket:(NSString*)packet
404 // Test if we can convert it into an NSXMLDocument.
405 NSError* error = nil;
406 NSXMLDocument* xmlTest = [[NSXMLDocument alloc] initWithXMLString:currentPacket_ options:NSXMLDocumentTidyXML error:&error];
408 // Try to recover if we encountered an error.
411 // We do not want to starve the write queue, so manually parse out the
413 NSRange location = [currentPacket_ rangeOfString:@"transaction_id"];
414 if (location.location != NSNotFound)
416 NSUInteger start = location.location + location.length;
417 NSUInteger end = start;
419 NSCharacterSet* numericSet = [NSCharacterSet decimalDigitCharacterSet];
421 // Loop over the characters after the attribute name to extract the ID.
422 while (end < [currentPacket_ length])
424 unichar c = [currentPacket_ characterAtIndex:end];
425 if ([numericSet characterIsMember:c])
427 // If this character is numeric, extend the range to substring.
434 // If this character is nonnumeric and we have nothing in the
435 // range, skip this character.
441 // We've moved past the numeric ID so we should stop searching.
447 // If we were able to extract the transaction ID, update the last read.
448 NSRange substringRange = NSMakeRange(start, end - start);
449 NSString* transactionStr = [currentPacket_ substringWithRange:substringRange];
450 if ([transactionStr length])
451 lastReadTransaction_ = [transactionStr intValue];
454 // Otherwise, assume +1 and hope it works.
455 ++lastReadTransaction_;
456 } else /*if (!reconnect_)*/ {
457 // See if the transaction can be parsed out.
458 NSInteger transaction = [self transactionIDFromResponse:xmlTest];
459 if (transaction < lastReadTransaction_) {
460 NSLog(@"tx = %d vs %d", transaction, lastReadTransaction_);
461 NSLog(@"out of date transaction %@", packet);
465 if (transaction != lastWrittenTransaction_)
466 NSLog(@"txn %d <> %d last written, %d last read", transaction, lastWrittenTransaction_, lastReadTransaction_);
468 lastReadTransaction_ = transaction;
471 // Log this receive event.
472 LogEntry* log = [self recordReceive:currentPacket_];
475 // Finally, dispatch the handler for this response.
476 [self handleResponse:[xmlTest autorelease]];
479 - (void)handleResponse:(NSXMLDocument*)response
481 // Check and see if there's an error.
482 NSArray* error = [[response rootElement] elementsForName:@"error"];
483 if ([error count] > 0)
485 NSLog(@"Xdebug error: %@", error);
486 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
487 [self errorEncountered:errorMessage];
490 if ([[[response rootElement] name] isEqualToString:@"init"]) {
492 [delegate_ performSelectorOnMainThread:@selector(handleInitialResponse:)
498 if ([delegate_ respondsToSelector:@selector(handleResponse:)])
499 [delegate_ performSelectorOnMainThread:@selector(handleResponse:)
503 [self sendQueuedWrites];
507 * This performs a blocking send. This should ONLY be called when we know we
508 * have write access to the stream. We will busy wait in case we don't do a full
511 - (void)performSend:(NSString*)command
513 // If this is an out-of-date transaction, do not bother sending it.
514 NSInteger transaction = [self transactionIDFromCommand:command];
515 if (transaction != NSNotFound && transaction < lastWrittenTransaction_)
520 char* string = (char*)[command UTF8String];
521 int stringLength = strlen(string);
523 // Busy wait while writing. BAADD. Should background this operation.
526 if (CFWriteStreamCanAcceptBytes(writeStream_))
528 // Include the NULL byte in the string when we write.
529 int bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
530 if (bytesWritten < 0)
532 NSLog(@"write error");
535 else if (bytesWritten < strlen(string))
537 // Adjust the buffer and wait for another chance to write.
538 stringLength -= bytesWritten;
539 memmove(string, string + bytesWritten, stringLength);
545 // We need to scan the string to find the transactionID.
546 if (transaction == NSNotFound)
548 NSLog(@"sent %@ without a transaction ID", command);
551 lastWrittenTransaction_ = transaction;
556 // Log this trancation.
557 [self recordSend:command];
561 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
562 * them if it's OK to do so. This will not block.
564 - (void)sendQueuedWrites
569 [writeQueueLock_ lock];
570 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0)
572 NSString* command = [queuedWrites_ objectAtIndex:0];
574 // We don't want to block because this is called from the main thread.
575 // |-performSend:| busy waits when the stream is not ready. Bail out
576 // before we do that becuase busy waiting is BAD.
577 if (CFWriteStreamCanAcceptBytes(writeStream_))
579 [self performSend:command];
580 [queuedWrites_ removeObjectAtIndex:0];
583 [writeQueueLock_ unlock];