PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/external_dependencies/cocoalumberjack/Xcode/WebServerIPhone/Vendor/CocoaAsyncSocket/GCDAsyncSocket.h

https://bitbucket.org/cel/growl
C Header | 963 lines | 197 code | 92 blank | 674 comment | 0 complexity | 208f91fcfc01089ea6118bd953b04a93 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. //
  2. // GCDAsyncSocket.h
  3. //
  4. // This class is in the public domain.
  5. // Originally created by Robbie Hanson in Q3 2010.
  6. // Updated and maintained by Deusty LLC and the Mac development community.
  7. //
  8. // http://code.google.com/p/cocoaasyncsocket/
  9. //
  10. #import <Foundation/Foundation.h>
  11. #import <Security/Security.h>
  12. #import <dispatch/dispatch.h>
  13. @class GCDAsyncReadPacket;
  14. @class GCDAsyncWritePacket;
  15. extern NSString *const GCDAsyncSocketException;
  16. extern NSString *const GCDAsyncSocketErrorDomain;
  17. #if !TARGET_OS_IPHONE
  18. extern NSString *const GCDAsyncSocketSSLCipherSuites;
  19. extern NSString *const GCDAsyncSocketSSLDiffieHellmanParameters;
  20. #endif
  21. enum GCDAsyncSocketError
  22. {
  23. GCDAsyncSocketNoError = 0, // Never used
  24. GCDAsyncSocketBadConfigError, // Invalid configuration
  25. GCDAsyncSocketBadParamError, // Invalid parameter was passed
  26. GCDAsyncSocketConnectTimeoutError, // A connect operation timed out
  27. GCDAsyncSocketReadTimeoutError, // A read operation timed out
  28. GCDAsyncSocketWriteTimeoutError, // A write operation timed out
  29. GCDAsyncSocketReadMaxedOutError, // Reached set maxLength without completing
  30. GCDAsyncSocketClosedError, // The remote peer closed the connection
  31. GCDAsyncSocketOtherError, // Description provided in userInfo
  32. };
  33. typedef enum GCDAsyncSocketError GCDAsyncSocketError;
  34. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  35. #pragma mark -
  36. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  37. @interface GCDAsyncSocket : NSObject
  38. {
  39. uint32_t flags;
  40. uint16_t config;
  41. __weak id delegate;
  42. dispatch_queue_t delegateQueue;
  43. int socket4FD;
  44. int socket6FD;
  45. int connectIndex;
  46. NSData * connectInterface4;
  47. NSData * connectInterface6;
  48. dispatch_queue_t socketQueue;
  49. dispatch_source_t accept4Source;
  50. dispatch_source_t accept6Source;
  51. dispatch_source_t connectTimer;
  52. dispatch_source_t readSource;
  53. dispatch_source_t writeSource;
  54. dispatch_source_t readTimer;
  55. dispatch_source_t writeTimer;
  56. NSMutableArray *readQueue;
  57. NSMutableArray *writeQueue;
  58. GCDAsyncReadPacket *currentRead;
  59. GCDAsyncWritePacket *currentWrite;
  60. unsigned long socketFDBytesAvailable;
  61. NSMutableData *partialReadBuffer;
  62. #if TARGET_OS_IPHONE
  63. CFStreamClientContext streamContext;
  64. CFReadStreamRef readStream;
  65. CFWriteStreamRef writeStream;
  66. #else
  67. SSLContextRef sslContext;
  68. NSMutableData *sslReadBuffer;
  69. size_t sslWriteCachedLength;
  70. #endif
  71. id userData;
  72. }
  73. /**
  74. * GCDAsyncSocket uses the standard delegate paradigm,
  75. * but executes all delegate callbacks on a given delegate dispatch queue.
  76. * This allows for maximum concurrency, while at the same time providing easy thread safety.
  77. *
  78. * You MUST set a delegate AND delegate dispatch queue before attempting to
  79. * use the socket, or you will get an error.
  80. *
  81. * The socket queue is optional.
  82. * If you pass NULL, GCDAsyncSocket will automatically create it's own socket queue.
  83. * If you choose to provide a socket queue, the socket queue must not be a concurrent queue.
  84. *
  85. * The delegate queue and socket queue can optionally be the same.
  86. **/
  87. - (id)init;
  88. - (id)initWithSocketQueue:(dispatch_queue_t)sq;
  89. - (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq;
  90. - (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq;
  91. #pragma mark Configuration
  92. - (id)delegate;
  93. - (void)setDelegate:(id)delegate;
  94. - (void)synchronouslySetDelegate:(id)delegate;
  95. - (dispatch_queue_t)delegateQueue;
  96. - (void)setDelegateQueue:(dispatch_queue_t)delegateQueue;
  97. - (void)synchronouslySetDelegateQueue:(dispatch_queue_t)delegateQueue;
  98. - (void)getDelegate:(id *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr;
  99. - (void)setDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
  100. - (void)synchronouslySetDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
  101. /**
  102. * Traditionally sockets are not closed until the conversation is over.
  103. * However, it is technically possible for the remote enpoint to close its write stream.
  104. * Our socket would then be notified that there is no more data to be read,
  105. * but our socket would still be writeable and the remote endpoint could continue to receive our data.
  106. *
  107. * The argument for this confusing functionality stems from the idea that a client could shut down its
  108. * write stream after sending a request to the server, thus notifying the server there are to be no further requests.
  109. * In practice, however, this technique did little to help server developers.
  110. *
  111. * To make matters worse, from a TCP perspective there is no way to tell the difference from a read stream close
  112. * and a full socket close. They both result in the TCP stack receiving a FIN packet. The only way to tell
  113. * is by continuing to write to the socket. If it was only a read stream close, then writes will continue to work.
  114. * Otherwise an error will be occur shortly (when the remote end sends us a RST packet).
  115. *
  116. * In addition to the technical challenges and confusion, many high level socket/stream API's provide
  117. * no support for dealing with the problem. If the read stream is closed, the API immediately declares the
  118. * socket to be closed, and shuts down the write stream as well. In fact, this is what Apple's CFStream API does.
  119. * It might sound like poor design at first, but in fact it simplifies development.
  120. *
  121. * The vast majority of the time if the read stream is closed it's because the remote endpoint closed its socket.
  122. * Thus it actually makes sense to close the socket at this point.
  123. * And in fact this is what most networking developers want and expect to happen.
  124. * However, if you are writing a server that interacts with a plethora of clients,
  125. * you might encounter a client that uses the discouraged technique of shutting down its write stream.
  126. * If this is the case, you can set this property to NO,
  127. * and make use of the socketDidCloseReadStream delegate method.
  128. *
  129. * The default value is YES.
  130. **/
  131. - (BOOL)autoDisconnectOnClosedReadStream;
  132. - (void)setAutoDisconnectOnClosedReadStream:(BOOL)flag;
  133. /**
  134. * By default, both IPv4 and IPv6 are enabled.
  135. *
  136. * For accepting incoming connections, this means GCDAsyncSocket automatically supports both protocols,
  137. * and can simulataneously accept incoming connections on either protocol.
  138. *
  139. * For outgoing connections, this means GCDAsyncSocket can connect to remote hosts running either protocol.
  140. * If a DNS lookup returns only IPv4 results, GCDAsyncSocket will automatically use IPv4.
  141. * If a DNS lookup returns only IPv6 results, GCDAsyncSocket will automatically use IPv6.
  142. * If a DNS lookup returns both IPv4 and IPv6 results, the preferred protocol will be chosen.
  143. * By default, the preferred protocol is IPv4, but may be configured as desired.
  144. **/
  145. - (BOOL)isIPv4Enabled;
  146. - (void)setIPv4Enabled:(BOOL)flag;
  147. - (BOOL)isIPv6Enabled;
  148. - (void)setIPv6Enabled:(BOOL)flag;
  149. - (BOOL)isIPv4PreferredOverIPv6;
  150. - (void)setPreferIPv4OverIPv6:(BOOL)flag;
  151. /**
  152. * User data allows you to associate arbitrary information with the socket.
  153. * This data is not used internally by socket in any way.
  154. **/
  155. - (id)userData;
  156. - (void)setUserData:(id)arbitraryUserData;
  157. #pragma mark Accepting
  158. /**
  159. * Tells the socket to begin listening and accepting connections on the given port.
  160. * When a connection is accepted, a new instance of GCDAsyncSocket will be spawned to handle it,
  161. * and the socket:didAcceptNewSocket: delegate method will be invoked.
  162. *
  163. * The socket will listen on all available interfaces (e.g. wifi, ethernet, etc)
  164. **/
  165. - (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr;
  166. /**
  167. * This method is the same as acceptOnPort:error: with the
  168. * additional option of specifying which interface to listen on.
  169. *
  170. * For example, you could specify that the socket should only accept connections over ethernet,
  171. * and not other interfaces such as wifi.
  172. *
  173. * The interface may be specified by name (e.g. "en1" or "lo0") or by IP address (e.g. "192.168.4.34").
  174. * You may also use the special strings "localhost" or "loopback" to specify that
  175. * the socket only accept connections from the local machine.
  176. *
  177. * You can see the list of interfaces via the command line utility "ifconfig",
  178. * or programmatically via the getifaddrs() function.
  179. *
  180. * To accept connections on any interface pass nil, or simply use the acceptOnPort:error: method.
  181. **/
  182. - (BOOL)acceptOnInterface:(NSString *)interface port:(uint16_t)port error:(NSError **)errPtr;
  183. #pragma mark Connecting
  184. /**
  185. * Connects to the given host and port.
  186. *
  187. * This method invokes connectToHost:onPort:viaInterface:withTimeout:error:
  188. * and uses the default interface, and no timeout.
  189. **/
  190. - (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr;
  191. /**
  192. * Connects to the given host and port with an optional timeout.
  193. *
  194. * This method invokes connectToHost:onPort:viaInterface:withTimeout:error: and uses the default interface.
  195. **/
  196. - (BOOL)connectToHost:(NSString *)host
  197. onPort:(uint16_t)port
  198. withTimeout:(NSTimeInterval)timeout
  199. error:(NSError **)errPtr;
  200. /**
  201. * Connects to the given host & port, via the optional interface, with an optional timeout.
  202. *
  203. * The host may be a domain name (e.g. "deusty.com") or an IP address string (e.g. "192.168.0.2").
  204. * The host may also be the special strings "localhost" or "loopback" to specify connecting
  205. * to a service on the local machine.
  206. *
  207. * The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
  208. * The interface may also be used to specify the local port (see below).
  209. *
  210. * To not time out use a negative time interval.
  211. *
  212. * This method will return NO if an error is detected, and set the error pointer (if one was given).
  213. * Possible errors would be a nil host, invalid interface, or socket is already connected.
  214. *
  215. * If no errors are detected, this method will start a background connect operation and immediately return YES.
  216. * The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.
  217. *
  218. * Since this class supports queued reads and writes, you can immediately start reading and/or writing.
  219. * All read/write operations will be queued, and upon socket connection,
  220. * the operations will be dequeued and processed in order.
  221. *
  222. * The interface may optionally contain a port number at the end of the string, separated by a colon.
  223. * This allows you to specify the local port that should be used for the outgoing connection. (read paragraph to end)
  224. * To specify both interface and local port: "en1:8082" or "192.168.4.35:2424".
  225. * To specify only local port: ":8082".
  226. * Please note this is an advanced feature, and is somewhat hidden on purpose.
  227. * You should understand that 99.999% of the time you should NOT specify the local port for an outgoing connection.
  228. * If you think you need to, there is a very good chance you have a fundamental misunderstanding somewhere.
  229. * Local ports do NOT need to match remote ports. In fact, they almost never do.
  230. * This feature is here for networking professionals using very advanced techniques.
  231. **/
  232. - (BOOL)connectToHost:(NSString *)host
  233. onPort:(uint16_t)port
  234. viaInterface:(NSString *)interface
  235. withTimeout:(NSTimeInterval)timeout
  236. error:(NSError **)errPtr;
  237. /**
  238. * Connects to the given address, specified as a sockaddr structure wrapped in a NSData object.
  239. * For example, a NSData object returned from NSNetService's addresses method.
  240. *
  241. * If you have an existing struct sockaddr you can convert it to a NSData object like so:
  242. * struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
  243. * struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
  244. *
  245. * This method invokes connectToAdd
  246. **/
  247. - (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
  248. /**
  249. * This method is the same as connectToAddress:error: with an additional timeout option.
  250. * To not time out use a negative time interval, or simply use the connectToAddress:error: method.
  251. **/
  252. - (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr;
  253. /**
  254. * Connects to the given address, using the specified interface and timeout.
  255. *
  256. * The address is specified as a sockaddr structure wrapped in a NSData object.
  257. * For example, a NSData object returned from NSNetService's addresses method.
  258. *
  259. * If you have an existing struct sockaddr you can convert it to a NSData object like so:
  260. * struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
  261. * struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
  262. *
  263. * The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
  264. * The interface may also be used to specify the local port (see below).
  265. *
  266. * The timeout is optional. To not time out use a negative time interval.
  267. *
  268. * This method will return NO if an error is detected, and set the error pointer (if one was given).
  269. * Possible errors would be a nil host, invalid interface, or socket is already connected.
  270. *
  271. * If no errors are detected, this method will start a background connect operation and immediately return YES.
  272. * The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.
  273. *
  274. * Since this class supports queued reads and writes, you can immediately start reading and/or writing.
  275. * All read/write operations will be queued, and upon socket connection,
  276. * the operations will be dequeued and processed in order.
  277. *
  278. * The interface may optionally contain a port number at the end of the string, separated by a colon.
  279. * This allows you to specify the local port that should be used for the outgoing connection. (read paragraph to end)
  280. * To specify both interface and local port: "en1:8082" or "192.168.4.35:2424".
  281. * To specify only local port: ":8082".
  282. * Please note this is an advanced feature, and is somewhat hidden on purpose.
  283. * You should understand that 99.999% of the time you should NOT specify the local port for an outgoing connection.
  284. * If you think you need to, there is a very good chance you have a fundamental misunderstanding somewhere.
  285. * Local ports do NOT need to match remote ports. In fact, they almost never do.
  286. * This feature is here for networking professionals using very advanced techniques.
  287. **/
  288. - (BOOL)connectToAddress:(NSData *)remoteAddr
  289. viaInterface:(NSString *)interface
  290. withTimeout:(NSTimeInterval)timeout
  291. error:(NSError **)errPtr;
  292. #pragma mark Disconnecting
  293. /**
  294. * Disconnects immediately (synchronously). Any pending reads or writes are dropped.
  295. *
  296. * If the socket is not already disconnected, an invocation to the socketDidDisconnect:withError: delegate method
  297. * will be queued onto the delegateQueue asynchronously (behind any previously queued delegate methods).
  298. * In other words, the disconnected delegate method will be invoked sometime shortly after this method returns.
  299. *
  300. * Please note the recommended way of releasing a GCDAsyncSocket instance (e.g. in a dealloc method)
  301. * [asyncSocket setDelegate:nil];
  302. * [asyncSocket disconnect];
  303. * [asyncSocket release];
  304. *
  305. * If you plan on disconnecting the socket, and then immediately asking it to connect again,
  306. * you'll likely want to do so like this:
  307. * [asyncSocket setDelegate:nil];
  308. * [asyncSocket disconnect];
  309. * [asyncSocket setDelegate:self];
  310. * [asyncSocket connect...];
  311. **/
  312. - (void)disconnect;
  313. /**
  314. * Disconnects after all pending reads have completed.
  315. * After calling this, the read and write methods will do nothing.
  316. * The socket will disconnect even if there are still pending writes.
  317. **/
  318. - (void)disconnectAfterReading;
  319. /**
  320. * Disconnects after all pending writes have completed.
  321. * After calling this, the read and write methods will do nothing.
  322. * The socket will disconnect even if there are still pending reads.
  323. **/
  324. - (void)disconnectAfterWriting;
  325. /**
  326. * Disconnects after all pending reads and writes have completed.
  327. * After calling this, the read and write methods will do nothing.
  328. **/
  329. - (void)disconnectAfterReadingAndWriting;
  330. #pragma mark Diagnostics
  331. /**
  332. * Returns whether the socket is disconnected or connected.
  333. *
  334. * A disconnected socket may be recycled.
  335. * That is, it can used again for connecting or listening.
  336. *
  337. * If a socket is in the process of connecting, it may be neither disconnected nor connected.
  338. **/
  339. - (BOOL)isDisconnected;
  340. - (BOOL)isConnected;
  341. /**
  342. * Returns the local or remote host and port to which this socket is connected, or nil and 0 if not connected.
  343. * The host will be an IP address.
  344. **/
  345. - (NSString *)connectedHost;
  346. - (uint16_t)connectedPort;
  347. - (NSString *)localHost;
  348. - (uint16_t)localPort;
  349. /**
  350. * Returns the local or remote address to which this socket is connected,
  351. * specified as a sockaddr structure wrapped in a NSData object.
  352. *
  353. * See also the connectedHost, connectedPort, localHost and localPort methods.
  354. **/
  355. - (NSData *)connectedAddress;
  356. - (NSData *)localAddress;
  357. /**
  358. * Returns whether the socket is IPv4 or IPv6.
  359. * An accepting socket may be both.
  360. **/
  361. - (BOOL)isIPv4;
  362. - (BOOL)isIPv6;
  363. /**
  364. * Returns whether or not the socket has been secured via SSL/TLS.
  365. *
  366. * See also the startTLS method.
  367. **/
  368. - (BOOL)isSecure;
  369. #pragma mark Reading
  370. // The readData and writeData methods won't block (they are asynchronous).
  371. //
  372. // When a read is complete the socket:didReadData:withTag: delegate method is dispatched on the delegateQueue.
  373. // When a write is complete the socket:didWriteDataWithTag: delegate method is dispatched on the delegateQueue.
  374. //
  375. // You may optionally set a timeout for any read/write operation. (To not timeout, use a negative time interval.)
  376. // If a read/write opertion times out, the corresponding "socket:shouldTimeout..." delegate method
  377. // is called to optionally allow you to extend the timeout.
  378. // Upon a timeout, the "socket:didDisconnectWithError:" method is called
  379. //
  380. // The tag is for your convenience.
  381. // You can use it as an array index, step number, state id, pointer, etc.
  382. /**
  383. * Reads the first available bytes that become available on the socket.
  384. *
  385. * If the timeout value is negative, the read operation will not use a timeout.
  386. **/
  387. - (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
  388. /**
  389. * Reads the first available bytes that become available on the socket.
  390. * The bytes will be appended to the given byte buffer starting at the given offset.
  391. * The given buffer will automatically be increased in size if needed.
  392. *
  393. * If the timeout value is negative, the read operation will not use a timeout.
  394. * If the buffer if nil, the socket will create a buffer for you.
  395. *
  396. * If the bufferOffset is greater than the length of the given buffer,
  397. * the method will do nothing, and the delegate will not be called.
  398. *
  399. * If you pass a buffer, you must not alter it in any way while the socket is using it.
  400. * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
  401. * That is, it will reference the bytes that were appended to the given buffer via
  402. * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
  403. **/
  404. - (void)readDataWithTimeout:(NSTimeInterval)timeout
  405. buffer:(NSMutableData *)buffer
  406. bufferOffset:(NSUInteger)offset
  407. tag:(long)tag;
  408. /**
  409. * Reads the first available bytes that become available on the socket.
  410. * The bytes will be appended to the given byte buffer starting at the given offset.
  411. * The given buffer will automatically be increased in size if needed.
  412. * A maximum of length bytes will be read.
  413. *
  414. * If the timeout value is negative, the read operation will not use a timeout.
  415. * If the buffer if nil, a buffer will automatically be created for you.
  416. * If maxLength is zero, no length restriction is enforced.
  417. *
  418. * If the bufferOffset is greater than the length of the given buffer,
  419. * the method will do nothing, and the delegate will not be called.
  420. *
  421. * If you pass a buffer, you must not alter it in any way while the socket is using it.
  422. * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
  423. * That is, it will reference the bytes that were appended to the given buffer via
  424. * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
  425. **/
  426. - (void)readDataWithTimeout:(NSTimeInterval)timeout
  427. buffer:(NSMutableData *)buffer
  428. bufferOffset:(NSUInteger)offset
  429. maxLength:(NSUInteger)length
  430. tag:(long)tag;
  431. /**
  432. * Reads the given number of bytes.
  433. *
  434. * If the timeout value is negative, the read operation will not use a timeout.
  435. *
  436. * If the length is 0, this method does nothing and the delegate is not called.
  437. **/
  438. - (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag;
  439. /**
  440. * Reads the given number of bytes.
  441. * The bytes will be appended to the given byte buffer starting at the given offset.
  442. * The given buffer will automatically be increased in size if needed.
  443. *
  444. * If the timeout value is negative, the read operation will not use a timeout.
  445. * If the buffer if nil, a buffer will automatically be created for you.
  446. *
  447. * If the length is 0, this method does nothing and the delegate is not called.
  448. * If the bufferOffset is greater than the length of the given buffer,
  449. * the method will do nothing, and the delegate will not be called.
  450. *
  451. * If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
  452. * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
  453. * That is, it will reference the bytes that were appended to the given buffer via
  454. * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
  455. **/
  456. - (void)readDataToLength:(NSUInteger)length
  457. withTimeout:(NSTimeInterval)timeout
  458. buffer:(NSMutableData *)buffer
  459. bufferOffset:(NSUInteger)offset
  460. tag:(long)tag;
  461. /**
  462. * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
  463. *
  464. * If the timeout value is negative, the read operation will not use a timeout.
  465. *
  466. * If you pass nil or zero-length data as the "data" parameter,
  467. * the method will do nothing (except maybe print a warning), and the delegate will not be called.
  468. *
  469. * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
  470. * If you're developing your own custom protocol, be sure your separator can not occur naturally as
  471. * part of the data between separators.
  472. * For example, imagine you want to send several small documents over a socket.
  473. * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
  474. * In this particular example, it would be better to use a protocol similar to HTTP with
  475. * a header that includes the length of the document.
  476. * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
  477. *
  478. * The given data (separator) parameter should be immutable.
  479. * For performance reasons, the socket will retain it, not copy it.
  480. * So if it is immutable, don't modify it while the socket is using it.
  481. **/
  482. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
  483. /**
  484. * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
  485. * The bytes will be appended to the given byte buffer starting at the given offset.
  486. * The given buffer will automatically be increased in size if needed.
  487. *
  488. * If the timeout value is negative, the read operation will not use a timeout.
  489. * If the buffer if nil, a buffer will automatically be created for you.
  490. *
  491. * If the bufferOffset is greater than the length of the given buffer,
  492. * the method will do nothing (except maybe print a warning), and the delegate will not be called.
  493. *
  494. * If you pass a buffer, you must not alter it in any way while the socket is using it.
  495. * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
  496. * That is, it will reference the bytes that were appended to the given buffer via
  497. * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
  498. *
  499. * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
  500. * If you're developing your own custom protocol, be sure your separator can not occur naturally as
  501. * part of the data between separators.
  502. * For example, imagine you want to send several small documents over a socket.
  503. * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
  504. * In this particular example, it would be better to use a protocol similar to HTTP with
  505. * a header that includes the length of the document.
  506. * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
  507. *
  508. * The given data (separator) parameter should be immutable.
  509. * For performance reasons, the socket will retain it, not copy it.
  510. * So if it is immutable, don't modify it while the socket is using it.
  511. **/
  512. - (void)readDataToData:(NSData *)data
  513. withTimeout:(NSTimeInterval)timeout
  514. buffer:(NSMutableData *)buffer
  515. bufferOffset:(NSUInteger)offset
  516. tag:(long)tag;
  517. /**
  518. * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
  519. *
  520. * If the timeout value is negative, the read operation will not use a timeout.
  521. *
  522. * If maxLength is zero, no length restriction is enforced.
  523. * Otherwise if maxLength bytes are read without completing the read,
  524. * it is treated similarly to a timeout - the socket is closed with a GCDAsyncSocketReadMaxedOutError.
  525. * The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
  526. *
  527. * If you pass nil or zero-length data as the "data" parameter,
  528. * the method will do nothing (except maybe print a warning), and the delegate will not be called.
  529. * If you pass a maxLength parameter that is less than the length of the data parameter,
  530. * the method will do nothing (except maybe print a warning), and the delegate will not be called.
  531. *
  532. * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
  533. * If you're developing your own custom protocol, be sure your separator can not occur naturally as
  534. * part of the data between separators.
  535. * For example, imagine you want to send several small documents over a socket.
  536. * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
  537. * In this particular example, it would be better to use a protocol similar to HTTP with
  538. * a header that includes the length of the document.
  539. * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
  540. *
  541. * The given data (separator) parameter should be immutable.
  542. * For performance reasons, the socket will retain it, not copy it.
  543. * So if it is immutable, don't modify it while the socket is using it.
  544. **/
  545. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag;
  546. /**
  547. * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
  548. * The bytes will be appended to the given byte buffer starting at the given offset.
  549. * The given buffer will automatically be increased in size if needed.
  550. *
  551. * If the timeout value is negative, the read operation will not use a timeout.
  552. * If the buffer if nil, a buffer will automatically be created for you.
  553. *
  554. * If maxLength is zero, no length restriction is enforced.
  555. * Otherwise if maxLength bytes are read without completing the read,
  556. * it is treated similarly to a timeout - the socket is closed with a GCDAsyncSocketReadMaxedOutError.
  557. * The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
  558. *
  559. * If you pass a maxLength parameter that is less than the length of the data (separator) parameter,
  560. * the method will do nothing (except maybe print a warning), and the delegate will not be called.
  561. * If the bufferOffset is greater than the length of the given buffer,
  562. * the method will do nothing (except maybe print a warning), and the delegate will not be called.
  563. *
  564. * If you pass a buffer, you must not alter it in any way while the socket is using it.
  565. * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
  566. * That is, it will reference the bytes that were appended to the given buffer via
  567. * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
  568. *
  569. * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
  570. * If you're developing your own custom protocol, be sure your separator can not occur naturally as
  571. * part of the data between separators.
  572. * For example, imagine you want to send several small documents over a socket.
  573. * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
  574. * In this particular example, it would be better to use a protocol similar to HTTP with
  575. * a header that includes the length of the document.
  576. * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
  577. *
  578. * The given data (separator) parameter should be immutable.
  579. * For performance reasons, the socket will retain it, not copy it.
  580. * So if it is immutable, don't modify it while the socket is using it.
  581. **/
  582. - (void)readDataToData:(NSData *)data
  583. withTimeout:(NSTimeInterval)timeout
  584. buffer:(NSMutableData *)buffer
  585. bufferOffset:(NSUInteger)offset
  586. maxLength:(NSUInteger)length
  587. tag:(long)tag;
  588. #pragma mark Writing
  589. /**
  590. * Writes data to the socket, and calls the delegate when finished.
  591. *
  592. * If you pass in nil or zero-length data, this method does nothing and the delegate will not be called.
  593. * If the timeout value is negative, the write operation will not use a timeout.
  594. *
  595. * Thread-Safety Note:
  596. * If the given data parameter is mutable (NSMutableData) then you MUST NOT alter the data while
  597. * the socket is writing it. In other words, it's not safe to alter the data until after the delegate method
  598. * socket:didWriteDataWithTag: is invoked signifying that this particular write operation has completed.
  599. * This is due to the fact that GCDAsyncSocket does NOT copy the data. It simply retains it.
  600. * This is for performance reasons. Often times, if NSMutableData is passed, it is because
  601. * a request/response was built up in memory. Copying this data adds an unwanted/unneeded overhead.
  602. * If you need to write data from an immutable buffer, and you need to alter the buffer before the socket
  603. * completes writing the bytes (which is NOT immediately after this method returns, but rather at a later time
  604. * when the delegate method notifies you), then you should first copy the bytes, and pass the copy to this method.
  605. **/
  606. - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
  607. #pragma mark Security
  608. /**
  609. * Secures the connection using SSL/TLS.
  610. *
  611. * This method may be called at any time, and the TLS handshake will occur after all pending reads and writes
  612. * are finished. This allows one the option of sending a protocol dependent StartTLS message, and queuing
  613. * the upgrade to TLS at the same time, without having to wait for the write to finish.
  614. * Any reads or writes scheduled after this method is called will occur over the secured connection.
  615. *
  616. * The possible keys and values for the TLS settings are well documented.
  617. * Some possible keys are:
  618. * - kCFStreamSSLLevel
  619. * - kCFStreamSSLAllowsExpiredCertificates
  620. * - kCFStreamSSLAllowsExpiredRoots
  621. * - kCFStreamSSLAllowsAnyRoot
  622. * - kCFStreamSSLValidatesCertificateChain
  623. * - kCFStreamSSLPeerName
  624. * - kCFStreamSSLCertificates
  625. * - kCFStreamSSLIsServer
  626. *
  627. * Please refer to Apple's documentation for associated values, as well as other possible keys.
  628. *
  629. * If you pass in nil or an empty dictionary, the default settings will be used.
  630. *
  631. * The default settings will check to make sure the remote party's certificate is signed by a
  632. * trusted 3rd party certificate agency (e.g. verisign) and that the certificate is not expired.
  633. * However it will not verify the name on the certificate unless you
  634. * give it a name to verify against via the kCFStreamSSLPeerName key.
  635. * The security implications of this are important to understand.
  636. * Imagine you are attempting to create a secure connection to MySecureServer.com,
  637. * but your socket gets directed to MaliciousServer.com because of a hacked DNS server.
  638. * If you simply use the default settings, and MaliciousServer.com has a valid certificate,
  639. * the default settings will not detect any problems since the certificate is valid.
  640. * To properly secure your connection in this particular scenario you
  641. * should set the kCFStreamSSLPeerName property to "MySecureServer.com".
  642. * If you do not know the peer name of the remote host in advance (for example, you're not sure
  643. * if it will be "domain.com" or "www.domain.com"), then you can use the default settings to validate the
  644. * certificate, and then use the X509Certificate class to verify the issuer after the socket has been secured.
  645. * The X509Certificate class is part of the CocoaAsyncSocket open source project.
  646. **/
  647. - (void)startTLS:(NSDictionary *)tlsSettings;
  648. #pragma mark Advanced
  649. /**
  650. * It's not thread-safe to access certain variables from outside the socket's internal queue.
  651. *
  652. * For example, the socket file descriptor.
  653. * File descriptors are simply integers which reference an index in the per-process file table.
  654. * However, when one requests a new file descriptor (by opening a file or socket),
  655. * the file descriptor returned is guaranteed to be the lowest numbered unused descriptor.
  656. * So if we're not careful, the following could be possible:
  657. *
  658. * - Thread A invokes a method which returns the socket's file descriptor.
  659. * - The socket is closed via the socket's internal queue on thread B.
  660. * - Thread C opens a file, and subsequently receives the file descriptor that was previously the socket's FD.
  661. * - Thread A is now accessing/altering the file instead of the socket.
  662. *
  663. * In addition to this, other variables are not actually objects,
  664. * and thus cannot be retained/released or even autoreleased.
  665. * An example is the sslContext, of type SSLContextRef, which is actually a malloc'd struct.
  666. *
  667. * Although there are internal variables that make it difficult to maintain thread-safety,
  668. * it is important to provide access to these variables
  669. * to ensure this class can be used in a wide array of environments.
  670. * This method helps to accomplish this by invoking the current block on the socket's internal queue.
  671. * The methods below can be invoked from within the block to access
  672. * those generally thread-unsafe internal variables in a thread-safe manner.
  673. * The given block will be invoked synchronously on the socket's internal queue.
  674. *
  675. * If you save references to any protected variables and use them outside the block, you do so at your own peril.
  676. **/
  677. - (void)performBlock:(dispatch_block_t)block;
  678. /**
  679. * These methods are only available from within the context of a performBlock: invocation.
  680. * See the documentation for the performBlock: method above.
  681. *
  682. * Provides access to the socket's file descriptor(s).
  683. * If the socket is a server socket (is accepting incoming connections),
  684. * it might actually have multiple internal socket file descriptors - one for IPv4 and one for IPv6.
  685. **/
  686. - (int)socketFD;
  687. - (int)socket4FD;
  688. - (int)socket6FD;
  689. #if TARGET_OS_IPHONE
  690. /**
  691. * These methods are only available from within the context of a performBlock: invocation.
  692. * See the documentation for the performBlock: method above.
  693. *
  694. * Provides access to the socket's internal CFReadStream/CFWriteStream.
  695. *
  696. * These streams are only used as workarounds for specific iOS shortcomings:
  697. *
  698. * - Apple has decided to keep the SecureTransport framework private is iOS.
  699. * This means the only supplied way to do SSL/TLS is via CFStream or some other API layered on top of it.
  700. * Thus, in order to provide SSL/TLS support on iOS we are forced to rely on CFStream,
  701. * instead of the preferred and faster and more powerful SecureTransport.
  702. *
  703. * - If a socket doesn't have backgrounding enabled, and that socket is closed while the app is backgrounded,
  704. * Apple only bothers to notify us via the CFStream API.
  705. * The faster and more powerful GCD API isn't notified properly in this case.
  706. *
  707. * See also: (BOOL)enableBackgroundingOnSocket
  708. **/
  709. - (CFReadStreamRef)readStream;
  710. - (CFWriteStreamRef)writeStream;
  711. /**
  712. * This method is only available from within the context of a performBlock: invocation.
  713. * See the documentation for the performBlock: method above.
  714. *
  715. * Configures the socket to allow it to operate when the iOS application has been backgrounded.
  716. * In other words, this method creates a read & write stream, and invokes:
  717. *
  718. * CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  719. * CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  720. *
  721. * Returns YES if successful, NO otherwise.
  722. *
  723. * Note: Apple does not officially support backgrounding server sockets.
  724. * That is, if your socket is accepting incoming connections, Apple does not officially support
  725. * allowing iOS applications to accept incoming connections while an app is backgrounded.
  726. *
  727. * Example usage:
  728. *
  729. * - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
  730. * {
  731. * [asyncSocket performBlock:^{
  732. * [asyncSocket enableBackgroundingOnSocket];
  733. * }];
  734. * }
  735. **/
  736. - (BOOL)enableBackgroundingOnSocket;
  737. #else
  738. /**
  739. * This method is only available from within the context of a performBlock: invocation.
  740. * See the documentation for the performBlock: method above.
  741. *
  742. * Provides access to the socket's SSLContext, if SSL/TLS has been started on the socket.
  743. **/
  744. - (SSLContextRef)sslContext;
  745. #endif
  746. #pragma mark Utilities
  747. /**
  748. * Extracting host and port information from raw address data.
  749. **/
  750. + (NSString *)hostFromAddress:(NSData *)address;
  751. + (uint16_t)portFromAddress:(NSData *)address;
  752. + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr fromAddress:(NSData *)address;
  753. /**
  754. * A few common line separators, for use with the readDataToData:... methods.
  755. **/
  756. + (NSData *)CRLFData; // 0x0D0A
  757. + (NSData *)CRData; // 0x0D
  758. + (NSData *)LFData; // 0x0A
  759. + (NSData *)ZeroData; // 0x00
  760. @end
  761. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  762. #pragma mark -
  763. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  764. @protocol GCDAsyncSocketDelegate
  765. @optional
  766. /**
  767. * This method is called immediately prior to socket:didAcceptNewSocket:.
  768. * It optionally allows a listening socket to specify the socketQueue for a new accepted socket.
  769. * If this method is not implemented, or returns NULL, the new accepted socket will create its own default queue.
  770. *
  771. * Since you cannot autorelease a dispatch_queue,
  772. * this method uses the "new" prefix in its name to specify that the returned queue has been retained.
  773. *
  774. * Thus you could do something like this in the implementation:
  775. * return dispatch_queue_create("MyQueue", NULL);
  776. *
  777. * If you are placing multiple sockets on the same queue,
  778. * then care should be taken to increment the retain count each time this method is invoked.
  779. *
  780. * For example, your implementation might look something like this:
  781. * dispatch_retain(myExistingQueue);
  782. * return myExistingQueue;
  783. **/
  784. - (dispatch_queue_t)newSocketQueueForConnectionFromAddress:(NSData *)address onSocket:(GCDAsyncSocket *)sock;
  785. /**
  786. * Called when a socket accepts a connection.
  787. * Another socket is automatically spawned to handle it.
  788. *
  789. * You must retain the newSocket if you wish to handle the connection.
  790. * Otherwise the newSocket instance will be released and the spawned connection will be closed.
  791. *
  792. * By default the new socket will have the same delegate and delegateQueue.
  793. * You may, of course, change this at any time.
  794. **/
  795. - (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket;
  796. /**
  797. * Called when a socket connects and is ready for reading and writing.
  798. * The host parameter will be an IP address, not a DNS name.
  799. **/
  800. - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
  801. /**
  802. * Called when a socket has completed reading the requested data into memory.
  803. * Not called if there is an error.
  804. **/
  805. - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
  806. /**
  807. * Called when a socket has read in data, but has not yet completed the read.
  808. * This would occur if using readToData: or readToLength: methods.
  809. * It may be used to for things such as updating progress bars.
  810. **/
  811. - (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
  812. /**
  813. * Called when a socket has completed writing the requested data. Not called if there is an error.
  814. **/
  815. - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;
  816. /**
  817. * Called when a socket has written some data, but has not yet completed the entire write.
  818. * It may be used to for things such as updating progress bars.
  819. **/
  820. - (void)socket:(GCDAsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
  821. /**
  822. * Called if a read operation has reached its timeout without completing.
  823. * This method allows you to optionally extend the timeout.
  824. * If you return a positive time interval (> 0) the read's timeout will be extended by the given amount.
  825. * If you don't implement this method, or return a non-positive time interval (<= 0) the read will timeout as usual.
  826. *
  827. * The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
  828. * The length parameter is the number of bytes that have been read so far for the read operation.
  829. *
  830. * Note that this method may be called multiple times for a single read if you return positive numbers.
  831. **/
  832. - (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag
  833. elapsed:(NSTimeInterval)elapsed
  834. bytesDone:(NSUInteger)length;
  835. /**
  836. * Called if a write operation has reached its timeout without completing.
  837. * This method allows you to optionally extend the timeout.
  838. * If you return a positive time interval (> 0) the write's timeout will be extended by the given amount.
  839. * If you don't implement this method, or return a non-positive time interval (<= 0) the write will timeout as usual.
  840. *
  841. * The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
  842. * The length parameter is the number of bytes that have been written so far for the write operation.
  843. *
  844. * Note that this method may be called multiple times for a single write if you return positive numbers.
  845. **/
  846. - (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag
  847. elapsed:(NSTimeInterval)elapsed
  848. bytesDone:(NSUInteger)length;
  849. /**
  850. * Conditionally called if the read stream closes, but the write stream may still be writeable.
  851. *
  852. * This delegate method is only called if autoDisconnectOnClosedReadStream has been set to NO.
  853. * See the discussion on the autoDisconnectOnClosedReadStream method for more information.
  854. **/
  855. - (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock;
  856. /**
  857. * Called when a socket disconnects with or without error.
  858. *
  859. * If you call the disconnect method, and the socket wasn't already disconnected,
  860. * this delegate method will be called before the disconnect method returns.
  861. **/
  862. - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err;
  863. /**
  864. * Called after the socket has successfully completed SSL/TLS negotiation.
  865. * This method is not called unless you use the provided startTLS method.
  866. *
  867. * If a SSL/TLS negotiation fails (invalid certificate, etc) then the socket will immediately close,
  868. * and the socketDidDisconnect:withError: delegate method will be called with the specific SSL error code.
  869. **/
  870. - (void)socketDidSecure:(GCDAsyncSocket *)sock;
  871. @end