Turning off GC and adding back manual memory management
[macgdbp.git] / Source / SocketWrapper.m
1 /*
2 * MacGDBp
3 * Copyright (c) 2007 - 2008, 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 @interface SocketWrapper (Private)
25
26 - (void)error:(NSString *)msg;
27
28 @end
29
30 @implementation SocketWrapper
31
32 /**
33 * Initializes the socket wrapper with a host and port
34 */
35 - (id)initWithConnection:(DebuggerConnection *)cnx
36 {
37 if (self = [super init])
38 {
39 connection = [cnx retain];
40 port = [connection port];
41 }
42 return self;
43 }
44
45 /**
46 * Dealloc
47 */
48 - (void)dealloc
49 {
50 [connection release];
51 [super dealloc];
52 }
53
54 /**
55 * Close our socket and clean up anything else
56 */
57 - (void)close
58 {
59 close(sock);
60 }
61
62 /**
63 * Returns the delegate
64 */
65 - (id)delegate
66 {
67 return delegate;
68 }
69
70 /**
71 * Sets the delegate but does *not* retain it
72 */
73 - (void)setDelegate:(id)aDelegate
74 {
75 delegate = aDelegate;
76 }
77
78 /**
79 * Returns the name of the host to whom we are currently connected.
80 */
81 - (NSString *)remoteHost
82 {
83 struct sockaddr_in addr;
84 socklen_t addrLength;
85
86 if (getpeername(sock, (struct sockaddr *)&addr, &addrLength) < 0)
87 {
88 [self error:@"Could not get remote hostname."];
89 }
90
91 char *name = inet_ntoa(addr.sin_addr);
92
93 return [NSString stringWithUTF8String:name];
94 }
95
96 /**
97 * Connects to a socket on the port specified during init. This will dispatch another thread to do the
98 * actual waiting. Delegate notifications are posted along the way to let the client know what is going on.
99 */
100 - (void)connect
101 {
102 [NSThread detachNewThreadSelector:@selector(connect:) toTarget:self withObject:nil];
103 }
104
105 /**
106 * This does the actual dirty work (in a separate thread) of connecting to a socket
107 */
108 - (void)connect:(id)obj
109 {
110 // create an INET socket that we'll be listen()ing on
111 int socketOpen = socket(PF_INET, SOCK_STREAM, 0);
112
113 // create our address given the port
114 struct sockaddr_in address;
115 address.sin_family = AF_INET;
116 address.sin_port = htons(port);
117 address.sin_addr.s_addr = htonl(INADDR_ANY);
118 memset(address.sin_zero, '\0', sizeof(address.sin_zero));
119
120 // allow an already-opened socket to be reused
121 int yes = 1;
122 setsockopt(socketOpen, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
123
124 // bind the socket... and don't give up until we've tried for a while
125 int tries = 0;
126 while (bind(socketOpen, (struct sockaddr *)&address, sizeof(address)) < 0)
127 {
128 if (tries >= 5)
129 {
130 close(socketOpen);
131 [self error:@"Could not bind to socket"];
132 return;
133 }
134 NSLog(@"couldn't bind to the socket... trying again in 5");
135 sleep(5);
136 tries++;
137 }
138
139 // now we just have to keep our ears open
140 if (listen(socketOpen, 0) == -1)
141 {
142 [self error:@"Could not use bound socket for listening"];
143 }
144
145 // accept a connection
146 struct sockaddr_in remoteAddress;
147 socklen_t remoteAddressLen = sizeof(remoteAddress);
148 sock = accept(socketOpen, (struct sockaddr *)&remoteAddress, &remoteAddressLen);
149 if (sock < 0)
150 {
151 close(socketOpen);
152 [self error:@"Client failed to accept remote socket"];
153 return;
154 }
155
156 // we're done listening now that we have a connection
157 close(socketOpen);
158
159 [connection performSelectorOnMainThread:@selector(socketDidAccept:) withObject:nil waitUntilDone:NO];
160 }
161
162 /**
163 * Reads from the socket and returns the result as a NSString (because it's always going to be XML). Be aware
164 * that the underlying socket recv() call will *wait* for the server to send a message, so be sure that this
165 * is used either in a threaded environment so the interface does not hang, or when you *know* the server
166 * will return something (which we almost always do). Returns the data that was received from the socket.
167 */
168 - (NSData *)receive
169 {
170 // create a buffer
171 char buffer[1024];
172
173 // do our initial recv() call to get (hopefully) all the data and the lengh of the packet
174 int recvd = recv(sock, &buffer, sizeof(buffer), 0);
175
176 // take the received data and put it into an NSData
177 NSMutableData *data = [NSMutableData data];
178
179 // strip the length from the packet, and clear the null byte then add it to the NSData
180 char packetLength[8];
181 memset(packetLength, '\0', sizeof(packetLength));
182 int i = 0;
183 while (buffer[i] != '\0')
184 {
185 packetLength[i] = buffer[i];
186 i++;
187 }
188
189 // we also want the null byte, so move us up 1
190 i++;
191
192 // the total length of the full transmission
193 int length = atoi(packetLength);
194
195 // move the packet part of the received data into it's own char[]
196 char packet[sizeof(buffer)];
197 memset(packet, '\0', sizeof(packet));
198 memmove(packet, &buffer[i], recvd - i);
199
200 // convert bytes to NSData
201 [data appendBytes:packet length:recvd - i];
202
203 // check if we have a partial packet
204 if (length + i > sizeof(buffer))
205 {
206 while (recvd < length)
207 {
208 int latest = recv(sock, &buffer, sizeof(buffer), 0);
209 if (latest < 1)
210 {
211 [self error:@"Socket closed or could not be read"];
212 return nil;
213 }
214 [data appendBytes:buffer length:latest];
215 recvd += latest;
216 }
217 }
218
219 return data;
220 }
221
222 /**
223 * Sends a given NSString over the socket. Returns YES on complete submission.
224 */
225 - (BOOL)send:(NSString *)data
226 {
227 data = [NSString stringWithFormat:@"%@\0", data];
228 int sent = send(sock, [data UTF8String], [data length], 0);
229 if (sent < 0)
230 {
231 [self error:@"Failed to write data to socket"];
232 return NO;
233 }
234 if (sent < [data length])
235 {
236 // TODO - do we really need to worry about partial sends with the lenght of our commands?
237 NSLog(@"FAIL: only partial packet was sent; sent %d bytes", sent);
238 return NO;
239 }
240
241 return YES;
242 }
243
244 /**
245 * Helper method that just calls -[DebuggerWindowController setError:] on the main thread
246 */
247 - (void)error:(NSString *)msg
248 {
249 [delegate performSelectorOnMainThread:@selector(errorEncountered:) withObject:msg waitUntilDone:NO];
250 }
251
252 @end