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 "NetworkCallbackController.h"
19 #import <sys/socket.h>
20 #import <netinet/in.h>
22 #import "NetworkConnection.h"
23 #import "NetworkConnectionPrivate.h"
25 NetworkCallbackController::NetworkCallbackController(NetworkConnection* connection)
26 : listeningSocket_(NULL),
30 connection_(connection),
31 runLoop_(CFRunLoopGetCurrent())
35 void NetworkCallbackController::OpenConnection(NSUInteger port)
37 // Pass ourselves to the callback so we don't have to use ugly globals.
38 CFSocketContext context = { 0 };
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);
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)];
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."];
67 } while (!listeningSocket_);
69 // Allow old, yet-to-be recycled sockets to be reused.
71 setsockopt(CFSocketGetNative(listeningSocket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
72 setsockopt(CFSocketGetNative(listeningSocket_), SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(BOOL));
74 // Schedule the socket on the run loop.
75 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, listeningSocket_, 0);
76 CFRunLoopAddSource(runLoop_, source, kCFRunLoopCommonModes);
80 void NetworkCallbackController::CloseConnection()
82 UnscheduleReadStream();
83 UnscheduleWriteStream();
88 [connection_ socketDisconnected];
92 BOOL NetworkCallbackController::WriteStreamCanAcceptBytes()
94 return writeStream_ && CFWriteStreamCanAcceptBytes(writeStream_);
97 BOOL NetworkCallbackController::WriteString(NSString* string)
101 char* cString = const_cast<char*>([string UTF8String]);
102 size_t stringLength = strlen(cString);
104 // Busy wait while writing. BAADD. Should background this operation.
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_);
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);
129 // Static Methods //////////////////////////////////////////////////////////////
131 void NetworkCallbackController::SocketAcceptCallback(CFSocketRef socket,
132 CFSocketCallBackType callbackType,
137 assert(callbackType == kCFSocketAcceptCallBack);
138 static_cast<NetworkCallbackController*>(self)->OnSocketAccept(socket, address, data);
141 void NetworkCallbackController::ReadStreamCallback(CFReadStreamRef stream,
142 CFStreamEventType eventType,
145 static_cast<NetworkCallbackController*>(self)->OnReadStreamEvent(stream, eventType);
148 void NetworkCallbackController::WriteStreamCallback(CFWriteStreamRef stream,
149 CFStreamEventType eventType,
152 static_cast<NetworkCallbackController*>(self)->OnWriteStreamEvent(stream, eventType);
156 // Private Instance Methods ////////////////////////////////////////////////////
158 void NetworkCallbackController::OnSocketAccept(CFSocketRef socket,
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;
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.
173 // Create struct to register callbacks for the stream.
174 CFStreamClientContext context = { 0 };
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);
188 // Open the stream now that it's scheduled on the run loop.
189 if (!CFReadStreamOpen(readStream_)) {
190 ReportError(CFReadStreamCopyError(readStream_));
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);
205 // Open the write stream.
206 if (!CFWriteStreamOpen(writeStream_)) {
207 ReportError(CFWriteStreamCopyError(writeStream_));
211 [connection_ socketDidAccept];
216 void NetworkCallbackController::OnReadStreamEvent(CFReadStreamRef stream,
217 CFStreamEventType eventType)
221 case kCFStreamEventHasBytesAvailable:
223 [connection_ readStreamHasData:stream];
226 case kCFStreamEventErrorOccurred:
227 ReportError(CFReadStreamCopyError(stream));
231 case kCFStreamEventEndEncountered:
237 void NetworkCallbackController::OnWriteStreamEvent(CFWriteStreamRef stream,
238 CFStreamEventType eventType)
242 case kCFStreamEventCanAcceptBytes:
243 [connection_ sendQueuedWrites];
246 case kCFStreamEventErrorOccurred:
247 ReportError(CFWriteStreamCopyError(stream));
251 case kCFStreamEventEndEncountered:
257 void NetworkCallbackController::CloseSocket()
259 if (listeningSocket_) {
260 CFSocketInvalidate(listeningSocket_);
261 CFRelease(listeningSocket_);
262 listeningSocket_ = NULL;
266 void NetworkCallbackController::UnscheduleReadStream()
270 CFReadStreamUnscheduleFromRunLoop(readStream_, runLoop_, kCFRunLoopCommonModes);
271 CFReadStreamClose(readStream_);
272 CFRelease(readStream_);
276 void NetworkCallbackController::UnscheduleWriteStream()
280 CFWriteStreamUnscheduleFromRunLoop(writeStream_, runLoop_, kCFRunLoopCommonModes);
281 CFWriteStreamClose(writeStream_);
282 CFRelease(writeStream_);
286 void NetworkCallbackController::ReportError(CFErrorRef error)
288 [connection_ errorEncountered:[(NSError*)error description]];