3 * Copyright (c) 2013, 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 "MessageQueue.h"
19 #include <netinet/in.h>
20 #include <sys/socket.h>
22 @interface MessageQueue (Private
)
23 // Thread main function that is started from -connect.
24 - (void)runMessageQueue
;
26 // All the following methods must be called from the -runMessageQueue thread.
28 // Creates a listening socket and schedules it in the run loop.
29 - (void)listenForClient
;
31 // Closes down the listening socket, the child socket, and the streams.
32 - (void)disconnectClient
;
34 // This first calls -disconnectClient and then stops the run loop and terminates
35 // the -runMessageQueue thread.
38 // Adds a |message| to |_queue|.
39 - (void)enqueueMessage
:(NSString
*)message
;
41 // If the write stream is ready and there is data to send, sends the next message.
42 - (void)dequeueAndSend
;
44 // Writes the string into the write stream.
45 - (void)performSend
:(NSString
*)message
;
47 // Reads bytes out of the read stream. This may be called multiple times if the
48 // message cannot be read in one pass.
49 - (void)readMessageFromStream
;
51 // Converts a CFErrorRef to an NSError and passes it to the delegate.
52 - (void)reportError
:(CFErrorRef
)error
;
54 // Forwarding methods from the CoreFoundation callbacks.
55 - (void)listenSocket
:(CFSocketRef
)socket acceptedSocket
:(CFSocketNativeHandle
)child
;
56 - (void)readStream
:(CFReadStreamRef
)stream handleEvent
:(CFStreamEventType
)event
;
57 - (void)writeStream
:(CFWriteStreamRef
)stream handleEvent
:(CFStreamEventType
)event
;
60 // CoreFoundation Callbacks ////////////////////////////////////////////////////
62 static void MessageQueueSocketAccept(CFSocketRef socket
,
63 CFSocketCallBackType callbackType
,
68 CFSocketNativeHandle child
= *(CFSocketNativeHandle
*)data
;
69 [(MessageQueue
*)self listenSocket
:socket acceptedSocket
:child
];
72 static void MessageQueueReadEvent(CFReadStreamRef stream
,
73 CFStreamEventType eventType
,
76 [(MessageQueue
*)self readStream
:stream handleEvent
:eventType
];
79 static void MessageQueueWriteEvent(CFWriteStreamRef stream
,
80 CFStreamEventType eventType
,
83 [(MessageQueue
*)self writeStream
:stream handleEvent
:eventType
];
86 ////////////////////////////////////////////////////////////////////////////////
88 @implementation MessageQueue
90 - (id)initWithPort
:(NSUInteger
)port delegate
:(id<MessageQueueDelegate
>)delegate
{
91 if ((self = [super init
])) {
93 _queue
= [[NSMutableArray alloc
] init
];
94 _delegate
= (BSProtocolThreadInvoker
<MessageQueueDelegate
>*)
95 [[BSProtocolThreadInvoker alloc
] initWithObject
:delegate
96 protocol
:@protocol(MessageQueueDelegate
)
97 thread
:[NSThread currentThread
]];
108 - (BOOL)isConnected
{
116 [NSThread detachNewThreadSelector
:@selector(runMessageQueue
)
122 [self performSelector
:@selector(stopRunLoop
)
128 - (void)sendMessage
:(NSString
*)message
{
129 [self performSelector
:@selector(enqueueMessage
:)
135 // Private /////////////////////////////////////////////////////////////////////
137 - (void)runMessageQueue
{
139 _thread
= [NSThread currentThread
];
140 _runLoop
= [NSRunLoop currentRunLoop
];
143 [self scheduleListenSocket
];
145 // Use CFRunLoop instead of NSRunLoop because the latter has no programmatic
154 - (void)scheduleListenSocket
{
155 // Create the address structure.
156 struct sockaddr_in address
;
157 memset(&address
, 0, sizeof(address
));
158 address.sin_len
= sizeof(address
);
159 address.sin_family
= AF_INET
;
160 address.sin_port
= htons(_port
);
161 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
163 // Create the socket signature.
164 CFSocketSignature signature
;
165 signature.protocolFamily
= PF_INET
;
166 signature.socketType
= SOCK_STREAM
;
167 signature.protocol
= IPPROTO_TCP
;
168 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
170 CFSocketContext context
= { 0 };
175 CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
176 &signature
, // Socket signature.
177 kCFSocketAcceptCallBack
, // Callback types.
178 &MessageQueueSocketAccept
, // Callback function.
179 &context
); // Context to pass to callout.
181 //[connection_ errorEncountered:@"Could not open socket."];
186 // Allow old, yet-to-be recycled sockets to be reused.
188 setsockopt(CFSocketGetNative(_socket
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(int));
189 setsockopt(CFSocketGetNative(_socket
), SOL_SOCKET
, SO_REUSEPORT
, &yes
, sizeof(int));
191 // Schedule the socket on the run loop.
192 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, _socket
, 0);
193 CFRunLoopAddSource([_runLoop getCFRunLoop
], source
, kCFRunLoopCommonModes
);
197 - (void)disconnectClient
{
199 CFReadStreamUnscheduleFromRunLoop(_readStream
, [_runLoop getCFRunLoop
], kCFRunLoopCommonModes
);
200 CFReadStreamClose(_readStream
);
201 CFRelease(_readStream
);
206 CFWriteStreamUnscheduleFromRunLoop(_writeStream
, [_runLoop getCFRunLoop
], kCFRunLoopCommonModes
);
207 CFWriteStreamClose(_writeStream
);
208 CFRelease(_writeStream
);
218 [_delegate messageQueueDidDisconnect
:self];
221 - (void)stopRunLoop
{
222 [self disconnectClient
];
223 CFRunLoopStop([_runLoop getCFRunLoop
]);
226 - (void)enqueueMessage
:(NSString
*)message
{
227 [_queue addObject
:message
];
228 [self dequeueAndSend
];
231 - (void)dequeueAndSend
{
235 if (!CFWriteStreamCanAcceptBytes(_writeStream
))
238 NSString
* message
= [_queue objectAtIndex
:0];
239 [self performSend
:message
];
240 [_queue removeObjectAtIndex
:0];
243 - (void)performSend
:(NSString
*)message
{
244 // TODO: May need to negotiate with the server as to the string encoding.
245 const NSStringEncoding kEncoding
= NSUTF8StringEncoding
;
246 // Add space for the NUL byte.
247 NSUInteger maxBufferSize
= [message maximumLengthOfBytesUsingEncoding
:kEncoding
] + 1;
249 UInt8
* buffer
= malloc(maxBufferSize
);
250 bzero(buffer
, maxBufferSize
);
252 NSUInteger bufferSize
= 0;
253 if (![message getBytes
:buffer
254 maxLength
:maxBufferSize
255 usedLength
:&bufferSize
258 range
:NSMakeRange(0, [message length
])
259 remainingRange
:NULL
]) {
264 // Include a NUL byte.
267 // Write the packet out, and spin in a busy wait loop if the stream is not ready. This
268 // method is only ever called in response to a stream ready event.
269 NSUInteger totalWritten
= 0;
270 while (totalWritten
< bufferSize
) {
271 CFIndex bytesWritten
= CFWriteStreamWrite(_writeStream
, buffer
+ totalWritten
, bufferSize
- totalWritten
);
272 if (bytesWritten
< 0) {
273 [self reportError
:CFWriteStreamCopyError(_writeStream
)];
276 totalWritten
+= bytesWritten
;
279 [_delegate messageQueue
:self didSendMessage
:message
];
284 - (void)readMessageFromStream
{
285 const NSUInteger kBufferSize
= 1024;
286 UInt8 buffer
[kBufferSize
];
287 CFIndex bufferOffset
= 0; // Starting point in |buffer| to work with.
288 CFIndex bytesRead
= CFReadStreamRead(_readStream
, buffer
, kBufferSize
);
289 const char* charBuffer
= (const char*)buffer
;
291 // The read loop works by going through the buffer until all the bytes have
293 while (bufferOffset
< bytesRead
) {
294 // Find the NUL separator, or the end of the string.
295 NSUInteger partLength
= 0;
296 for (CFIndex i
= bufferOffset
; i
< bytesRead
&& charBuffer
[i
] != '\0'; ++i
, ++partLength
) ;
298 // If there is not a current packet, set some state.
300 // Read the message header: the size. This will be |partLength| bytes.
301 _totalMessageSize
= atoi(charBuffer
+ bufferOffset
);
303 _message
= [[NSMutableString alloc
] initWithCapacity
:_totalMessageSize
];
304 bufferOffset
+= partLength
+ 1; // Pass over the NUL byte.
305 continue; // Spin the loop to begin reading actual data.
308 // Substring the byte stream and append it to the packet string.
309 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
310 buffer
+ bufferOffset
, // Byte pointer, offset by start index.
311 partLength
, // Length.
312 kCFStringEncodingUTF8
,
314 [_message appendString
:(NSString
*)bufferString
];
315 CFRelease(bufferString
);
318 _messageSize
+= partLength
;
319 bufferOffset
+= partLength
+ 1;
321 // If this read finished the packet, handle it and reset.
322 if (_messageSize
>= _totalMessageSize
) {
323 [_delegate messageQueue
:self didReceiveMessage
:[_message autorelease
]];
326 // Process any outgoing messages.
327 [self dequeueAndSend
];
332 - (void)listenSocket
:(CFSocketRef
)socket acceptedSocket
:(CFSocketNativeHandle
)child
{
333 if (socket
!= _socket
) {
340 // Create the streams on the socket.
341 CFStreamCreatePairWithSocket(kCFAllocatorDefault
,
342 _child
, // Socket handle.
343 &_readStream
, // Read stream in-pointer.
344 &_writeStream
); // Write stream in-pointer.
346 // Create struct to register callbacks for the stream.
347 CFStreamClientContext context
= { 0 };
350 // Set the client of the read stream.
351 CFOptionFlags readFlags
= kCFStreamEventOpenCompleted |
352 kCFStreamEventHasBytesAvailable |
353 kCFStreamEventErrorOccurred |
354 kCFStreamEventEndEncountered
;
355 if (CFReadStreamSetClient(_readStream
, readFlags
, &MessageQueueReadEvent
, &context
))
356 // Schedule in run loop to do asynchronous communication with the engine.
357 CFReadStreamScheduleWithRunLoop(_readStream
, [_runLoop getCFRunLoop
], kCFRunLoopCommonModes
);
361 // Open the stream now that it's scheduled on the run loop.
362 if (!CFReadStreamOpen(_readStream
)) {
363 [self reportError
:CFReadStreamCopyError(_readStream
)];
367 // Set the client of the write stream.
368 CFOptionFlags writeFlags
= kCFStreamEventOpenCompleted |
369 kCFStreamEventCanAcceptBytes |
370 kCFStreamEventErrorOccurred |
371 kCFStreamEventEndEncountered
;
372 if (CFWriteStreamSetClient(_writeStream
, writeFlags
, &MessageQueueWriteEvent
, &context
))
373 // Schedule it in the run loop to receive error information.
374 CFWriteStreamScheduleWithRunLoop(_writeStream
, [_runLoop getCFRunLoop
], kCFRunLoopCommonModes
);
378 // Open the write stream.
379 if (!CFWriteStreamOpen(_writeStream
)) {
380 [self reportError
:CFWriteStreamCopyError(_writeStream
)];
385 [_delegate messageQueueDidConnect
:self];
387 CFSocketInvalidate(_socket
);
392 - (void)reportError
:(CFErrorRef
)error
394 [_delegate messageQueue
:self error
:(NSError
*)error
];
398 - (void)readStream
:(CFReadStreamRef
)stream handleEvent
:(CFStreamEventType
)event
400 assert(stream
== _readStream
);
403 case kCFStreamEventHasBytesAvailable
:
404 [self readMessageFromStream
];
407 case kCFStreamEventErrorOccurred
:
408 [self reportError
:CFReadStreamCopyError(stream
)];
412 case kCFStreamEventEndEncountered
:
422 - (void)writeStream
:(CFWriteStreamRef
)stream handleEvent
:(CFStreamEventType
)event
424 assert(stream
== _writeStream
);
426 case kCFStreamEventCanAcceptBytes
:
427 [self dequeueAndSend
];
430 case kCFStreamEventErrorOccurred
:
431 [self reportError
:CFWriteStreamCopyError(stream
)];
435 case kCFStreamEventEndEncountered
: