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
214 // The state still is connected, which means that we did not get here
215 // through normal disconnected procedure (a call to |-close|, followed by
216 // the downing of the socket and the stream, which also produces this
217 // messsage). Instead, the stream callbacks encountered EOF unexpectedly.
220 if ([delegate_ respondsToSelector:@selector(connectionDidClose:)])
221 [delegate_ connectionDidClose:self];
225 * Writes a command into the write stream. If the stream is ready for writing,
226 * we do so immediately. If not, the command is queued and will be written
227 * when the stream is ready.
229 - (void)send:(NSString*)command
231 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_)) {
232 [self performSend:command];
234 [writeQueueLock_ lock];
235 [queuedWrites_ addObject:command];
236 [writeQueueLock_ unlock];
238 [self sendQueuedWrites];
242 * This will send a command to the debugger engine. It will append the
243 * transaction ID automatically. It accepts a NSString command along with a
244 * a variable number of arguments to substitute into the command, a la
245 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
247 - (NSNumber*)sendCommandWithFormat:(NSString*)format, ...
249 // Collect varargs and format command.
251 va_start(args, format);
252 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
255 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
256 NSString* taggedCommand = [NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey];
257 [self performSelector:@selector(send:)
259 withObject:taggedCommand
260 waitUntilDone:connected_];
266 * Given a file path, this returns a file:// URI and escapes any spaces for the
269 - (NSString*)escapedURIPath:(NSString*)path
271 // Custon GDBp paths are fine.
272 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
275 // Create a temporary URL that will escape all the nasty characters.
276 NSURL* url = [NSURL fileURLWithPath:path];
277 NSString* urlString = [url absoluteString];
279 // Remove the host because this is a file:// URL;
280 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
282 // Escape % for use in printf-style NSString formatters.
283 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
288 * Returns the transaction_id from an NSXMLDocument.
290 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
292 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
296 * Scans a command string for the transaction ID component. If it is not found,
297 * returns NSNotFound.
299 - (NSInteger)transactionIDFromCommand:(NSString*)command
301 NSRange occurrence = [command rangeOfString:@"-i "];
302 if (occurrence.location == NSNotFound)
304 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
305 return [transaction intValue];
308 // Private /////////////////////////////////////////////////////////////////////
311 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
314 * Receives errors from the SocketWrapper and updates the display
316 - (void)errorEncountered:(NSString*)error
318 if (![delegate_ respondsToSelector:@selector(errorEncountered:)])
320 [delegate_ performSelectorOnMainThread:@selector(errorEncountered:)
325 - (LogEntry*)recordSend:(NSString*)command
327 LoggingController* logger = [[AppDelegate instance] loggingController];
328 LogEntry* entry = [LogEntry newSendEntry:command];
329 entry.lastReadTransactionID = lastReadTransaction_;
330 entry.lastWrittenTransactionID = lastWrittenTransaction_;
331 [logger performSelectorOnMainThread:@selector(recordEntry:)
334 return [entry autorelease];
337 - (LogEntry*)recordReceive:(NSString*)command
339 LoggingController* logger = [[AppDelegate instance] loggingController];
340 LogEntry* entry = [LogEntry newReceiveEntry:command];
341 entry.lastReadTransactionID = lastReadTransaction_;
342 entry.lastWrittenTransactionID = lastWrittenTransaction_;
343 [logger performSelectorOnMainThread:@selector(recordEntry:)
346 return [entry autorelease];
349 // Stream Managers /////////////////////////////////////////////////////////////
352 * Callback from the CFReadStream that there is data waiting to be read.
354 - (void)readStreamHasData
356 const NSUInteger kBufferSize = 1024;
357 UInt8 buffer[kBufferSize];
358 CFIndex bufferOffset = 0; // Starting point in |buffer| to work with.
359 CFIndex bytesRead = CFReadStreamRead(readStream_, buffer, kBufferSize);
360 const char* charBuffer = (const char*)buffer;
362 // The read loop works by going through the buffer until all the bytes have
364 while (bufferOffset < bytesRead)
366 // Find the NULL separator, or the end of the string.
367 NSUInteger partLength = 0;
368 for (NSUInteger i = bufferOffset; i < bytesRead && charBuffer[i] != '\0'; ++i, ++partLength) ;
370 // If there is not a current packet, set some state.
371 if (!self.currentPacket)
373 // Read the message header: the size. This will be |partLength| bytes.
374 packetSize_ = atoi(charBuffer + bufferOffset);
375 currentPacketIndex_ = 0;
376 self.currentPacket = [NSMutableString stringWithCapacity:packetSize_];
377 bufferOffset += partLength + 1; // Pass over the NULL byte.
378 continue; // Spin the loop to begin reading actual data.
381 // Substring the byte stream and append it to the packet string.
382 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
383 buffer + bufferOffset, // Byte pointer, offset by start index.
384 partLength, // Length.
385 kCFStringEncodingUTF8,
387 [self.currentPacket appendString:(NSString*)bufferString];
388 CFRelease(bufferString);
391 currentPacketIndex_ += partLength;
392 bufferOffset += partLength + 1;
394 // If this read finished the packet, handle it and reset.
395 if (currentPacketIndex_ >= packetSize_)
397 [self handlePacket:[[currentPacket_ retain] autorelease]];
398 self.currentPacket = nil;
400 currentPacketIndex_ = 0;
406 * Performs the packet handling of a raw string XML packet. From this point on,
407 * the packets are associated with a transaction and are then dispatched.
409 - (void)handlePacket:(NSString*)packet
411 // Test if we can convert it into an NSXMLDocument.
412 NSError* error = nil;
413 NSXMLDocument* xmlTest = [[NSXMLDocument alloc] initWithXMLString:currentPacket_ options:NSXMLDocumentTidyXML error:&error];
415 // Try to recover if we encountered an error.
418 // We do not want to starve the write queue, so manually parse out the
420 NSRange location = [currentPacket_ rangeOfString:@"transaction_id"];
421 if (location.location != NSNotFound)
423 NSUInteger start = location.location + location.length;
424 NSUInteger end = start;
426 NSCharacterSet* numericSet = [NSCharacterSet decimalDigitCharacterSet];
428 // Loop over the characters after the attribute name to extract the ID.
429 while (end < [currentPacket_ length])
431 unichar c = [currentPacket_ characterAtIndex:end];
432 if ([numericSet characterIsMember:c])
434 // If this character is numeric, extend the range to substring.
441 // If this character is nonnumeric and we have nothing in the
442 // range, skip this character.
448 // We've moved past the numeric ID so we should stop searching.
454 // If we were able to extract the transaction ID, update the last read.
455 NSRange substringRange = NSMakeRange(start, end - start);
456 NSString* transactionStr = [currentPacket_ substringWithRange:substringRange];
457 if ([transactionStr length])
458 lastReadTransaction_ = [transactionStr intValue];
461 // Otherwise, assume +1 and hope it works.
462 ++lastReadTransaction_;
463 } else /*if (!reconnect_)*/ {
464 // See if the transaction can be parsed out.
465 NSInteger transaction = [self transactionIDFromResponse:xmlTest];
466 if (transaction < lastReadTransaction_) {
467 NSLog(@"tx = %d vs %d", transaction, lastReadTransaction_);
468 NSLog(@"out of date transaction %@", packet);
472 if (transaction != lastWrittenTransaction_)
473 NSLog(@"txn %d <> %d last written, %d last read", transaction, lastWrittenTransaction_, lastReadTransaction_);
475 lastReadTransaction_ = transaction;
478 // Log this receive event.
479 LogEntry* log = [self recordReceive:currentPacket_];
482 // Finally, dispatch the handler for this response.
483 [self handleResponse:[xmlTest autorelease]];
486 - (void)handleResponse:(NSXMLDocument*)response
488 // Check and see if there's an error.
489 NSArray* error = [[response rootElement] elementsForName:@"error"];
490 if ([error count] > 0)
492 NSLog(@"Xdebug error: %@", error);
493 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
494 [self errorEncountered:errorMessage];
497 if ([[[response rootElement] name] isEqualToString:@"init"]) {
499 [delegate_ performSelectorOnMainThread:@selector(handleInitialResponse:)
505 if ([delegate_ respondsToSelector:@selector(handleResponse:)])
506 [delegate_ performSelectorOnMainThread:@selector(handleResponse:)
510 [self sendQueuedWrites];
514 * This performs a blocking send. This should ONLY be called when we know we
515 * have write access to the stream. We will busy wait in case we don't do a full
518 - (void)performSend:(NSString*)command
520 // If this is an out-of-date transaction, do not bother sending it.
521 NSInteger transaction = [self transactionIDFromCommand:command];
522 if (transaction != NSNotFound && transaction < lastWrittenTransaction_)
527 char* string = (char*)[command UTF8String];
528 int stringLength = strlen(string);
530 // Busy wait while writing. BAADD. Should background this operation.
533 if (CFWriteStreamCanAcceptBytes(writeStream_))
535 // Include the NULL byte in the string when we write.
536 int bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
537 if (bytesWritten < 0)
539 NSLog(@"write error");
542 else if (bytesWritten < strlen(string))
544 // Adjust the buffer and wait for another chance to write.
545 stringLength -= bytesWritten;
546 memmove(string, string + bytesWritten, stringLength);
552 // We need to scan the string to find the transactionID.
553 if (transaction == NSNotFound)
555 NSLog(@"sent %@ without a transaction ID", command);
558 lastWrittenTransaction_ = transaction;
563 // Log this trancation.
564 [self recordSend:command];
568 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
569 * them if it's OK to do so. This will not block.
571 - (void)sendQueuedWrites
576 [writeQueueLock_ lock];
577 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0)
579 NSString* command = [queuedWrites_ objectAtIndex:0];
581 // We don't want to block because this is called from the main thread.
582 // |-performSend:| busy waits when the stream is not ready. Bail out
583 // before we do that becuase busy waiting is BAD.
584 if (CFWriteStreamCanAcceptBytes(writeStream_))
586 [self performSend:command];
587 [queuedWrites_ removeObjectAtIndex:0];
590 [writeQueueLock_ unlock];