3 * Copyright (c) 2002 - 2007, 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 "SocketWrapper.h"
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
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";
31 @interface SocketWrapper (Private
)
33 - (void)connect
:(id)obj
;
34 - (void)postNotification
:(NSString
*)name withObject
:(id)obj
;
35 - (void)postNotification
:(NSString
*)name withObject
:(id)obj withDict
:(NSMutableDictionary
*)dict
;
39 @implementation SocketWrapper
42 * Initializes the socket wrapper with a host and port
44 - (id)initWithPort
:(int)aPort
46 if (self = [super init
])
50 // the delegate notifications work funky because of threads. we register ourselves as the
51 // observer and then pass up the messages that are actually from this object (as we can't only observe self due to threads)
52 // to our delegate, and not to all delegates
53 [[NSNotificationCenter defaultCenter
] addObserver
:self selector
:@selector(sendMessageToDelegate
:) name
:nil object
:nil];
59 * Close our socket and clean up anything else
63 [[NSNotificationCenter defaultCenter
] removeObserver
:self];
70 * Returns the delegate
78 * Sets the delegate but does *not* retain it
80 - (void)setDelegate
:(id)aDelegate
86 * Returns the name of the host to whom we are currently connected.
88 - (NSString
*)remoteHost
90 struct sockaddr_in addr
;
93 if (getpeername(sock
, (struct sockaddr
*)&addr
, &addrLength
) < 0)
95 [self postNotification
:NsockError withObject
:[NSError errorWithDomain
:@
"Could not get remote hostname." code
:-1 userInfo
:nil]];
98 char *name
= inet_ntoa(addr.sin_addr
);
100 return [NSString stringWithUTF8String
:name
];
104 * This is the notification listener for all types of notifications. If the notifications are from a SocketWrapper
105 * class, it checks that the value of _delegate in the NSNotification's userInfo matches that of this object. If it does,
106 * then the notification was sent from the same object in another thread and it passes the message along to the object's
107 * delegate. Complicated enough?
109 - (void)sendMessageToDelegate
:(NSNotification
*)notif
111 // this isn't us, so there's no point in continuing
112 if ([[notif userInfo
] objectForKey
:sockNotificationDebuggerConnection
] != delegate
)
117 NSString
*name
= [notif name
];
119 if (name
== NsockDidAccept
)
121 [delegate socketDidAccept
];
123 else if (name
== NsockDataReceived
)
125 [delegate dataReceived
:[notif object
] deliverTo
:NSSelectorFromString([[notif userInfo
] objectForKey
:sockNotificationReceiver
])];
127 else if (name
== NsockDataSent
)
129 [delegate dataSent
:[notif object
]];
131 else if (name
== NsockError
)
133 [delegate errorEncountered
:[NSError errorWithDomain
:[notif object
] code
:-1 userInfo
:nil]];
138 * Connects to a socket on the port specified during init. This will dispatch another thread to do the
139 * actual waiting. Delegate notifications are posted along the way to let the client know what is going on.
143 [NSThread detachNewThreadSelector
:@selector(connect
:) toTarget
:self withObject
:nil];
147 * This does the actual dirty work (in a separate thread) of connecting to a socket
149 - (void)connect
:(id)obj
151 NSAutoreleasePool
*pool
= [[NSAutoreleasePool alloc
] init
];
153 // create an INET socket that we'll be listen()ing on
154 int socketOpen
= socket(PF_INET
, SOCK_STREAM
, 0);
156 // create our address given the port
157 struct sockaddr_in address
;
158 address.sin_family
= AF_INET
;
159 address.sin_port
= htons(port
);
160 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
161 memset(address.sin_zero
, '\0', sizeof(address.sin_zero
));
163 // allow an already-opened socket to be reused
165 setsockopt(socketOpen
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(int));
167 // bind the socket... and don't give up until we've tried for a while
169 while (bind(socketOpen
, (struct sockaddr
*)&address
, sizeof(address
)) < 0)
174 [self postNotification
:NsockError withObject
:@
"Could not bind to socket"];
177 NSLog(@
"couldn't bind to the socket... trying again in 5");
182 // now we just have to keep our ears open
183 if (listen(socketOpen
, 0) == -1)
185 [self postNotification
:NsockError withObject
:@
"Could not use bound socket for listening"];
188 // accept a connection
189 struct sockaddr_in remoteAddress
;
190 socklen_t remoteAddressLen
= sizeof(remoteAddress
);
191 sock
= accept(socketOpen
, (struct sockaddr
*)&remoteAddress
, &remoteAddressLen
);
195 [self postNotification
:NsockError withObject
:@
"Client failed to accept remote socket"];
199 // we're done listening now that we have a connection
202 [self postNotification
:NsockDidAccept withObject
:nil];
208 * Reads from the socket and returns the result as a NSString (because it's always going to be XML). Be aware
209 * that the underlying socket recv() call will *wait* for the server to send a message, so be sure that this
210 * is used either in a threaded environment so the interface does not hang, or when you *know* the server
211 * will return something (which we almost always do).
213 * The paramater is an optional selector which the delegate method dataReceived:deliverTo: should forward to
215 - (void)receive
:(SEL)selector
220 // do our initial recv() call to get (hopefully) all the data and the lengh of the packet
221 int recvd
= recv(sock
, &buffer
, sizeof(buffer
), 0);
223 // take the received data and put it into an NSData
224 NSMutableData
*data
= [NSMutableData data
];
226 // strip the length from the packet, and clear the null byte then add it to the NSData
227 char packetLength
[8];
228 memset(packetLength
, '\0', sizeof(packetLength
));
230 while (buffer
[i
] != '\0')
232 packetLength
[i
] = buffer
[i
];
236 // we also want the null byte, so move us up 1
239 // the total length of the full transmission
240 int length
= atoi(packetLength
);
242 // move the packet part of the received data into it's own char[]
243 char packet
[sizeof(buffer
)];
244 memset(packet
, '\0', sizeof(packet
));
245 memmove(packet
, &buffer
[i
], recvd
- i
);
247 // convert bytes to NSData
248 [data appendBytes
:packet length
:recvd
- i
];
250 // check if we have a partial packet
251 if (length
+ i
> sizeof(buffer
))
253 while (recvd
< length
)
255 int latest
= recv(sock
, &buffer
, sizeof(buffer
), 0);
258 [self postNotification
:NsockError withObject
:@
"Socket closed or could not be read"];
261 [data appendBytes
:buffer length
:latest
];
266 //NSLog(@"data = %@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
270 [self postNotification
:NsockDataReceived
272 withDict
:[NSMutableDictionary dictionaryWithObject
:NSStringFromSelector(selector
) forKey
:sockNotificationReceiver
]];
276 [self postNotification
:NsockDataReceived withObject
:data
];
281 * Sends a given NSString over the socket
283 - (void)send
:(NSString
*)data
285 data
= [NSString stringWithFormat
:@
"%@\0", data
];
286 int sent
= send(sock
, [data UTF8String
], [data length
], 0);
289 [self postNotification
:NsockError withObject
:@
"Failed to write data to socket"];
292 if (sent
< [data length
])
294 // TODO - do we really need to worry about partial sends with the lenght of our commands?
295 NSLog(@
"FAIL:only partial packet was sent; sent %d bytes", sent
);
298 [self postNotification
:NsockDataSent withObject
:[data substringToIndex
:sent
]];
302 * Helper method to simply post a notification to the default notification center with a given name and object
304 - (void)postNotification
:(NSString
*)name withObject
:(id)obj
306 [self postNotification
:name withObject
:obj withDict
:[NSMutableDictionary dictionary
]];
310 * Another helper method to aid in the posting of notifications. This one should be used if you have additional
311 * things for the userInfo. This automatically adds the sockNotificationDebuggerConnection key.
313 - (void)postNotification
:(NSString
*)name withObject
:(id)obj withDict
:(NSMutableDictionary
*)dict
315 [dict setValue
:delegate forKey
:sockNotificationDebuggerConnection
];
316 [[NSNotificationCenter defaultCenter
] postNotificationName
:name object
:obj userInfo
:dict
];