4 * OS X networking support functions. Currently this is just for activity callbacks.
6 * Copyright (c) 2009 Nathan Keynes.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
19 #include <CoreFoundation/CoreFoundation.h>
22 struct net_osx_cbinfo {
23 net_callback_t callback;
25 void (*cbdealloc)(void *);
27 CFRunLoopSourceRef sourceRef;
30 static void net_osx_callback( CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *unused, void *data )
32 struct net_osx_cbinfo *cbinfo = (struct net_osx_cbinfo *)data;
33 if(!cbinfo->callback( CFSocketGetNative(s), cbinfo->cbdata) ) {
34 CFRunLoopRemoveSource( CFRunLoopGetCurrent(), cbinfo->sourceRef, kCFRunLoopCommonModes );
35 CFRelease(cbinfo->sourceRef);
36 cbinfo->sourceRef = NULL;
37 CFRelease(cbinfo->sockRef);
41 static void net_osx_release( const void *data )
43 struct net_osx_cbinfo *cbinfo = (struct net_osx_cbinfo *)data;
44 if( cbinfo->cbdealloc != NULL ) {
45 cbinfo->cbdealloc(cbinfo->cbdata);
51 * Register a TCP server socket listener on an already open (and listening)
52 * socket. The socket must not have been previously registered.
53 * @return TRUE on success, FALSE on failure.
55 * Defined in netutil.h
57 gboolean net_register_tcp_listener( int fd, net_callback_t callback, void *data, void (*dealloc)(void*) )
59 CFSocketContext socketContext;
60 struct net_osx_cbinfo *cbinfo = malloc( sizeof(struct net_osx_cbinfo) );
61 assert(cbinfo != NULL);
63 cbinfo->callback = callback;
64 cbinfo->cbdata = data;
65 cbinfo->cbdealloc = dealloc;
66 socketContext.version = 0;
67 socketContext.info = cbinfo;
68 socketContext.retain = NULL;
69 socketContext.release = net_osx_release;
70 socketContext.copyDescription = NULL;
72 cbinfo->sockRef = CFSocketCreateWithNative( kCFAllocatorDefault, fd, kCFSocketReadCallBack,
73 net_osx_callback, &socketContext );
74 cbinfo->sourceRef = CFSocketCreateRunLoopSource( kCFAllocatorDefault, cbinfo->sockRef, 0 );
75 CFRunLoopAddSource( CFRunLoopGetCurrent(), cbinfo->sourceRef, kCFRunLoopCommonModes );
.