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 "AppDelegate.h"
21 #import "LoggingController.h"
22 #include "NetworkCallbackController.h"
24 // Other Run Loop Callbacks ////////////////////////////////////////////////////
26 void PerformQuitSignal(void* info)
28 NetworkConnection* obj = (NetworkConnection*)info;
29 [obj performQuitSignal];
32 ////////////////////////////////////////////////////////////////////////////////
34 @implementation NetworkConnection
36 @synthesize port = port_;
37 @synthesize connected = connected_;
38 @synthesize delegate = delegate_;
40 @synthesize readStream = readStream_;
41 @synthesize lastReadTransaction = lastReadTransaction_;
42 @synthesize currentPacket = currentPacket_;
43 @synthesize writeStream = writeStream_;
44 @synthesize lastWrittenTransaction = lastWrittenTransaction_;
45 @synthesize queuedWrites = queuedWrites_;
47 - (id)initWithPort:(NSUInteger)aPort
49 if (self = [super init]) {
57 self.currentPacket = nil;
62 * Kicks off the socket on another thread.
66 if (thread_ && !connected_) {
67 // A thread has been detached but the socket has yet to connect. Do not
68 // spawn a new thread otherwise multiple threads will be blocked on the same
72 [NSThread detachNewThreadSelector:@selector(runNetworkThread) toTarget:self withObject:nil];
76 * Creates, connects to, and schedules a CFSocket.
78 - (void)runNetworkThread
80 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
82 thread_ = [NSThread currentThread];
83 runLoop_ = [NSRunLoop currentRunLoop];
84 callbackController_ = new NetworkCallbackController(self);
86 // Create a source that is used to quit.
87 CFRunLoopSourceContext quitContext = { 0 };
88 quitContext.info = self;
89 quitContext.perform = PerformQuitSignal;
90 quitSource_ = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &quitContext);
91 CFRunLoopAddSource([runLoop_ getCFRunLoop], quitSource_, kCFRunLoopCommonModes);
93 callbackController_->OpenConnection(port_);
99 delete callbackController_;
100 callbackController_ = NULL;
102 CFRunLoopSourceInvalidate(quitSource_);
103 CFRelease(quitSource_);
110 * Called by SocketWrapper after the connection is successful. This immediately calls
111 * -[SocketWrapper receive] to clear the way for communication, though the information
112 * could be useful server information that we don't use right now.
114 - (void)socketDidAccept
118 lastReadTransaction_ = 0;
119 lastWrittenTransaction_ = 0;
120 self.queuedWrites = [NSMutableArray array];
121 writeQueueLock_ = [NSRecursiveLock new];
122 if ([delegate_ respondsToSelector:@selector(connectionDidAccept:)])
123 [delegate_ performSelectorOnMainThread:@selector(connectionDidAccept:)
129 * Closes a socket and releases the ref.
136 if (runLoop_ && quitSource_) {
137 CFRunLoopSourceSignal(quitSource_);
138 CFRunLoopWakeUp([runLoop_ getCFRunLoop]);
143 * Quits the run loop and stops the thread.
145 - (void)performQuitSignal
147 self.queuedWrites = nil;
149 [writeQueueLock_ release];
152 CFRunLoopStop([runLoop_ getCFRunLoop]);
155 callbackController_->CloseConnection();
159 * Notification that the socket disconnected.
161 - (void)socketDisconnected
163 if ([delegate_ respondsToSelector:@selector(connectionDidClose:)])
164 [delegate_ connectionDidClose:self];
168 * Writes a command into the write stream. If the stream is ready for writing,
169 * we do so immediately. If not, the command is queued and will be written
170 * when the stream is ready.
172 - (void)send:(NSString*)command
174 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_)) {
175 [self performSend:command];
177 [writeQueueLock_ lock];
178 [queuedWrites_ addObject:command];
179 [writeQueueLock_ unlock];
181 [self sendQueuedWrites];
185 * This will send a command to the debugger engine. It will append the
186 * transaction ID automatically. It accepts a NSString command along with a
187 * a variable number of arguments to substitute into the command, a la
188 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
190 - (NSNumber*)sendCommandWithFormat:(NSString*)format, ...
192 // Collect varargs and format command.
194 va_start(args, format);
195 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
198 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
199 NSString* taggedCommand = [NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey];
200 [self performSelector:@selector(send:)
202 withObject:taggedCommand
203 waitUntilDone:connected_];
209 * Given a file path, this returns a file:// URI and escapes any spaces for the
212 - (NSString*)escapedURIPath:(NSString*)path
214 // Custon GDBp paths are fine.
215 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
218 // Create a temporary URL that will escape all the nasty characters.
219 NSURL* url = [NSURL fileURLWithPath:path];
220 NSString* urlString = [url absoluteString];
222 // Remove the host because this is a file:// URL;
223 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
225 // Escape % for use in printf-style NSString formatters.
226 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
231 * Returns the transaction_id from an NSXMLDocument.
233 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
235 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
239 * Scans a command string for the transaction ID component. If it is not found,
240 * returns NSNotFound.
242 - (NSInteger)transactionIDFromCommand:(NSString*)command
244 NSRange occurrence = [command rangeOfString:@"-i "];
245 if (occurrence.location == NSNotFound)
247 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
248 return [transaction intValue];
251 // Private /////////////////////////////////////////////////////////////////////
254 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
257 * Receives errors from the SocketWrapper and updates the display
259 - (void)errorEncountered:(NSString*)error
261 if (![delegate_ respondsToSelector:@selector(errorEncountered:)])
263 [delegate_ performSelectorOnMainThread:@selector(errorEncountered:)
268 - (LogEntry*)recordSend:(NSString*)command
270 LoggingController* logger = [[AppDelegate instance] loggingController];
271 LogEntry* entry = [LogEntry newSendEntry:command];
272 entry.lastReadTransactionID = lastReadTransaction_;
273 entry.lastWrittenTransactionID = lastWrittenTransaction_;
274 [logger performSelectorOnMainThread:@selector(recordEntry:)
277 return [entry autorelease];
280 - (LogEntry*)recordReceive:(NSString*)command
282 LoggingController* logger = [[AppDelegate instance] loggingController];
283 LogEntry* entry = [LogEntry newReceiveEntry:command];
284 entry.lastReadTransactionID = lastReadTransaction_;
285 entry.lastWrittenTransactionID = lastWrittenTransaction_;
286 [logger performSelectorOnMainThread:@selector(recordEntry:)
289 return [entry autorelease];
292 // Stream Managers /////////////////////////////////////////////////////////////
295 * Callback from the CFReadStream that there is data waiting to be read.
297 - (void)readStreamHasData
299 const NSUInteger kBufferSize = 1024;
300 UInt8 buffer[kBufferSize];
301 CFIndex bufferOffset = 0; // Starting point in |buffer| to work with.
302 CFIndex bytesRead = CFReadStreamRead(readStream_, buffer, kBufferSize);
303 const char* charBuffer = (const char*)buffer;
305 // The read loop works by going through the buffer until all the bytes have
307 while (bufferOffset < bytesRead) {
308 // Find the NULL separator, or the end of the string.
309 NSUInteger partLength = 0;
310 for (CFIndex i = bufferOffset; i < bytesRead && charBuffer[i] != '\0'; ++i, ++partLength) ;
312 // If there is not a current packet, set some state.
313 if (!self.currentPacket) {
314 // Read the message header: the size. This will be |partLength| bytes.
315 packetSize_ = atoi(charBuffer + bufferOffset);
316 currentPacketIndex_ = 0;
317 self.currentPacket = [NSMutableString stringWithCapacity:packetSize_];
318 bufferOffset += partLength + 1; // Pass over the NULL byte.
319 continue; // Spin the loop to begin reading actual data.
322 // Substring the byte stream and append it to the packet string.
323 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
324 buffer + bufferOffset, // Byte pointer, offset by start index.
325 partLength, // Length.
326 kCFStringEncodingUTF8,
328 [self.currentPacket appendString:(NSString*)bufferString];
329 CFRelease(bufferString);
332 currentPacketIndex_ += partLength;
333 bufferOffset += partLength + 1;
335 // If this read finished the packet, handle it and reset.
336 if (currentPacketIndex_ >= packetSize_) {
337 [self handlePacket:[[currentPacket_ retain] autorelease]];
338 self.currentPacket = nil;
340 currentPacketIndex_ = 0;
346 * Performs the packet handling of a raw string XML packet. From this point on,
347 * the packets are associated with a transaction and are then dispatched.
349 - (void)handlePacket:(NSString*)packet
351 // Test if we can convert it into an NSXMLDocument.
352 NSError* error = nil;
353 NSXMLDocument* xml = [[NSXMLDocument alloc] initWithXMLString:currentPacket_
354 options:NSXMLDocumentTidyXML
356 // TODO: Remove this assert before stable release. Flush out any possible
357 // issues during testing.
360 // Validate the transaction.
361 NSInteger transaction = [self transactionIDFromResponse:xml];
362 if (transaction < lastReadTransaction_) {
363 NSLog(@"Transaction #%d is out of date (lastRead = %d). Dropping packet: %@",
364 transaction, lastReadTransaction_, packet);
367 if (transaction != lastWrittenTransaction_) {
368 NSLog(@"Transaction #%d received out of order. lastRead = %d, lastWritten = %d. Continuing.",
369 transaction, lastReadTransaction_, lastWrittenTransaction_);
372 lastReadTransaction_ = transaction;
374 // Log this receive event.
375 LogEntry* log = [self recordReceive:currentPacket_];
378 // Finally, dispatch the handler for this response.
379 [self handleResponse:[xml autorelease]];
382 - (void)handleResponse:(NSXMLDocument*)response
384 // Check and see if there's an error.
385 NSArray* error = [[response rootElement] elementsForName:@"error"];
386 if ([error count] > 0) {
387 NSLog(@"Xdebug error: %@", error);
388 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
389 [self errorEncountered:errorMessage];
392 if ([[[response rootElement] name] isEqualToString:@"init"]) {
394 [delegate_ performSelectorOnMainThread:@selector(handleInitialResponse:)
400 if ([delegate_ respondsToSelector:@selector(handleResponse:)])
401 [delegate_ performSelectorOnMainThread:@selector(handleResponse:)
405 [self sendQueuedWrites];
409 * This performs a blocking send. This should ONLY be called when we know we
410 * have write access to the stream. We will busy wait in case we don't do a full
413 - (void)performSend:(NSString*)command
415 // If this is an out-of-date transaction, do not bother sending it.
416 NSInteger transaction = [self transactionIDFromCommand:command];
417 if (transaction != NSNotFound && transaction < lastWrittenTransaction_)
422 char* string = (char*)[command UTF8String];
423 size_t stringLength = strlen(string);
425 // Busy wait while writing. BAADD. Should background this operation.
427 if (CFWriteStreamCanAcceptBytes(writeStream_)){
428 // Include the NULL byte in the string when we write.
429 CFIndex bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
430 if (bytesWritten < 0) {
431 CFErrorRef error = CFWriteStreamCopyError(writeStream_);
432 NSLog(@"Write stream error: %@", error);
436 else if (bytesWritten < static_cast<CFIndex>(strlen(string))) {
437 // Adjust the buffer and wait for another chance to write.
438 stringLength -= bytesWritten;
439 memmove(string, string + bytesWritten, stringLength);
443 // We need to scan the string to find the transactionID.
444 if (transaction == NSNotFound) {
445 NSLog(@"sent %@ without a transaction ID", command);
448 lastWrittenTransaction_ = transaction;
453 // Log this trancation.
454 [self recordSend:command];
458 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
459 * them if it's OK to do so. This will not block.
461 - (void)sendQueuedWrites
466 [writeQueueLock_ lock];
467 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0) {
468 NSString* command = [queuedWrites_ objectAtIndex:0];
470 // We don't want to block because this is called from the main thread.
471 // |-performSend:| busy waits when the stream is not ready. Bail out
472 // before we do that becuase busy waiting is BAD.
473 if (CFWriteStreamCanAcceptBytes(writeStream_)) {
474 [self performSend:command];
475 [queuedWrites_ removeObjectAtIndex:0];
478 [writeQueueLock_ unlock];