Synthesize new properties for class cross-referencing and SocketWrapper now init...
[macgdbp.git] / Source / SocketWrapper.m
1 /*
2 * MacGDBp
3 * Copyright (c) 2002 - 2007, 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 "SocketWrapper.h"
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <unistd.h>
23
24 NSString *sockNotificationDebuggerConnection = @"DebuggerConnection";
25 NSString *sockNotificationReceiver = @"SEL-del-SocketWrapper_dataReceived";
26 NSString *NsockError = @"SocketWrapper_Error";
27 NSString *NsockDidAccept = @"SocketWrapper_DidAccept";
28 NSString *NsockDataReceived = @"SocketWrapper_DataReceived";
29 NSString *NsockDataSent = @"SocketWrapper_DataSent";
30
31 @interface SocketWrapper (Private)
32
33 - (void)connect:(id)obj;
34 - (void)postNotification:(NSString *)name withObject:(id)obj;
35 - (void)postNotification:(NSString *)name withObject:(id)obj withDict:(NSMutableDictionary *)dict;
36
37 @end
38
39 @implementation SocketWrapper
40
41 /**
42 * Initializes the socket wrapper with a host and port
43 */
44 - (id)initWithConnection:(DebuggerConnection *)cnx
45 {
46 if (self = [super init])
47 {
48 connection = cnx;
49 port = [connection port];
50
51 // the delegate notifications work funky because of threads. we register ourselves as the
52 // observer and then pass up the messages that are actually from this object (as we can't only observe self due to threads)
53 // to our delegate, and not to all delegates
54 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendMessageToDelegate:) name:nil object:nil];
55 }
56 return self;
57 }
58
59 /**
60 * Close our socket and clean up anything else
61 */
62 - (void)close
63 {
64 [[NSNotificationCenter defaultCenter] removeObserver:self];
65 close(sock);
66 }
67
68 /**
69 * Returns the delegate
70 */
71 - (id)delegate
72 {
73 return delegate;
74 }
75
76 /**
77 * Sets the delegate but does *not* retain it
78 */
79 - (void)setDelegate:(id)aDelegate
80 {
81 delegate = aDelegate;
82 }
83
84 /**
85 * Returns the name of the host to whom we are currently connected.
86 */
87 - (NSString *)remoteHost
88 {
89 struct sockaddr_in addr;
90 socklen_t addrLength;
91
92 if (getpeername(sock, (struct sockaddr *)&addr, &addrLength) < 0)
93 {
94 [self postNotification:NsockError withObject:[NSError errorWithDomain:@"Could not get remote hostname." code:-1 userInfo:nil]];
95 }
96
97 char *name = inet_ntoa(addr.sin_addr);
98
99 return [NSString stringWithUTF8String:name];
100 }
101
102 /**
103 * This is the notification listener for all types of notifications. If the notifications are from a SocketWrapper
104 * class, it checks that the value of _delegate in the NSNotification's userInfo matches that of this object. If it does,
105 * then the notification was sent from the same object in another thread and it passes the message along to the object's
106 * delegate. Complicated enough?
107 */
108 - (void)sendMessageToDelegate:(NSNotification *)notif
109 {
110 // this isn't us, so there's no point in continuing
111 if ([[notif userInfo] objectForKey:sockNotificationDebuggerConnection] != delegate)
112 {
113 return;
114 }
115
116 NSString *name = [notif name];
117
118 if (name == NsockDidAccept)
119 {
120 [delegate socketDidAccept];
121 }
122 else if (name == NsockDataReceived)
123 {
124 [delegate dataReceived:[notif object] deliverTo:NSSelectorFromString([[notif userInfo] objectForKey:sockNotificationReceiver])];
125 }
126 else if (name == NsockDataSent)
127 {
128 [delegate dataSent:[notif object]];
129 }
130 else if (name == NsockError)
131 {
132 [delegate errorEncountered:[NSError errorWithDomain:[notif object] code:-1 userInfo:nil]];
133 }
134 }
135
136 /**
137 * Connects to a socket on the port specified during init. This will dispatch another thread to do the
138 * actual waiting. Delegate notifications are posted along the way to let the client know what is going on.
139 */
140 - (void)connect
141 {
142 [NSThread detachNewThreadSelector:@selector(connect:) toTarget:self withObject:nil];
143 }
144
145 /**
146 * This does the actual dirty work (in a separate thread) of connecting to a socket
147 */
148 - (void)connect:(id)obj
149 {
150 // create an INET socket that we'll be listen()ing on
151 int socketOpen = socket(PF_INET, SOCK_STREAM, 0);
152
153 // create our address given the port
154 struct sockaddr_in address;
155 address.sin_family = AF_INET;
156 address.sin_port = htons(port);
157 address.sin_addr.s_addr = htonl(INADDR_ANY);
158 memset(address.sin_zero, '\0', sizeof(address.sin_zero));
159
160 // allow an already-opened socket to be reused
161 int yes = 1;
162 setsockopt(socketOpen, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
163
164 // bind the socket... and don't give up until we've tried for a while
165 int tries = 0;
166 while (bind(socketOpen, (struct sockaddr *)&address, sizeof(address)) < 0)
167 {
168 if (tries >= 5)
169 {
170 close(socketOpen);
171 [self postNotification:NsockError withObject:@"Could not bind to socket"];
172 return;
173 }
174 NSLog(@"couldn't bind to the socket... trying again in 5");
175 sleep(5);
176 tries++;
177 }
178
179 // now we just have to keep our ears open
180 if (listen(socketOpen, 0) == -1)
181 {
182 [self postNotification:NsockError withObject:@"Could not use bound socket for listening"];
183 }
184
185 // accept a connection
186 struct sockaddr_in remoteAddress;
187 socklen_t remoteAddressLen = sizeof(remoteAddress);
188 sock = accept(socketOpen, (struct sockaddr *)&remoteAddress, &remoteAddressLen);
189 if (sock < 0)
190 {
191 close(socketOpen);
192 [self postNotification:NsockError withObject:@"Client failed to accept remote socket"];
193 return;
194 }
195
196 // we're done listening now that we have a connection
197 close(socketOpen);
198
199 [self postNotification:NsockDidAccept withObject:nil];
200 }
201
202 /**
203 * Reads from the socket and returns the result as a NSString (because it's always going to be XML). Be aware
204 * that the underlying socket recv() call will *wait* for the server to send a message, so be sure that this
205 * is used either in a threaded environment so the interface does not hang, or when you *know* the server
206 * will return something (which we almost always do).
207 *
208 * The paramater is an optional selector which the delegate method dataReceived:deliverTo: should forward to
209 */
210 - (void)receive:(SEL)selector
211 {
212 // create a buffer
213 char buffer[1024];
214
215 // do our initial recv() call to get (hopefully) all the data and the lengh of the packet
216 int recvd = recv(sock, &buffer, sizeof(buffer), 0);
217
218 // take the received data and put it into an NSData
219 NSMutableData *data = [NSMutableData data];
220
221 // strip the length from the packet, and clear the null byte then add it to the NSData
222 char packetLength[8];
223 memset(packetLength, '\0', sizeof(packetLength));
224 int i = 0;
225 while (buffer[i] != '\0')
226 {
227 packetLength[i] = buffer[i];
228 i++;
229 }
230
231 // we also want the null byte, so move us up 1
232 i++;
233
234 // the total length of the full transmission
235 int length = atoi(packetLength);
236
237 // move the packet part of the received data into it's own char[]
238 char packet[sizeof(buffer)];
239 memset(packet, '\0', sizeof(packet));
240 memmove(packet, &buffer[i], recvd - i);
241
242 // convert bytes to NSData
243 [data appendBytes:packet length:recvd - i];
244
245 // check if we have a partial packet
246 if (length + i > sizeof(buffer))
247 {
248 while (recvd < length)
249 {
250 int latest = recv(sock, &buffer, sizeof(buffer), 0);
251 if (latest < 1)
252 {
253 [self postNotification:NsockError withObject:@"Socket closed or could not be read"];
254 return;
255 }
256 [data appendBytes:buffer length:latest];
257 recvd += latest;
258 }
259 }
260
261 //NSLog(@"data = %@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
262
263 if (selector != nil)
264 {
265 [self postNotification:NsockDataReceived
266 withObject:data
267 withDict:[NSMutableDictionary dictionaryWithObject:NSStringFromSelector(selector) forKey:sockNotificationReceiver]];
268 }
269 else
270 {
271 [self postNotification:NsockDataReceived withObject:data];
272 }
273 }
274
275 /**
276 * Sends a given NSString over the socket
277 */
278 - (void)send:(NSString *)data
279 {
280 data = [NSString stringWithFormat:@"%@\0", data];
281 int sent = send(sock, [data UTF8String], [data length], 0);
282 if (sent < 0)
283 {
284 [self postNotification:NsockError withObject:@"Failed to write data to socket"];
285 return;
286 }
287 if (sent < [data length])
288 {
289 // TODO - do we really need to worry about partial sends with the lenght of our commands?
290 NSLog(@"FAIL: only partial packet was sent; sent %d bytes", sent);
291 }
292
293 [self postNotification:NsockDataSent withObject:[data substringToIndex:sent]];
294 }
295
296 /**
297 * Helper method to simply post a notification to the default notification center with a given name and object
298 */
299 - (void)postNotification:(NSString *)name withObject:(id)obj
300 {
301 [self postNotification:name withObject:obj withDict:[NSMutableDictionary dictionary]];
302 }
303
304 /**
305 * Another helper method to aid in the posting of notifications. This one should be used if you have additional
306 * things for the userInfo. This automatically adds the sockNotificationDebuggerConnection key.
307 */
308 - (void)postNotification:(NSString *)name withObject:(id)obj withDict:(NSMutableDictionary *)dict
309 {
310 [dict setValue:delegate forKey:sockNotificationDebuggerConnection];
311 [[NSNotificationCenter defaultCenter] postNotificationName:name object:obj userInfo:dict];
312 }
313
314 @end