Move dealing with the socket into NetworkCallbackController.
[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 : connection_(connection),
27 runLoop_(CFRunLoopGetCurrent())
28 {
29 }
30
31 void NetworkCallbackController::OpenConnection(NSUInteger port)
32 {
33 // Pass ourselves to the callback so we don't have to use ugly globals.
34 CFSocketContext context = { 0 };
35 context.info = this;
36
37 // Create the address structure.
38 struct sockaddr_in address;
39 memset(&address, 0, sizeof(address));
40 address.sin_len = sizeof(address);
41 address.sin_family = AF_INET;
42 address.sin_port = htons(port);
43 address.sin_addr.s_addr = htonl(INADDR_ANY);
44
45 // Create the socket signature.
46 CFSocketSignature signature;
47 signature.protocolFamily = PF_INET;
48 signature.socketType = SOCK_STREAM;
49 signature.protocol = IPPROTO_TCP;
50 signature.address = (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)];
51
52 do {
53 socket_ = CFSocketCreateWithSocketSignature(kCFAllocatorDefault,
54 &signature, // Socket signature.
55 kCFSocketAcceptCallBack, // Callback types.
56 &NetworkCallbackController::SocketAcceptCallback, // Callout function pointer.
57 &context); // Context to pass to callout.
58 if (!socket_) {
59 [connection_ errorEncountered:@"Could not open socket."];
60 sleep(1);
61 }
62 } while (!socket_);
63
64 // Allow old, yet-to-be recycled sockets to be reused.
65 BOOL yes = YES;
66 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
67 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(BOOL));
68
69 // Schedule the socket on the run loop.
70 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 0);
71 CFRunLoopAddSource(runLoop_, source, kCFRunLoopCommonModes);
72 CFRelease(source);
73 }
74
75 void NetworkCallbackController::CloseConnection()
76 {
77 if (socket_) {
78 NSLog(@"invalidating socket %d", close(CFSocketGetNative(socket_)));
79 CFSocketInvalidate(socket_);
80 NSLog(@"socket is valid %d", CFSocketIsValid(socket_));
81 CFRelease(socket_);
82 socket_ = NULL;
83 }
84 UnscheduleReadStream();
85 UnscheduleWriteStream();
86 }
87
88 // Static Methods //////////////////////////////////////////////////////////////
89
90 void NetworkCallbackController::SocketAcceptCallback(CFSocketRef socket,
91 CFSocketCallBackType callbackType,
92 CFDataRef address,
93 const void* data,
94 void* self)
95 {
96 assert(callbackType == kCFSocketAcceptCallBack);
97 static_cast<NetworkCallbackController*>(self)->OnSocketAccept(socket, address, data);
98 }
99
100 void NetworkCallbackController::ReadStreamCallback(CFReadStreamRef stream,
101 CFStreamEventType eventType,
102 void* self)
103 {
104 static_cast<NetworkCallbackController*>(self)->OnReadStreamEvent(stream, eventType);
105 }
106
107 void NetworkCallbackController::WriteStreamCallback(CFWriteStreamRef stream,
108 CFStreamEventType eventType,
109 void* self)
110 {
111 static_cast<NetworkCallbackController*>(self)->OnWriteStreamEvent(stream, eventType);
112 }
113
114
115 // Private Instance Methods ////////////////////////////////////////////////////
116
117 void NetworkCallbackController::OnSocketAccept(CFSocketRef socket,
118 CFDataRef address,
119 const void* data)
120 {
121 CFReadStreamRef readStream;
122 CFWriteStreamRef writeStream;
123
124 // Create the streams on the socket.
125 CFStreamCreatePairWithSocket(kCFAllocatorDefault,
126 *(CFSocketNativeHandle*)data, // Socket handle.
127 &readStream, // Read stream in-pointer.
128 &writeStream); // Write stream in-pointer.
129
130 // Create struct to register callbacks for the stream.
131 CFStreamClientContext context = { 0 };
132 context.info = this;
133
134 // Set the client of the read stream.
135 CFOptionFlags readFlags = kCFStreamEventOpenCompleted |
136 kCFStreamEventHasBytesAvailable |
137 kCFStreamEventErrorOccurred |
138 kCFStreamEventEndEncountered;
139 if (CFReadStreamSetClient(readStream, readFlags, &NetworkCallbackController::ReadStreamCallback, &context))
140 // Schedule in run loop to do asynchronous communication with the engine.
141 CFReadStreamScheduleWithRunLoop(readStream, runLoop_, kCFRunLoopCommonModes);
142 else
143 return;
144
145 // Open the stream now that it's scheduled on the run loop.
146 if (!CFReadStreamOpen(readStream)) {
147 ReportError(CFReadStreamCopyError(readStream));
148 return;
149 }
150
151 // Set the client of the write stream.
152 CFOptionFlags writeFlags = kCFStreamEventOpenCompleted |
153 kCFStreamEventCanAcceptBytes |
154 kCFStreamEventErrorOccurred |
155 kCFStreamEventEndEncountered;
156 if (CFWriteStreamSetClient(writeStream, writeFlags, &NetworkCallbackController::WriteStreamCallback, &context))
157 // Schedule it in the run loop to receive error information.
158 CFWriteStreamScheduleWithRunLoop(writeStream, runLoop_, kCFRunLoopCommonModes);
159 else
160 return;
161
162 // Open the write stream.
163 if (!CFWriteStreamOpen(writeStream)) {
164 ReportError(CFWriteStreamCopyError(writeStream));
165 return;
166 }
167
168 connection_.readStream = readStream;
169 connection_.writeStream = writeStream;
170 [connection_ socketDidAccept];
171 }
172
173 void NetworkCallbackController::OnReadStreamEvent(CFReadStreamRef stream,
174 CFStreamEventType eventType)
175 {
176 switch (eventType)
177 {
178 case kCFStreamEventHasBytesAvailable:
179 if (connection_.readStream)
180 [connection_ readStreamHasData];
181 break;
182
183 case kCFStreamEventErrorOccurred:
184 NSLog(@"%s error", __PRETTY_FUNCTION__);
185 ReportError(CFReadStreamCopyError(stream));
186 UnscheduleReadStream();
187 break;
188
189 case kCFStreamEventEndEncountered:
190 NSLog(@"%s end", __PRETTY_FUNCTION__);
191 UnscheduleReadStream();
192 [connection_ socketDisconnected];
193 break;
194 };
195 }
196
197 void NetworkCallbackController::OnWriteStreamEvent(CFWriteStreamRef stream,
198 CFStreamEventType eventType)
199 {
200 switch (eventType)
201 {
202 case kCFStreamEventCanAcceptBytes:
203 [connection_ sendQueuedWrites];
204 break;
205
206 case kCFStreamEventErrorOccurred:
207 ReportError(CFWriteStreamCopyError(stream));
208 UnscheduleWriteStream();
209 break;
210
211 case kCFStreamEventEndEncountered:
212 UnscheduleReadStream();
213 [connection_ socketDisconnected];
214 break;
215 }
216 }
217
218 void NetworkCallbackController::UnscheduleReadStream()
219 {
220 CFReadStreamUnscheduleFromRunLoop(connection_.readStream, runLoop_, kCFRunLoopCommonModes);
221 CFReadStreamClose(connection_.readStream);
222 CFRelease(connection_.readStream);
223 connection_.readStream = NULL;
224 }
225
226 void NetworkCallbackController::UnscheduleWriteStream()
227 {
228 CFWriteStreamUnscheduleFromRunLoop(connection_.writeStream, runLoop_, kCFRunLoopCommonModes);
229 CFWriteStreamClose(connection_.writeStream);
230 CFRelease(connection_.writeStream);
231 connection_.writeStream = NULL;
232 }
233
234 void NetworkCallbackController::ReportError(CFErrorRef error)
235 {
236 [connection_ errorEncountered:[(NSError*)error description]];
237 CFRelease(error);
238 }