Remove some dead code in -[NetworkConnection socketDisconnected]
[macgdbp.git] / Source / NetworkConnection.mm
1 /*
2 * MacGDBp
3 * Copyright (c) 2007 - 2011, Blue Static <http://www.bluestatic.org>
4 *
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.
8 *
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.
12 *
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
15 */
16
17 #import "NetworkConnection.h"
18 #import "NetworkConnectionPrivate.h"
19
20 #import <sys/socket.h>
21 #import <netinet/in.h>
22
23 #import "AppDelegate.h"
24 #import "LoggingController.h"
25 #include "NetworkCallbackController.h"
26
27 // Other Run Loop Callbacks ////////////////////////////////////////////////////
28
29 void PerformQuitSignal(void* info)
30 {
31 NetworkConnection* obj = (NetworkConnection*)info;
32 [obj performQuitSignal];
33 }
34
35 ////////////////////////////////////////////////////////////////////////////////
36
37 @implementation NetworkConnection
38
39 @synthesize port = port_;
40 @synthesize connected = connected_;
41 @synthesize delegate = delegate_;
42
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_;
50
51 - (id)initWithPort:(NSUInteger)aPort
52 {
53 if (self = [super init])
54 {
55 port_ = aPort;
56 }
57 return self;
58 }
59
60 - (void)dealloc
61 {
62 self.currentPacket = nil;
63 [super dealloc];
64 }
65
66 /**
67 * Kicks off the socket on another thread.
68 */
69 - (void)connect
70 {
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
74 // socket.
75 return;
76 }
77 [NSThread detachNewThreadSelector:@selector(runNetworkThread) toTarget:self withObject:nil];
78 }
79
80 /**
81 * Creates, connects to, and schedules a CFSocket.
82 */
83 - (void)runNetworkThread
84 {
85 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
86
87 thread_ = [NSThread currentThread];
88 runLoop_ = [NSRunLoop currentRunLoop];
89 callbackController_ = new NetworkCallbackController(self);
90
91 // Pass ourselves to the callback so we don't have to use ugly globals.
92 CFSocketContext context = { 0 };
93 context.info = callbackController_;
94
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);
102
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)];
109
110 do {
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.
116 if (!socket_) {
117 [self errorEncountered:@"Could not open socket."];
118 sleep(1);
119 }
120 } while (!socket_);
121
122 // Allow old, yet-to-be recycled sockets to be reused.
123 BOOL yes = YES;
124 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
125 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(BOOL));
126
127 // Schedule the socket on the run loop.
128 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 0);
129 CFRunLoopAddSource([runLoop_ getCFRunLoop], source, kCFRunLoopCommonModes);
130 CFRelease(source);
131
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);
138
139 CFRunLoopRun();
140
141 thread_ = nil;
142 runLoop_ = nil;
143 delete callbackController_;
144 callbackController_ = NULL;
145
146 CFRunLoopSourceInvalidate(quitSource_);
147 CFRelease(quitSource_);
148 quitSource_ = NULL;
149
150 [pool release];
151 }
152
153 /**
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.
157 */
158 - (void)socketDidAccept
159 {
160 connected_ = YES;
161 transactionID = 1;
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:)
168 withObject:self
169 waitUntilDone:NO];
170 }
171
172 /**
173 * Closes a socket and releases the ref.
174 */
175 - (void)close
176 {
177 if (thread_) {
178 [thread_ cancel];
179 }
180 if (runLoop_ && quitSource_) {
181 CFRunLoopSourceSignal(quitSource_);
182 CFRunLoopWakeUp([runLoop_ getCFRunLoop]);
183 }
184 }
185
186 /**
187 * Quits the run loop and stops the thread.
188 */
189 - (void)performQuitSignal
190 {
191 self.queuedWrites = nil;
192 connected_ = NO;
193 [writeQueueLock_ release];
194
195 if (runLoop_) {
196 CFRunLoopStop([runLoop_ getCFRunLoop]);
197 }
198
199 // The socket goes down, so do the streams, which clean themselves up.
200 if (socket_) {
201 NSLog(@"invalidating socket");
202 CFSocketInvalidate(socket_);
203 CFRelease(socket_);
204 socket_ = NULL;
205 }
206 }
207
208 /**
209 * Notification that the socket disconnected.
210 */
211 - (void)socketDisconnected
212 {
213 if ([delegate_ respondsToSelector:@selector(connectionDidClose:)])
214 [delegate_ connectionDidClose:self];
215 }
216
217 /**
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.
221 */
222 - (void)send:(NSString*)command
223 {
224 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_)) {
225 [self performSend:command];
226 } else {
227 [writeQueueLock_ lock];
228 [queuedWrites_ addObject:command];
229 [writeQueueLock_ unlock];
230 }
231 [self sendQueuedWrites];
232 }
233
234 /**
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.
239 */
240 - (NSNumber*)sendCommandWithFormat:(NSString*)format, ...
241 {
242 // Collect varargs and format command.
243 va_list args;
244 va_start(args, format);
245 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
246 va_end(args);
247
248 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
249 NSString* taggedCommand = [NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey];
250 [self performSelector:@selector(send:)
251 onThread:thread_
252 withObject:taggedCommand
253 waitUntilDone:connected_];
254
255 return callbackKey;
256 }
257
258 /**
259 * Given a file path, this returns a file:// URI and escapes any spaces for the
260 * debugger engine.
261 */
262 - (NSString*)escapedURIPath:(NSString*)path
263 {
264 // Custon GDBp paths are fine.
265 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
266 return path;
267
268 // Create a temporary URL that will escape all the nasty characters.
269 NSURL* url = [NSURL fileURLWithPath:path];
270 NSString* urlString = [url absoluteString];
271
272 // Remove the host because this is a file:// URL;
273 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
274
275 // Escape % for use in printf-style NSString formatters.
276 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
277 return urlString;
278 }
279
280 /**
281 * Returns the transaction_id from an NSXMLDocument.
282 */
283 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
284 {
285 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
286 }
287
288 /**
289 * Scans a command string for the transaction ID component. If it is not found,
290 * returns NSNotFound.
291 */
292 - (NSInteger)transactionIDFromCommand:(NSString*)command
293 {
294 NSRange occurrence = [command rangeOfString:@"-i "];
295 if (occurrence.location == NSNotFound)
296 return NSNotFound;
297 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
298 return [transaction intValue];
299 }
300
301 // Private /////////////////////////////////////////////////////////////////////
302 #pragma mark Private
303
304 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
305
306 /**
307 * Receives errors from the SocketWrapper and updates the display
308 */
309 - (void)errorEncountered:(NSString*)error
310 {
311 if (![delegate_ respondsToSelector:@selector(errorEncountered:)])
312 return;
313 [delegate_ performSelectorOnMainThread:@selector(errorEncountered:)
314 withObject:error
315 waitUntilDone:NO];
316 }
317
318 - (LogEntry*)recordSend:(NSString*)command
319 {
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:)
325 withObject:entry
326 waitUntilDone:NO];
327 return [entry autorelease];
328 }
329
330 - (LogEntry*)recordReceive:(NSString*)command
331 {
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:)
337 withObject:entry
338 waitUntilDone:NO];
339 return [entry autorelease];
340 }
341
342 // Stream Managers /////////////////////////////////////////////////////////////
343
344 /**
345 * Callback from the CFReadStream that there is data waiting to be read.
346 */
347 - (void)readStreamHasData
348 {
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;
354
355 // The read loop works by going through the buffer until all the bytes have
356 // been processed.
357 while (bufferOffset < bytesRead)
358 {
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) ;
362
363 // If there is not a current packet, set some state.
364 if (!self.currentPacket)
365 {
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.
372 }
373
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,
379 true);
380 [self.currentPacket appendString:(NSString*)bufferString];
381 CFRelease(bufferString);
382
383 // Advance counters.
384 currentPacketIndex_ += partLength;
385 bufferOffset += partLength + 1;
386
387 // If this read finished the packet, handle it and reset.
388 if (currentPacketIndex_ >= packetSize_)
389 {
390 [self handlePacket:[[currentPacket_ retain] autorelease]];
391 self.currentPacket = nil;
392 packetSize_ = 0;
393 currentPacketIndex_ = 0;
394 }
395 }
396 }
397
398 /**
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.
401 */
402 - (void)handlePacket:(NSString*)packet
403 {
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];
407
408 // Try to recover if we encountered an error.
409 if (!xmlTest)
410 {
411 // We do not want to starve the write queue, so manually parse out the
412 // transaction ID.
413 NSRange location = [currentPacket_ rangeOfString:@"transaction_id"];
414 if (location.location != NSNotFound)
415 {
416 NSUInteger start = location.location + location.length;
417 NSUInteger end = start;
418
419 NSCharacterSet* numericSet = [NSCharacterSet decimalDigitCharacterSet];
420
421 // Loop over the characters after the attribute name to extract the ID.
422 while (end < [currentPacket_ length])
423 {
424 unichar c = [currentPacket_ characterAtIndex:end];
425 if ([numericSet characterIsMember:c])
426 {
427 // If this character is numeric, extend the range to substring.
428 ++end;
429 }
430 else
431 {
432 if (start == end)
433 {
434 // If this character is nonnumeric and we have nothing in the
435 // range, skip this character.
436 ++start;
437 ++end;
438 }
439 else
440 {
441 // We've moved past the numeric ID so we should stop searching.
442 break;
443 }
444 }
445 }
446
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];
452 }
453
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);
462 return;
463 }
464
465 if (transaction != lastWrittenTransaction_)
466 NSLog(@"txn %d <> %d last written, %d last read", transaction, lastWrittenTransaction_, lastReadTransaction_);
467
468 lastReadTransaction_ = transaction;
469 }
470
471 // Log this receive event.
472 LogEntry* log = [self recordReceive:currentPacket_];
473 log.error = error;
474
475 // Finally, dispatch the handler for this response.
476 [self handleResponse:[xmlTest autorelease]];
477 }
478
479 - (void)handleResponse:(NSXMLDocument*)response
480 {
481 // Check and see if there's an error.
482 NSArray* error = [[response rootElement] elementsForName:@"error"];
483 if ([error count] > 0)
484 {
485 NSLog(@"Xdebug error: %@", error);
486 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
487 [self errorEncountered:errorMessage];
488 }
489
490 if ([[[response rootElement] name] isEqualToString:@"init"]) {
491 connected_ = YES;
492 [delegate_ performSelectorOnMainThread:@selector(handleInitialResponse:)
493 withObject:response
494 waitUntilDone:NO];
495 return;
496 }
497
498 if ([delegate_ respondsToSelector:@selector(handleResponse:)])
499 [delegate_ performSelectorOnMainThread:@selector(handleResponse:)
500 withObject:response
501 waitUntilDone:NO];
502
503 [self sendQueuedWrites];
504 }
505
506 /**
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
509 * send.
510 */
511 - (void)performSend:(NSString*)command
512 {
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_)
516 return;
517
518 BOOL done = NO;
519
520 char* string = (char*)[command UTF8String];
521 int stringLength = strlen(string);
522
523 // Busy wait while writing. BAADD. Should background this operation.
524 while (!done)
525 {
526 if (CFWriteStreamCanAcceptBytes(writeStream_))
527 {
528 // Include the NULL byte in the string when we write.
529 int bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
530 if (bytesWritten < 0)
531 {
532 NSLog(@"write error");
533 }
534 // Incomplete write.
535 else if (bytesWritten < strlen(string))
536 {
537 // Adjust the buffer and wait for another chance to write.
538 stringLength -= bytesWritten;
539 memmove(string, string + bytesWritten, stringLength);
540 }
541 else
542 {
543 done = YES;
544
545 // We need to scan the string to find the transactionID.
546 if (transaction == NSNotFound)
547 {
548 NSLog(@"sent %@ without a transaction ID", command);
549 continue;
550 }
551 lastWrittenTransaction_ = transaction;
552 }
553 }
554 }
555
556 // Log this trancation.
557 [self recordSend:command];
558 }
559
560 /**
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.
563 */
564 - (void)sendQueuedWrites
565 {
566 if (!connected_)
567 return;
568
569 [writeQueueLock_ lock];
570 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0)
571 {
572 NSString* command = [queuedWrites_ objectAtIndex:0];
573
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_))
578 {
579 [self performSend:command];
580 [queuedWrites_ removeObjectAtIndex:0];
581 }
582 }
583 [writeQueueLock_ unlock];
584 }
585
586 @end