Move out of 1.5 beta to stable, and update the copyright years.
[macgdbp.git] / Source / NetworkCallbackController.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 "NetworkCallbackController.h"
18
19 #import <sys/socket.h>
20 #import <netinet/in.h>
21
22 #import "NetworkConnection.h"
23 #import "NetworkConnectionPrivate.h"
24
25 NetworkCallbackController::NetworkCallbackController(NetworkConnection* connection)
26 : listeningSocket_(NULL),
27 socketHandle_(NULL),
28 readStream_(NULL),
29 writeStream_(NULL),
30 connection_(connection),
31 runLoop_(CFRunLoopGetCurrent())
32 {
33 }
34
35 void NetworkCallbackController::OpenConnection(NSUInteger port)
36 {
37 // Pass ourselves to the callback so we don't have to use ugly globals.
38 CFSocketContext context = { 0 };
39 context.info = this;
40
41 // Create the address structure.
42 struct sockaddr_in address;
43 memset(&address, 0, sizeof(address));
44 address.sin_len = sizeof(address);
45 address.sin_family = AF_INET;
46 address.sin_port = htons(port);
47 address.sin_addr.s_addr = htonl(INADDR_ANY);
48
49 // Create the socket signature.
50 CFSocketSignature signature;
51 signature.protocolFamily = PF_INET;
52 signature.socketType = SOCK_STREAM;
53 signature.protocol = IPPROTO_TCP;
54 signature.address = (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)];
55
56 do {
57 listeningSocket_ =
58 CFSocketCreateWithSocketSignature(kCFAllocatorDefault,
59 &signature, // Socket signature.
60 kCFSocketAcceptCallBack, // Callback types.
61 &NetworkCallbackController::SocketAcceptCallback, // Callout function pointer.
62 &context); // Context to pass to callout.
63 if (!listeningSocket_) {
64 [connection_ errorEncountered:@"Could not open socket."];
65 sleep(1);
66 }
67 } while (!listeningSocket_);
68
69 // Allow old, yet-to-be recycled sockets to be reused.
70 BOOL yes = YES;
71 setsockopt(CFSocketGetNative(listeningSocket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
72 setsockopt(CFSocketGetNative(listeningSocket_), SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(BOOL));
73
74 // Schedule the socket on the run loop.
75 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, listeningSocket_, 0);
76 CFRunLoopAddSource(runLoop_, source, kCFRunLoopCommonModes);
77 CFRelease(source);
78 }
79
80 void NetworkCallbackController::CloseConnection()
81 {
82 UnscheduleReadStream();
83 UnscheduleWriteStream();
84
85 if (socketHandle_) {
86 close(socketHandle_);
87 socketHandle_ = NULL;
88 [connection_ socketDisconnected];
89 }
90 }
91
92 BOOL NetworkCallbackController::WriteStreamCanAcceptBytes()
93 {
94 return writeStream_ && CFWriteStreamCanAcceptBytes(writeStream_);
95 }
96
97 BOOL NetworkCallbackController::WriteString(NSString* string)
98 {
99 BOOL done = NO;
100
101 char* cString = const_cast<char*>([string UTF8String]);
102 size_t stringLength = strlen(cString);
103
104 // Busy wait while writing. BAADD. Should background this operation.
105 while (!done) {
106 if (WriteStreamCanAcceptBytes()) {
107 // Include the NULL byte in the string when we write.
108 CFIndex bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)cString, stringLength + 1);
109 if (bytesWritten < 0) {
110 CFErrorRef error = CFWriteStreamCopyError(writeStream_);
111 ReportError(error);
112 break;
113 }
114 // Incomplete write.
115 else if (bytesWritten < static_cast<CFIndex>(strlen(cString))) {
116 // Adjust the buffer and wait for another chance to write.
117 stringLength -= bytesWritten;
118 memmove(string, string + bytesWritten, stringLength);
119 }
120 else {
121 done = YES;
122 }
123 }
124 }
125
126 return done;
127 }
128
129 // Static Methods //////////////////////////////////////////////////////////////
130
131 void NetworkCallbackController::SocketAcceptCallback(CFSocketRef socket,
132 CFSocketCallBackType callbackType,
133 CFDataRef address,
134 const void* data,
135 void* self)
136 {
137 assert(callbackType == kCFSocketAcceptCallBack);
138 static_cast<NetworkCallbackController*>(self)->OnSocketAccept(socket, address, data);
139 }
140
141 void NetworkCallbackController::ReadStreamCallback(CFReadStreamRef stream,
142 CFStreamEventType eventType,
143 void* self)
144 {
145 static_cast<NetworkCallbackController*>(self)->OnReadStreamEvent(stream, eventType);
146 }
147
148 void NetworkCallbackController::WriteStreamCallback(CFWriteStreamRef stream,
149 CFStreamEventType eventType,
150 void* self)
151 {
152 static_cast<NetworkCallbackController*>(self)->OnWriteStreamEvent(stream, eventType);
153 }
154
155
156 // Private Instance Methods ////////////////////////////////////////////////////
157
158 void NetworkCallbackController::OnSocketAccept(CFSocketRef socket,
159 CFDataRef address,
160 const void* data)
161 {
162 // Keep a reference to the socket handle of the child socket. Do not create
163 // a CFSocket with this because doing so prohibits the use of streams. The
164 // kCFSocketDataCallBack would have to be used instead.
165 socketHandle_ = *(CFSocketNativeHandle*)data;
166
167 // Create the streams on the socket.
168 CFStreamCreatePairWithSocket(kCFAllocatorDefault,
169 socketHandle_, // Socket handle.
170 &readStream_, // Read stream in-pointer.
171 &writeStream_); // Write stream in-pointer.
172
173 // Create struct to register callbacks for the stream.
174 CFStreamClientContext context = { 0 };
175 context.info = this;
176
177 // Set the client of the read stream.
178 CFOptionFlags readFlags = kCFStreamEventOpenCompleted |
179 kCFStreamEventHasBytesAvailable |
180 kCFStreamEventErrorOccurred |
181 kCFStreamEventEndEncountered;
182 if (CFReadStreamSetClient(readStream_, readFlags, &NetworkCallbackController::ReadStreamCallback, &context))
183 // Schedule in run loop to do asynchronous communication with the engine.
184 CFReadStreamScheduleWithRunLoop(readStream_, runLoop_, kCFRunLoopCommonModes);
185 else
186 return;
187
188 // Open the stream now that it's scheduled on the run loop.
189 if (!CFReadStreamOpen(readStream_)) {
190 ReportError(CFReadStreamCopyError(readStream_));
191 return;
192 }
193
194 // Set the client of the write stream.
195 CFOptionFlags writeFlags = kCFStreamEventOpenCompleted |
196 kCFStreamEventCanAcceptBytes |
197 kCFStreamEventErrorOccurred |
198 kCFStreamEventEndEncountered;
199 if (CFWriteStreamSetClient(writeStream_, writeFlags, &NetworkCallbackController::WriteStreamCallback, &context))
200 // Schedule it in the run loop to receive error information.
201 CFWriteStreamScheduleWithRunLoop(writeStream_, runLoop_, kCFRunLoopCommonModes);
202 else
203 return;
204
205 // Open the write stream.
206 if (!CFWriteStreamOpen(writeStream_)) {
207 ReportError(CFWriteStreamCopyError(writeStream_));
208 return;
209 }
210
211 [connection_ socketDidAccept];
212
213 CloseSocket();
214 }
215
216 void NetworkCallbackController::OnReadStreamEvent(CFReadStreamRef stream,
217 CFStreamEventType eventType)
218 {
219 switch (eventType)
220 {
221 case kCFStreamEventHasBytesAvailable:
222 if (readStream_)
223 [connection_ readStreamHasData:stream];
224 break;
225
226 case kCFStreamEventErrorOccurred:
227 ReportError(CFReadStreamCopyError(stream));
228 CloseConnection();
229 break;
230
231 case kCFStreamEventEndEncountered:
232 CloseConnection();
233 break;
234 };
235 }
236
237 void NetworkCallbackController::OnWriteStreamEvent(CFWriteStreamRef stream,
238 CFStreamEventType eventType)
239 {
240 switch (eventType)
241 {
242 case kCFStreamEventCanAcceptBytes:
243 [connection_ sendQueuedWrites];
244 break;
245
246 case kCFStreamEventErrorOccurred:
247 ReportError(CFWriteStreamCopyError(stream));
248 CloseConnection();
249 break;
250
251 case kCFStreamEventEndEncountered:
252 CloseConnection();
253 break;
254 }
255 }
256
257 void NetworkCallbackController::CloseSocket()
258 {
259 if (listeningSocket_) {
260 CFSocketInvalidate(listeningSocket_);
261 CFRelease(listeningSocket_);
262 listeningSocket_ = NULL;
263 }
264 }
265
266 void NetworkCallbackController::UnscheduleReadStream()
267 {
268 if (!readStream_)
269 return;
270 CFReadStreamUnscheduleFromRunLoop(readStream_, runLoop_, kCFRunLoopCommonModes);
271 CFReadStreamClose(readStream_);
272 CFRelease(readStream_);
273 readStream_ = NULL;
274 }
275
276 void NetworkCallbackController::UnscheduleWriteStream()
277 {
278 if (!writeStream_)
279 return;
280 CFWriteStreamUnscheduleFromRunLoop(writeStream_, runLoop_, kCFRunLoopCommonModes);
281 CFWriteStreamClose(writeStream_);
282 CFRelease(writeStream_);
283 writeStream_ = NULL;
284 }
285
286 void NetworkCallbackController::ReportError(CFErrorRef error)
287 {
288 [connection_ errorEncountered:[(NSError*)error description]];
289 CFRelease(error);
290 }