PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/CocoaAsyncSocket/GCDAsyncSocket.h

https://github.com/lujingyu/XMPPFramework
C Header | 1175 lines | 183 code | 94 blank | 898 comment | 0 complexity | 7e20d67791173a1be0678b5024f094d9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file