PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/External/Quickblox.framework/Versions/A/Headers/Core/External/XMPP/Vendor/CocoaAsyncSocket/QBGCDAsyncSocket.h

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