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)
99 // TODO: May need to negotiate with the server as to the string encoding.
100 const NSStringEncoding kEncoding = NSUTF8StringEncoding;
101 // Add space for the NUL byte.
102 NSUInteger maxBufferSize = [string maximumLengthOfBytesUsingEncoding:kEncoding] + 1;
104 UInt8* buffer = new UInt8[maxBufferSize];
105 bzero(buffer, maxBufferSize);
107 NSUInteger bufferSize = 0;
108 if (![string getBytes:buffer
109 maxLength:maxBufferSize
110 usedLength:&bufferSize
113 range:NSMakeRange(0, [string length])
114 remainingRange:NULL]) {
119 // Include a NUL byte.
122 // Busy wait while writing. BAADD. Should background this operation.
123 NSUInteger totalWritten = 0;
124 while (totalWritten < bufferSize) {
125 if (WriteStreamCanAcceptBytes()) {
126 // Include the NULL byte in the string when we write.
127 CFIndex bytesWritten = CFWriteStreamWrite(writeStream_, buffer + totalWritten, bufferSize - totalWritten);
128 if (bytesWritten < 0) {
129 CFErrorRef error = CFWriteStreamCopyError(writeStream_);
133 totalWritten += bytesWritten;
141 // Static Methods //////////////////////////////////////////////////////////////
143 void NetworkCallbackController::SocketAcceptCallback(CFSocketRef socket,
144 CFSocketCallBackType callbackType,
149 assert(callbackType == kCFSocketAcceptCallBack);
150 static_cast<NetworkCallbackController*>(self)->OnSocketAccept(socket, address, data);
153 void NetworkCallbackController::ReadStreamCallback(CFReadStreamRef stream,
154 CFStreamEventType eventType,
157 static_cast<NetworkCallbackController*>(self)->OnReadStreamEvent(stream, eventType);
160 void NetworkCallbackController::WriteStreamCallback(CFWriteStreamRef stream,
161 CFStreamEventType eventType,
164 static_cast<NetworkCallbackController*>(self)->OnWriteStreamEvent(stream, eventType);
168 // Private Instance Methods ////////////////////////////////////////////////////
170 void NetworkCallbackController::OnSocketAccept(CFSocketRef socket,
174 // Keep a reference to the socket handle of the child socket. Do not create
175 // a CFSocket with this because doing so prohibits the use of streams. The
176 // kCFSocketDataCallBack would have to be used instead.
177 socketHandle_ = *(CFSocketNativeHandle*)data;
179 // Create the streams on the socket.
180 CFStreamCreatePairWithSocket(kCFAllocatorDefault,
181 socketHandle_, // Socket handle.
182 &readStream_, // Read stream in-pointer.
183 &writeStream_); // Write stream in-pointer.
185 // Create struct to register callbacks for the stream.
186 CFStreamClientContext context = { 0 };
189 // Set the client of the read stream.
190 CFOptionFlags readFlags = kCFStreamEventOpenCompleted |
191 kCFStreamEventHasBytesAvailable |
192 kCFStreamEventErrorOccurred |
193 kCFStreamEventEndEncountered;
194 if (CFReadStreamSetClient(readStream_, readFlags, &NetworkCallbackController::ReadStreamCallback, &context))
195 // Schedule in run loop to do asynchronous communication with the engine.
196 CFReadStreamScheduleWithRunLoop(readStream_, runLoop_, kCFRunLoopCommonModes);
200 // Open the stream now that it's scheduled on the run loop.
201 if (!CFReadStreamOpen(readStream_)) {
202 ReportError(CFReadStreamCopyError(readStream_));
206 // Set the client of the write stream.
207 CFOptionFlags writeFlags = kCFStreamEventOpenCompleted |
208 kCFStreamEventCanAcceptBytes |
209 kCFStreamEventErrorOccurred |
210 kCFStreamEventEndEncountered;
211 if (CFWriteStreamSetClient(writeStream_, writeFlags, &NetworkCallbackController::WriteStreamCallback, &context))
212 // Schedule it in the run loop to receive error information.
213 CFWriteStreamScheduleWithRunLoop(writeStream_, runLoop_, kCFRunLoopCommonModes);
217 // Open the write stream.
218 if (!CFWriteStreamOpen(writeStream_)) {
219 ReportError(CFWriteStreamCopyError(writeStream_));
223 [connection_ socketDidAccept];
228 void NetworkCallbackController::OnReadStreamEvent(CFReadStreamRef stream,
229 CFStreamEventType eventType)
233 case kCFStreamEventHasBytesAvailable:
235 [connection_ readStreamHasData:stream];
238 case kCFStreamEventErrorOccurred:
239 ReportError(CFReadStreamCopyError(stream));
243 case kCFStreamEventEndEncountered:
249 void NetworkCallbackController::OnWriteStreamEvent(CFWriteStreamRef stream,
250 CFStreamEventType eventType)
254 case kCFStreamEventCanAcceptBytes:
255 [connection_ sendQueuedWrites];
258 case kCFStreamEventErrorOccurred:
259 ReportError(CFWriteStreamCopyError(stream));
263 case kCFStreamEventEndEncountered:
269 void NetworkCallbackController::CloseSocket()
271 if (listeningSocket_) {
272 CFSocketInvalidate(listeningSocket_);
273 CFRelease(listeningSocket_);
274 listeningSocket_ = NULL;
278 void NetworkCallbackController::UnscheduleReadStream()
282 CFReadStreamUnscheduleFromRunLoop(readStream_, runLoop_, kCFRunLoopCommonModes);
283 CFReadStreamClose(readStream_);
284 CFRelease(readStream_);
288 void NetworkCallbackController::UnscheduleWriteStream()
292 CFWriteStreamUnscheduleFromRunLoop(writeStream_, runLoop_, kCFRunLoopCommonModes);
293 CFWriteStreamClose(writeStream_);
294 CFRelease(writeStream_);
298 void NetworkCallbackController::ReportError(CFErrorRef error)
300 [connection_ errorEncountered:[(NSError*)error description]];