code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
/**
* Abstract HTTP message writer for non-blocking connections.
*
* @since 4.0
*/
public interface NHttpMessageWriter<T extends HttpMessage> {
/**
* Resets the writer. The writer will be ready to start serializing another
* HTTP message.
*/
void reset();
/**
* Serializes out the HTTP message head.
*
* @param message HTTP message.
* @throws IOException in case of an I/O error.
* @throws HttpException in case the HTTP message is malformed or
* violates the HTTP protocol.
*/
void write(T message) throws IOException, HttpException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageWriter.java
|
Java
|
gpl3
| 1,930
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* A content decoder capable of transferring data directly to a {@link FileChannel}
*
* @since 4.0
*/
public interface FileContentDecoder extends ContentDecoder {
/**
* Transfers a portion of entity content from the underlying network channel
* into the given file channel.<br>
*
* <b>Warning</b>: Many implementations cannot write beyond the length of the file.
* If the position exceeds the channel's size, some implementations
* may throw an IOException.
*
* @param dst the target FileChannel to transfer data into.
* @param position
* The position within the file at which the transfer is to begin;
* must be non-negative.
* <b>Must be less than or equal to the size of the file</b>
* @param count
* The maximum number of bytes to be transferred; must be
* non-negative
* @throws IOException, if some I/O error occurs.
* @return The number of bytes, possibly zero,
* that were actually transferred
*/
long transfer(FileChannel dst, long position, long count) throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/FileContentDecoder.java
|
Java
|
gpl3
| 2,456
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Abstract HTTP content decoder. HTTP content decoders can be used
* to read entity content from the underlying channel in small
* chunks and apply the required coding transformation.
*
* @since 4.0
*/
public interface ContentDecoder {
/**
* Reads a portion of content from the underlying channel
*
* @param dst The buffer into which entity content is to be transferred
* @return The number of bytes read, possibly zero, or -1 if the
* channel has reached end-of-stream
* @throws IOException if I/O error occurs while reading content
*/
int read(ByteBuffer dst) throws IOException;
/**
* Returns <code>true</code> if the entity has been received in its
* entirety.
*
* @return <code>true</code> if all the content has been consumed,
* <code>false</code> otherwise.
*/
boolean isCompleted();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/ContentDecoder.java
|
Java
|
gpl3
| 2,159
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.FileChannel;
import org.apache.http.nio.ContentEncoder;
/**
* A content encoder capable of transferring data directly from a {@link FileChannel}
*
* @since 4.0
*/
public interface FileContentEncoder extends ContentEncoder {
/**
* Transfers a portion of entity content from the given file channel
* to the underlying network channel.
*
* @param src the source FileChannel to transfer data from.
* @param position
* The position within the file at which the transfer is to begin;
* must be non-negative
* @param count
* The maximum number of bytes to be transferred; must be
* non-negative
*@throws IOException, if some I/O error occurs.
* @return The number of bytes, possibly zero,
* that were actually transferred
*/
long transfer(FileChannel src, long position, long count) throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/FileContentEncoder.java
|
Java
|
gpl3
| 2,196
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import org.apache.http.HttpConnection;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
/**
* Abstract non-blocking HTTP connection interface. Each connection contains an
* HTTP execution context, which can be used to maintain a processing state,
* as well as the actual {@link HttpRequest} and {@link HttpResponse} that are
* being transmitted over this connection. Both the request and
* the response objects can be <code>null</code> if there is no incoming or
* outgoing message currently being transferred.
* <p>
* Please note non-blocking HTTP connections are stateful and not thread safe.
* Input / output operations on non-blocking HTTP connections should be
* restricted to the dispatch events triggered by the I/O event dispatch thread.
* However, the {@link IOControl} interface is fully threading safe and can be
* manipulated from any thread.
*
* @since 4.0
*/
public interface NHttpConnection extends HttpConnection, IOControl {
public static final int ACTIVE = 0;
public static final int CLOSING = 1;
public static final int CLOSED = 2;
/**
* Returns status of the connection:
* <p>
* {@link #ACTIVE}: connection is active.
* <p>
* {@link #CLOSING}: connection is being closed.
* <p>
* {@link #CLOSED}: connection has been closed.
*
* @return connection status.
*/
int getStatus();
/**
* Returns the current HTTP request if one is being received / transmitted.
* Otherwise returns <code>null</code>.
*
* @return HTTP request, if available, <code>null</code> otherwise.
*/
HttpRequest getHttpRequest();
/**
* Returns the current HTTP response if one is being received / transmitted.
* Otherwise returns <tt>null</tt>.
*
* @return HTTP response, if available, <code>null</code> otherwise.
*/
HttpResponse getHttpResponse();
/**
* Returns an HTTP execution context associated with this connection.
* @return HTTP context
*/
HttpContext getContext();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpConnection.java
|
Java
|
gpl3
| 3,342
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import org.apache.http.nio.reactor.IOEventDispatch;
/**
* Extended version of the {@link NHttpClientConnection} used by
* {@link IOEventDispatch} implementations to inform client-side connection
* objects of I/O events.
*
* @since 4.0
*/
public interface NHttpClientIOTarget extends NHttpClientConnection {
/**
* Triggered when the connection is ready to consume input.
*
* @param handler the client protocol handler.
*/
void consumeInput(NHttpClientHandler handler);
/**
* Triggered when the connection is ready to produce output.
*
* @param handler the client protocol handler.
*/
void produceOutput(NHttpClientHandler handler);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientIOTarget.java
|
Java
|
gpl3
| 1,914
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
/**
* Abstract client-side HTTP protocol handler.
*
* @since 4.0
*/
public interface NHttpClientHandler {
/**
* Triggered when a new outgoing connection is created.
*
* @param conn new outgoing HTTP connection.
* @param attachment an object that was attached to the session request
*/
void connected(NHttpClientConnection conn, Object attachment);
/**
* Triggered when the connection is ready to accept a new HTTP request.
* The protocol handler does not have to submit a request if it is not
* ready.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that is ready to accept a new HTTP request.
*/
void requestReady(NHttpClientConnection conn);
/**
* Triggered when an HTTP response is received. The connection
* passed as a parameter to this method is guaranteed to return
* a valid HTTP response object.
* <p/>
* If the response received encloses a response entity this method will
* be followed by a series of
* {@link #inputReady(NHttpClientConnection, ContentDecoder)} calls
* to transfer the response content.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that contains an HTTP response
*/
void responseReceived(NHttpClientConnection conn);
/**
* Triggered when the underlying channel is ready for reading a
* new portion of the response entity through the corresponding
* content decoder.
* <p/>
* If the content consumer is unable to process the incoming content,
* input event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentDecoder
* @see IOControl
*
* @param conn HTTP connection that can produce a new portion of the
* incoming response content.
* @param decoder The content decoder to use to read content.
*/
void inputReady(NHttpClientConnection conn, ContentDecoder decoder);
/**
* Triggered when the underlying channel is ready for writing a next portion
* of the request entity through the corresponding content encoder.
* <p>
* If the content producer is unable to generate the outgoing content,
* output event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentEncoder
* @see IOControl
*
* @param conn HTTP connection that can accommodate a new portion
* of the outgoing request content.
* @param encoder The content encoder to use to write content.
*/
void outputReady(NHttpClientConnection conn, ContentEncoder encoder);
/**
* Triggered when an I/O error occurs while reading from or writing
* to the underlying channel.
*
* @param conn HTTP connection that caused an I/O error
* @param ex I/O exception
*/
void exception(NHttpClientConnection conn, IOException ex);
/**
* Triggered when an HTTP protocol violation occurs while receiving
* an HTTP response.
*
* @param conn HTTP connection that caused an HTTP protocol violation
* @param ex HTTP protocol violation exception
*/
void exception(NHttpClientConnection conn, HttpException ex);
/**
* Triggered when no input is detected on this connection over the
* maximum period of inactivity.
*
* @param conn HTTP connection that caused timeout condition.
*/
void timeout(NHttpClientConnection conn);
/**
* Triggered when the connection is closed.
*
* @param conn closed HTTP connection.
*/
void closed(NHttpClientConnection conn);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientHandler.java
|
Java
|
gpl3
| 5,045
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
-->
</head>
<body>
Representations for non-blocking HTTP message entities.
An {@link org.apache.http.HttpEntity entity} is the optional content of a
{@link org.apache.http.HttpMessage message}.
This package provides a basic selection of entity implementations
that can obtain content from
{@link org.apache.http.nio.entity.NByteArrayEntity byte array},
{@link org.apache.http.nio.entity.NStringEntity string},
{@link org.apache.http.nio.entity.NFileEntity file}, or through an
{@link org.apache.http.nio.entity.NHttpEntityWrapper compatibility adaptor}
for blocking HTTP entities.
If a message is received from an open non-blocking connection, usually it is
represented by
{@link org.apache.http.nio.entity.ConsumingNHttpEntity consuming} entity.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/package.html
|
HTML
|
gpl3
| 1,967
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.io.BufferInfo;
import org.apache.http.nio.util.ContentInputBuffer;
/**
* {@link InputStream} adaptor for {@link ContentInputBuffer}.
*
* @since 4.0
*/
public class ContentInputStream extends InputStream {
private final ContentInputBuffer buffer;
public ContentInputStream(final ContentInputBuffer buffer) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Input buffer may not be null");
}
this.buffer = buffer;
}
@Override
public int available() throws IOException {
if (this.buffer instanceof BufferInfo) {
return ((BufferInfo) this.buffer).length();
} else {
return super.available();
}
}
@Override
public int read(final byte[] b, int off, int len) throws IOException {
return this.buffer.read(b, off, len);
}
@Override
public int read(final byte[] b) throws IOException {
if (b == null) {
return 0;
}
return this.buffer.read(b, 0, b.length);
}
@Override
public int read() throws IOException {
return this.buffer.read();
}
@Override
public void close() throws IOException {
// read and discard the remainder of the message
byte tmp[] = new byte[1024];
while (this.buffer.read(tmp, 0, tmp.length) >= 0) {
}
super.close();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentInputStream.java
|
Java
|
gpl3
| 2,717
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
/**
* An entity whose content is retrieved from a string. In addition to the
* standard {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NStringEntity}
*
* @since 4.0
*/
@Deprecated
public class StringNIOEntity extends StringEntity implements HttpNIOEntity {
public StringNIOEntity(
final String s,
String charset) throws UnsupportedEncodingException {
super(s, charset);
}
public ReadableByteChannel getChannel() throws IOException {
return Channels.newChannel(getContent());
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/StringNIOEntity.java
|
Java
|
gpl3
| 2,077
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.ContentEncoderChannel;
import org.apache.http.nio.FileContentEncoder;
import org.apache.http.nio.IOControl;
/**
* A self contained, repeatable non-blocking entity that retrieves its content
* from a file. This class is mostly used to stream large files of different
* types, so one needs to supply the content type of the file to make sure
* the content can be correctly recognized and processed by the recipient.
*
* @since 4.0
*/
public class NFileEntity extends AbstractHttpEntity implements ProducingNHttpEntity {
private final File file;
private FileChannel fileChannel;
private long idx = -1;
private boolean useFileChannels;
/**
* Creates new instance of NFileEntity from the given source {@link File}
* with the given content type. If <code>useFileChannels</code> is set to
* <code>true</code>, the entity will try to use {@link FileContentEncoder}
* interface to stream file content directly from the file channel.
*
* @param file the source file.
* @param contentType the content type of the file.
* @param useFileChannels flag whether the direct transfer from the file
* channel should be attempted.
*/
public NFileEntity(final File file, final String contentType, boolean useFileChannels) {
if (file == null) {
throw new IllegalArgumentException("File may not be null");
}
this.file = file;
this.useFileChannels = useFileChannels;
setContentType(contentType);
}
public NFileEntity(final File file, final String contentType) {
this(file, contentType, true);
}
public void finish() {
try {
if(fileChannel != null)
fileChannel.close();
} catch(IOException ignored) {}
fileChannel = null;
}
public long getContentLength() {
return file.length();
}
public boolean isRepeatable() {
return true;
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
if(fileChannel == null) {
FileInputStream in = new FileInputStream(file);
fileChannel = in.getChannel();
idx = 0;
}
long transferred;
if(useFileChannels && encoder instanceof FileContentEncoder) {
transferred = ((FileContentEncoder)encoder)
.transfer(fileChannel, idx, Long.MAX_VALUE);
} else {
transferred = fileChannel.
transferTo(idx, Long.MAX_VALUE, new ContentEncoderChannel(encoder));
}
if(transferred > 0)
idx += transferred;
if(idx >= fileChannel.size())
encoder.complete();
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() throws IOException {
return new FileInputStream(this.file);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = new FileInputStream(this.file);
try {
byte[] tmp = new byte[4096];
int l;
while ((l = instream.read(tmp)) != -1) {
outstream.write(tmp, 0, l);
}
outstream.flush();
} finally {
instream.close();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NFileEntity.java
|
Java
|
gpl3
| 4,978
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;
/**
* An entity whose content is retrieved from a byte array. In addition to the
* standard {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NByteArrayEntity}
*
* @since 4.0
*/
@Deprecated
public class ByteArrayNIOEntity extends ByteArrayEntity implements HttpNIOEntity {
public ByteArrayNIOEntity(final byte[] b) {
super(b);
}
public ReadableByteChannel getChannel() throws IOException {
return Channels.newChannel(getContent());
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ByteArrayNIOEntity.java
|
Java
|
gpl3
| 1,965
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.SimpleInputBuffer;
/**
* A {@link ConsumingNHttpEntity} that consumes content into a buffer. The
* content can be retrieved as an InputStream via
* {@link HttpEntity#getContent()}, or written to an output stream via
* {@link HttpEntity#writeTo(OutputStream)}.
*
* @since 4.0
*/
public class BufferingNHttpEntity extends HttpEntityWrapper implements
ConsumingNHttpEntity {
private final static int BUFFER_SIZE = 2048;
private final SimpleInputBuffer buffer;
private boolean finished;
private boolean consumed;
public BufferingNHttpEntity(
final HttpEntity httpEntity,
final ByteBufferAllocator allocator) {
super(httpEntity);
this.buffer = new SimpleInputBuffer(BUFFER_SIZE, allocator);
}
public void consumeContent(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
this.buffer.consumeContent(decoder);
if (decoder.isCompleted()) {
this.finished = true;
}
}
public void finish() {
this.finished = true;
}
@Override
public void consumeContent() throws IOException {
}
/**
* Obtains entity's content as {@link InputStream}.
*
* @throws IllegalStateException if content of the entity has not been
* fully received or has already been consumed.
*/
@Override
public InputStream getContent() throws IOException {
if (!this.finished) {
throw new IllegalStateException("Entity content has not been fully received");
}
if (this.consumed) {
throw new IllegalStateException("Entity content has been consumed");
}
this.consumed = true;
return new ContentInputStream(this.buffer);
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isStreaming() {
return true;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = getContent();
byte[] buffer = new byte[BUFFER_SIZE];
int l;
// consume until EOF
while ((l = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, l);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/BufferingNHttpEntity.java
|
Java
|
gpl3
| 3,973
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A non-blocking {@link HttpEntity} that allows content to be streamed from a
* {@link ContentDecoder}.
*
* @since 4.0
*/
public interface ConsumingNHttpEntity extends HttpEntity {
/**
* Notification that content is available to be read from the decoder.
* {@link IOControl} instance passed as a parameter to the method can be
* used to suspend input events if the entity is temporarily unable to
* allocate more storage to accommodate all incoming content.
*
* @param decoder content decoder.
* @param ioctrl I/O control of the underlying connection.
*/
void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException;
/**
* Notification that any resources allocated for reading can be released.
*/
void finish() throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ConsumingNHttpEntity.java
|
Java
|
gpl3
| 2,199
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
import org.apache.http.protocol.HTTP;
/**
* A simple, self contained, repeatable non-blocking entity that retrieves
* its content from a {@link String} object.
*
* @see AsyncNHttpServiceHandler
* @since 4.0
*
*/
public class NStringEntity extends AbstractHttpEntity implements ProducingNHttpEntity {
protected final byte[] content;
protected final ByteBuffer buffer;
public NStringEntity(final String s, String charset)
throws UnsupportedEncodingException {
if (s == null) {
throw new IllegalArgumentException("Source string may not be null");
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
this.content = s.getBytes(charset);
this.buffer = ByteBuffer.wrap(this.content);
setContentType(HTTP.PLAIN_TEXT_TYPE + HTTP.CHARSET_PARAM + charset);
}
public NStringEntity(final String s) throws UnsupportedEncodingException {
this(s, null);
}
public boolean isRepeatable() {
return true;
}
public long getContentLength() {
return this.buffer.limit();
}
public void finish() {
buffer.rewind();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
encoder.write(buffer);
if(!buffer.hasRemaining())
encoder.complete();
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() {
return new ByteArrayInputStream(content);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
outstream.write(content);
outstream.flush();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NStringEntity.java
|
Java
|
gpl3
| 3,444
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A listener for available data on a non-blocking {@link ConsumingNHttpEntity}.
*
* @since 4.0
*/
public interface ContentListener {
/**
* Notification that content is available to be read from the decoder.
*
* @param decoder content decoder.
* @param ioctrl I/O control of the underlying connection.
*/
void contentAvailable(ContentDecoder decoder, IOControl ioctrl)
throws IOException;
/**
* Notification that any resources allocated for reading can be released.
*/
void finished();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentListener.java
|
Java
|
gpl3
| 1,890
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.nio.util.ContentInputBuffer;
/**
* HTTP entity wrapper whose content is provided by a
* {@link ContentInputBuffer}.
*
* @since 4.0
*/
public class ContentBufferEntity extends BasicHttpEntity {
private HttpEntity wrappedEntity;
/**
* Creates new instance of ContentBufferEntity.
*
* @param entity the original entity.
* @param buffer the content buffer.
*/
public ContentBufferEntity(final HttpEntity entity, final ContentInputBuffer buffer) {
super();
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
this.wrappedEntity = entity;
setContent(new ContentInputStream(buffer));
}
@Override
public boolean isChunked() {
return this.wrappedEntity.isChunked();
}
@Override
public long getContentLength() {
return this.wrappedEntity.getContentLength();
}
@Override
public Header getContentType() {
return this.wrappedEntity.getContentType();
}
@Override
public Header getContentEncoding() {
return this.wrappedEntity.getContentEncoding();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentBufferEntity.java
|
Java
|
gpl3
| 2,521
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.util.ByteBufferAllocator;
/**
* A simple {@link ContentListener} that reads and ignores all content.
*
* @since 4.0
*/
public class SkipContentListener implements ContentListener {
private final ByteBuffer buffer;
public SkipContentListener(final ByteBufferAllocator allocator) {
super();
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
this.buffer = allocator.allocate(2048);
}
public void contentAvailable(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
int totalRead = 0;
int lastRead;
do {
buffer.clear();
lastRead = decoder.read(buffer);
if (lastRead > 0)
totalRead += lastRead;
} while (lastRead > 0);
}
public void finished() {
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/SkipContentListener.java
|
Java
|
gpl3
| 2,299
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.nio.util.ContentOutputBuffer;
/**
* {@link OutputStream} adaptor for {@link ContentOutputBuffer}.
*
* @since 4.0
*/
public class ContentOutputStream extends OutputStream {
private final ContentOutputBuffer buffer;
public ContentOutputStream(final ContentOutputBuffer buffer) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Output buffer may not be null");
}
this.buffer = buffer;
}
@Override
public void close() throws IOException {
this.buffer.writeCompleted();
}
@Override
public void flush() throws IOException {
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.buffer.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
if (b == null) {
return;
}
this.buffer.write(b, 0, b.length);
}
@Override
public void write(int b) throws IOException {
this.buffer.write(b);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentOutputStream.java
|
Java
|
gpl3
| 2,347
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.FileEntity;
/**
* An entity whose content is retrieved from from a file. In addition to the standard
* {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NFileEntity}
*
* @since 4.0
*/
@Deprecated
public class FileNIOEntity extends FileEntity implements HttpNIOEntity {
public FileNIOEntity(final File file, final String contentType) {
super(file, contentType);
}
public ReadableByteChannel getChannel() throws IOException {
RandomAccessFile rafile = new RandomAccessFile(this.file, "r");
return rafile.getChannel();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/FileNIOEntity.java
|
Java
|
gpl3
| 2,059
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* An {@link HttpEntity} that can stream content out into a
* {@link ContentEncoder}.
*
* @since 4.0
*/
public interface ProducingNHttpEntity extends HttpEntity {
/**
* Notification that content should be written to the encoder.
* {@link IOControl} instance passed as a parameter to the method can be
* used to suspend output events if the entity is temporarily unable to
* produce more content.
* <p>
* When all content is finished, this <b>MUST</b> call {@link ContentEncoder#complete()}.
* Failure to do so could result in the entity never being written.
*
* @param encoder content encoder.
* @param ioctrl I/O control of the underlying connection.
*/
void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException;
/**
* Notification that any resources allocated for writing can be released.
*/
void finish() throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ProducingNHttpEntity.java
|
Java
|
gpl3
| 2,313
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
/**
* A simple self contained, repeatable non-blocking entity that retrieves
* its content from a byte array.
*
* @see AsyncNHttpServiceHandler
* @since 4.0
*/
public class NByteArrayEntity
extends AbstractHttpEntity implements ProducingNHttpEntity {
protected final byte[] content;
protected final ByteBuffer buffer;
public NByteArrayEntity(final byte[] b) {
this.content = b;
this.buffer = ByteBuffer.wrap(b);
}
public void finish() {
buffer.rewind();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
encoder.write(buffer);
if(!buffer.hasRemaining())
encoder.complete();
}
public long getContentLength() {
return buffer.limit();
}
public boolean isRepeatable() {
return true;
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() {
return new ByteArrayInputStream(content);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
outstream.write(content);
outstream.flush();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NByteArrayEntity.java
|
Java
|
gpl3
| 2,863
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* {@link ProducingNHttpEntity} compatibility adaptor for blocking HTTP
* entities.
*
* @since 4.0
*/
public class NHttpEntityWrapper
extends HttpEntityWrapper implements ProducingNHttpEntity {
private final ReadableByteChannel channel;
private final ByteBuffer buffer;
public NHttpEntityWrapper(final HttpEntity httpEntity) throws IOException {
super(httpEntity);
this.channel = Channels.newChannel(httpEntity.getContent());
this.buffer = ByteBuffer.allocate(4096);
}
/**
* This method throws {@link UnsupportedOperationException}.
*/
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
@Override
public boolean isStreaming() {
return true;
}
/**
* This method throws {@link UnsupportedOperationException}.
*/
@Override
public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
/**
* This method is equivalent to the {@link #finish()} method.
* <br/>
* TODO: The name of this method is misnomer. It will be renamed to
* #finish() in the next major release.
*/
@Override
public void consumeContent() throws IOException {
finish();
}
public void produceContent(
final ContentEncoder encoder,
final IOControl ioctrl) throws IOException {
int i = this.channel.read(this.buffer);
this.buffer.flip();
encoder.write(this.buffer);
boolean buffering = this.buffer.hasRemaining();
this.buffer.compact();
if (i == -1 && !buffering) {
encoder.complete();
this.channel.close();
}
}
public void finish() {
try {
this.channel.close();
} catch (IOException ignore) {
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NHttpEntityWrapper.java
|
Java
|
gpl3
| 3,629
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A {@link ConsumingNHttpEntity} that forwards available content to a
* {@link ContentListener}.
*
* @since 4.0
*/
public class ConsumingNHttpEntityTemplate
extends HttpEntityWrapper implements ConsumingNHttpEntity {
private final ContentListener contentListener;
public ConsumingNHttpEntityTemplate(
final HttpEntity httpEntity,
final ContentListener contentListener) {
super(httpEntity);
this.contentListener = contentListener;
}
public ContentListener getContentListener() {
return contentListener;
}
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
@Override
public boolean isStreaming() {
return true;
}
@Override
public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
/**
* This method is equivalent to the {@link #finish()} method.
* <br/>
* TODO: The name of this method is misnomer. It will be renamed to
* #finish() in the next major release.
*/
@Override
public void consumeContent() throws IOException {
finish();
}
public void consumeContent(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
this.contentListener.contentAvailable(decoder, ioctrl);
}
public void finish() {
this.contentListener.finished();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ConsumingNHttpEntityTemplate.java
|
Java
|
gpl3
| 3,119
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
/**
* @deprecated Use {@link ProducingNHttpEntity}
*
* @since 4.0
*/
@Deprecated
public interface HttpNIOEntity extends HttpEntity {
ReadableByteChannel getChannel() throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/HttpNIOEntity.java
|
Java
|
gpl3
| 1,532
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
/**
* Abstract server-side HTTP protocol handler.
*
* @since 4.0
*/
public interface NHttpServiceHandler {
/**
* Triggered when a new incoming connection is created.
*
* @param conn new incoming connection HTTP connection.
*/
void connected(NHttpServerConnection conn);
/**
* Triggered when a new HTTP request is received. The connection
* passed as a parameter to this method is guaranteed to return
* a valid HTTP request object.
* <p/>
* If the request received encloses a request entity this method will
* be followed a series of
* {@link #inputReady(NHttpServerConnection, ContentDecoder)} calls
* to transfer the request content.
*
* @see NHttpServerConnection
*
* @param conn HTTP connection that contains a new HTTP request
*/
void requestReceived(NHttpServerConnection conn);
/**
* Triggered when the underlying channel is ready for reading a
* new portion of the request entity through the corresponding
* content decoder.
* <p/>
* If the content consumer is unable to process the incoming content,
* input event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpServerConnection
* @see ContentDecoder
* @see IOControl
*
* @param conn HTTP connection that can produce a new portion of the
* incoming request content.
* @param decoder The content decoder to use to read content.
*/
void inputReady(NHttpServerConnection conn, ContentDecoder decoder);
/**
* Triggered when the connection is ready to accept a new HTTP response.
* The protocol handler does not have to submit a response if it is not
* ready.
*
* @see NHttpServerConnection
*
* @param conn HTTP connection that contains an HTTP response
*/
void responseReady(NHttpServerConnection conn);
/**
* Triggered when the underlying channel is ready for writing a
* next portion of the response entity through the corresponding
* content encoder.
* <p/>
* If the content producer is unable to generate the outgoing content,
* output event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpServerConnection
* @see ContentEncoder
* @see IOControl
*
* @param conn HTTP connection that can accommodate a new portion
* of the outgoing response content.
* @param encoder The content encoder to use to write content.
*/
void outputReady(NHttpServerConnection conn, ContentEncoder encoder);
/**
* Triggered when an I/O error occurs while reading from or writing
* to the underlying channel.
*
* @param conn HTTP connection that caused an I/O error
* @param ex I/O exception
*/
void exception(NHttpServerConnection conn, IOException ex);
/**
* Triggered when an HTTP protocol violation occurs while receiving
* an HTTP request.
*
* @param conn HTTP connection that caused an HTTP protocol violation
* @param ex HTTP protocol violation exception
*/
void exception(NHttpServerConnection conn, HttpException ex);
/**
* Triggered when no input is detected on this connection over the
* maximum period of inactivity.
*
* @param conn HTTP connection that caused timeout condition.
*/
void timeout(NHttpServerConnection conn);
/**
* Triggered when the connection is closed.
*
* @param conn closed HTTP connection.
*/
void closed(NHttpServerConnection conn);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServiceHandler.java
|
Java
|
gpl3
| 4,955
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import org.apache.http.nio.reactor.IOEventDispatch;
/**
* Extended version of the {@link NHttpServerConnection} used by
* {@link IOEventDispatch} implementations to inform server-side connection
* objects of I/O events.
*
* @since 4.0
*/
public interface NHttpServerIOTarget extends NHttpServerConnection {
/**
* Triggered when the connection is ready to consume input.
*
* @param handler the server protocol handler.
*/
void consumeInput(NHttpServiceHandler handler);
/**
* Triggered when the connection is ready to produce output.
*
* @param handler the server protocol handler.
*/
void produceOutput(NHttpServiceHandler handler);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServerIOTarget.java
|
Java
|
gpl3
| 1,916
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.nio.channels.SelectionKey;
/**
* Type of I/O event notifications I/O sessions can declare interest in.
*
* @since 4.0
*/
public interface EventMask {
/**
* Interest in data input.
*/
public static final int READ = SelectionKey.OP_READ;
/**
* Interest in data output.
*/
public static final int WRITE = SelectionKey.OP_WRITE;
/**
* Interest in data input/output.
*/
public static final int READ_WRITE = READ | WRITE;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/EventMask.java
|
Java
|
gpl3
| 1,716
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
-->
</head>
<body>
API for event driven NIO based on
<a href="http://gee.cs.oswego.edu/dl/">Doug Lea</a>'s
<a href="http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf">reactor pattern</a>.
This API is not specific to HTTP communication.
However, it is minimal in the sense that it defines only
what is required within the scope of HTTP components.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/package.html
|
HTML
|
gpl3
| 1,562
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.net.SocketAddress;
import java.nio.channels.ByteChannel;
/**
* IOSession interface represents a sequence of logically related data exchanges
* between two end points.
* <p>
* The channel associated with implementations of this interface can be used to
* read data from and write data to the session.
* <p>
* I/O sessions are not bound to an execution thread, therefore one cannot use
* the context of the thread to store a session's state. All details about
* a particular session must be stored within the session itself, usually
* using execution context associated with it.
* <p>
* Implementations of this interface are expected to be threading safe.
*
* @since 4.0
*/
public interface IOSession {
/**
* Name of the context attribute key, which can be used to obtain the
* session attachment object.
*/
public static final String ATTACHMENT_KEY = "http.session.attachment";
public static final int ACTIVE = 0;
public static final int CLOSING = 1;
public static final int CLOSED = Integer.MAX_VALUE;
/**
* Returns the underlying I/O channel associated with this session.
*
* @return the I/O channel.
*/
ByteChannel channel();
/**
* Returns address of the remote peer.
*
* @return socket address.
*/
SocketAddress getRemoteAddress();
/**
* Returns local address.
*
* @return socket address.
*/
SocketAddress getLocalAddress();
/**
* Returns mask of I/O evens this session declared interest in.
*
* @return I/O event mask.
*/
int getEventMask();
/**
* Declares interest in I/O event notifications by setting the event mask
* associated with the session
*
* @param ops new I/O event mask.
*/
void setEventMask(int ops);
/**
* Declares interest in a particular I/O event type by updating the event
* mask associated with the session.
*
* @param op I/O event type.
*/
void setEvent(int op);
/**
* Clears interest in a particular I/O event type by updating the event
* mask associated with the session.
*
* @param op I/O event type.
*/
void clearEvent(int op);
/**
* Terminates the session gracefully and closes the underlying I/O channel.
* This method ensures that session termination handshake, such as the one
* used by the SSL/TLS protocol, is correctly carried out.
*/
void close();
/**
* Terminates the session by shutting down the underlying I/O channel.
*/
void shutdown();
/**
* Returns status of the session:
* <p>
* {@link #ACTIVE}: session is active.
* <p>
* {@link #CLOSING}: session is being closed.
* <p>
* {@link #CLOSED}: session has been terminated.
*
* @return session status.
*/
int getStatus();
/**
* Determines if the session has been terminated.
*
* @return <code>true</code> if the session has been terminated,
* <code>false</code> otherwise.
*/
boolean isClosed();
/**
* Returns value of the socket timeout in milliseconds. The value of
* <code>0</code> signifies the session cannot time out.
*
* @return socket timeout.
*/
int getSocketTimeout();
/**
* Sets value of the socket timeout in milliseconds. The value of
* <code>0</code> signifies the session cannot time out.
*
* @param timeout socket timeout.
*/
void setSocketTimeout(int timeout);
/**
* Quite often I/O sessions need to maintain internal I/O buffers in order
* to transform input / output data prior to returning it to the consumer or
* writing it to the underlying channel. Memory management in HttpCore NIO
* is based on the fundamental principle that the data consumer can read
* only as much input data as it can process without having to allocate more
* memory. That means, quite often some input data may remain unread in one
* of the internal or external session buffers. The I/O reactor can query
* the status of these session buffers, and make sure the consumer gets
* notified correctly as more data gets stored in one of the session
* buffers, thus allowing the consumer to read the remaining data once it
* is able to process it
* <p>
* I/O sessions can be made aware of the status of external session buffers
* using the {@link SessionBufferStatus} interface.
*
* @param status
*/
void setBufferStatus(SessionBufferStatus status);
/**
* Determines if the input buffer associated with the session contains data.
*
* @return <code>true</code> if the session input buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedInput();
/**
* Determines if the output buffer associated with the session contains
* data.
*
* @return <code>true</code> if the session output buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedOutput();
/**
* This method can be used to associate a particular object with the
* session by the given attribute name.
* <p>
* I/O sessions are not bound to an execution thread, therefore one cannot
* use the context of the thread to store a session's state. All details
* about a particular session must be stored within the session itself.
*
* @param name name of the attribute.
* @param obj value of the attribute.
*/
void setAttribute(String name, Object obj);
/**
* Returns the value of the attribute with the given name. The value can be
* <code>null</code> if not set.
* <p>
* The value of the session attachment object can be obtained using
* {@link #ATTACHMENT_KEY} name.
*
* @see #setAttribute(String, Object)
*
* @param name name of the attribute.
* @return value of the attribute.
*/
Object getAttribute(String name);
/**
* Removes attribute with the given name.
*
* @see #setAttribute(String, Object)
*
* @param name name of the attribute to be removed.
* @return value of the removed attribute.
*/
Object removeAttribute(String name);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOSession.java
|
Java
|
gpl3
| 7,585
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* SessionRequestCallback interface can be used to get notifications of
* completion of session requests asynchronously without having to wait
* for it, blocking the current thread of execution.
*
* @since 4.0
*/
public interface SessionRequestCallback {
/**
* Triggered on successful completion of a {@link SessionRequest}.
* The {@link SessionRequest#getSession()} method can now be used to obtain
* the new I/O session.
*
* @param request session request.
*/
void completed(SessionRequest request);
/**
* Triggered on unsuccessful completion a {@link SessionRequest}.
* The {@link SessionRequest#getException()} method can now be used to
* obtain the cause of the error.
*
* @param request session request.
*/
void failed(SessionRequest request);
/**
* Triggered if a {@link SessionRequest} times out.
*
* @param request session request.
*/
void timeout(SessionRequest request);
/**
* Triggered on cancellation of a {@link SessionRequest}.
*
* @param request session request.
*/
void cancelled(SessionRequest request);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequestCallback.java
|
Java
|
gpl3
| 2,393
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
/**
* HttpCore NIO is based on the Reactor pattern as described by Doug Lea.
* The purpose of I/O reactors is to react to I/O events and to dispatch event
* notifications to individual I/O sessions. The main idea of I/O reactor
* pattern is to break away from the one thread per connection model imposed
* by the classic blocking I/O model.
* <p>
* The IOReactor interface represents an abstract object implementing
* the Reactor pattern.
* <p>
* I/O reactors usually employ a small number of dispatch threads (often as
* few as one) to dispatch I/O event notifications to a much greater number
* (often as many as several thousands) of I/O sessions or connections. It is
* generally recommended to have one dispatch thread per CPU core.
*
* @since 4.0
*/
public interface IOReactor {
/**
* Returns the current status of the reactor.
*
* @return reactor status.
*/
IOReactorStatus getStatus();
/**
* Starts the reactor and initiates the dispatch of I/O event notifications
* to the given {@link IOEventDispatch}.
*
* @param eventDispatch the I/O event dispatch.
* @throws IOException in case of an I/O error.
*/
void execute(IOEventDispatch eventDispatch)
throws IOException;
/**
* Initiates shutdown of the reactor and blocks approximately for the given
* period of time in milliseconds waiting for the reactor to terminate all
* active connections, to shut down itself and to release system resources
* it currently holds.
*
* @param waitMs wait time in milliseconds.
* @throws IOException in case of an I/O error.
*/
void shutdown(long waitMs)
throws IOException;
/**
* Initiates shutdown of the reactor and blocks for a default period of
* time waiting for the reactor to terminate all active connections, to shut
* down itself and to release system resources it currently holds. It is
* up to individual implementations to decide for how long this method can
* remain blocked.
*
* @throws IOException in case of an I/O error.
*/
void shutdown()
throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactor.java
|
Java
|
gpl3
| 3,431
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* IOReactorStatus represents an internal status of an I/O reactor.
*
* @since 4.0
*/
public enum IOReactorStatus {
/**
* The reactor is inactive / has not been started
*/
INACTIVE,
/**
* The reactor is active / processing I/O events.
*/
ACTIVE,
/**
* Shutdown of the reactor has been requested.
*/
SHUTDOWN_REQUEST,
/**
* The reactor is shutting down.
*/
SHUTTING_DOWN,
/**
* The reactor has shut down.
*/
SHUT_DOWN;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorStatus.java
|
Java
|
gpl3
| 1,746
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import org.apache.http.util.CharArrayBuffer;
/**
* Session input buffer for non-blocking connections. This interface facilitates
* intermediate buffering of input data streamed from a source channel and
* reading buffered data to a destination, usually {@link ByteBuffer} or
* {@link WritableByteChannel}. This interface also provides methods for reading
* lines of text.
*
* @since 4.0
*/
public interface SessionInputBuffer {
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
boolean hasData();
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
int length();
/**
* Makes an attempt to fill the buffer with data from the given
* {@link ReadableByteChannel}.
*
* @param src the source channel
* @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
* channel has reached end-of-stream.
* @throws IOException in case of an I/O error.
*/
int fill(ReadableByteChannel src) throws IOException;
/**
* Reads one byte from the buffer. If the buffer is empty this method can
* throw a runtime exception. The exact type of runtime exception thrown
* by this method depends on implementation.
*
* @return one byte
*/
int read();
/**
* Reads a sequence of bytes from this buffer into the destination buffer,
* up to the given maximum limit. The exact number of bytes transferred
* depends on availability of data in this buffer and capacity of the
* destination buffer, but cannot be more than <code>maxLen</code> value.
*
* @param dst the destination buffer.
* @param maxLen the maximum number of bytes to be read.
* @return The number of bytes read, possibly zero.
*/
int read(ByteBuffer dst, int maxLen);
/**
* Reads a sequence of bytes from this buffer into the destination buffer.
* The exact number of bytes transferred depends on availability of data
* in this buffer and capacity of the destination buffer.
*
* @param dst the destination buffer.
* @return The number of bytes read, possibly zero.
*/
int read(ByteBuffer dst);
/**
* Reads a sequence of bytes from this buffer into the destination channel,
* up to the given maximum limit. The exact number of bytes transferred
* depends on availability of data in this buffer, but cannot be more than
* <code>maxLen</code> value.
*
* @param dst the destination channel.
* @param maxLen the maximum number of bytes to be read.
* @return The number of bytes read, possibly zero.
* @throws IOException in case of an I/O error.
*/
int read(WritableByteChannel dst, int maxLen) throws IOException;
/**
* Reads a sequence of bytes from this buffer into the destination channel.
* The exact number of bytes transferred depends on availability of data in
* this buffer.
*
* @param dst the destination channel.
* @return The number of bytes read, possibly zero.
* @throws IOException in case of an I/O error.
*/
int read(WritableByteChannel dst) throws IOException;
/**
* Attempts to transfer a complete line of characters up to a line delimiter
* from this buffer to the destination buffer. If a complete line is
* available in the buffer, the sequence of chars is transferred to the
* destination buffer the method returns <code>true</code>. The line
* delimiter itself is discarded. If a complete line is not available in
* the buffer, this method returns <code>false</code> without transferring
* anything to the destination buffer. If <code>endOfStream</code> parameter
* is set to <code>true</code> this method assumes the end of stream has
* been reached and the content currently stored in the buffer should be
* treated as a complete line.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param dst the destination buffer.
* @param endOfStream
* @return <code>true</code> if a sequence of chars representing a complete
* line has been transferred to the destination buffer, <code>false</code>
* otherwise.
*
* @throws CharacterCodingException in case a character encoding or decoding
* error occurs.
*/
boolean readLine(CharArrayBuffer dst, boolean endOfStream)
throws CharacterCodingException;
/**
* Attempts to transfer a complete line of characters up to a line delimiter
* from this buffer to a newly created string. If a complete line is
* available in the buffer, the sequence of chars is transferred to a newly
* created string. The line delimiter itself is discarded. If a complete
* line is not available in the buffer, this method returns
* <code>null</code>. If <code>endOfStream</code> parameter
* is set to <code>true</code> this method assumes the end of stream has
* been reached and the content currently stored in the buffer should be
* treated as a complete line.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param endOfStream
* @return a string representing a complete line, if available.
* <code>null</code> otherwise.
*
* @throws CharacterCodingException in case a character encoding or decoding
* error occurs.
*/
String readLine(boolean endOfStream)
throws CharacterCodingException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionInputBuffer.java
|
Java
|
gpl3
| 7,199
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
/**
* SessionRequest interface represents a request to establish a new connection
* (or session) to a remote host. It can be used to monitor the status of the
* request, to block waiting for its completion, or to cancel the request.
* <p>
* Implementations of this interface are expected to be threading safe.
*
* @since 4.0
*/
public interface SessionRequest {
/**
* Returns socket address of the remote host.
*
* @return socket address of the remote host
*/
SocketAddress getRemoteAddress();
/**
* Returns local socket address.
*
* @return local socket address.
*/
SocketAddress getLocalAddress();
/**
* Returns attachment object will be added to the session's context upon
* initialization. This object can be used to pass an initial processing
* state to the protocol handler.
*
* @return attachment object.
*/
Object getAttachment();
/**
* Determines whether the request has been completed (either successfully
* or unsuccessfully).
*
* @return <code>true</true> if the request has been completed,
* <code>false</true> if still pending.
*/
boolean isCompleted();
/**
* Returns {@link IOSession} instance created as a result of this request
* or <code>null</code> if the request is still pending.
*
* @return I/O session or <code>null</code> if the request is still pending.
*/
IOSession getSession();
/**
* Returns {@link IOException} instance if the request could not be
* successfully executed due to an I/O error or <code>null</code> if no
* error occurred to this point.
*
* @return I/O exception or <code>null</code> if no error occurred to
* this point.
*/
IOException getException();
/**
* Waits for completion of this session request.
*
* @throws InterruptedException in case the execution process was
* interrupted.
*/
void waitFor() throws InterruptedException;
/**
* Sets connect timeout value in milliseconds.
*
* @param timeout connect timeout value in milliseconds.
*/
void setConnectTimeout(int timeout);
/**
* Returns connect timeout value in milliseconds.
*
* @return connect timeout value in milliseconds.
*/
int getConnectTimeout();
/**
* Cancels the request. Invocation of this method will set the status of
* the request to completed and will unblock threads blocked in
* the {{@link #waitFor()}} method.
*/
void cancel();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequest.java
|
Java
|
gpl3
| 3,881
|
/*
* $Date:
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* SessionBufferStatus interface is intended to query the status of session
* I/O buffers.
*
* @since 4.0
*/
public interface SessionBufferStatus {
/**
* Determines if the session input buffer contains data.
*
* @return <code>true</code> if the session input buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedInput();
/**
* Determines if the session output buffer contains data.
*
* @return <code>true</code> if the session output buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedOutput();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionBufferStatus.java
|
Java
|
gpl3
| 1,862
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
/**
* Abstract exception handler intended to deal with potentially recoverable
* I/O exceptions thrown by an I/O reactor.
*
* @since 4.0
*/
public interface IOReactorExceptionHandler {
/**
* This method is expected to examine the I/O exception passed as
* a parameter and decide whether it is safe to continue execution of
* the I/O reactor.
*
* @param ex potentially recoverable I/O exception
* @return <code>true</code> if it is safe to ignore the exception
* and continue execution of the I/O reactor; <code>false</code> if the
* I/O reactor must throw {@link IOReactorException} and terminate
*/
boolean handle(IOException ex);
/**
* This method is expected to examine the runtime exception passed as
* a parameter and decide whether it is safe to continue execution of
* the I/O reactor.
*
* @param ex potentially recoverable runtime exception
* @return <code>true</code> if it is safe to ignore the exception
* and continue execution of the I/O reactor; <code>false</code> if the
* I/O reactor must throw {@link RuntimeException} and terminate
*/
boolean handle(RuntimeException ex);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorExceptionHandler.java
|
Java
|
gpl3
| 2,458
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.net.SocketAddress;
/**
* ConnectingIOReactor represents an I/O reactor capable of establishing
* connections to remote hosts.
*
* @since 4.0
*/
public interface ConnectingIOReactor extends IOReactor {
/**
* Requests a connection to a remote host.
* <p>
* Opening a connection to a remote host usually tends to be a time
* consuming process and may take a while to complete. One can monitor and
* control the process of session initialization by means of the
* {@link SessionRequest} interface.
* <p>
* There are several parameters one can use to exert a greater control over
* the process of session initialization:
* <p>
* A non-null local socket address parameter can be used to bind the socket
* to a specific local address.
* <p>
* An attachment object can added to the new session's context upon
* initialization. This object can be used to pass an initial processing
* state to the protocol handler.
* <p>
* It is often desirable to be able to react to the completion of a session
* request asynchronously without having to wait for it, blocking the
* current thread of execution. One can optionally provide an implementation
* {@link SessionRequestCallback} instance to get notified of events related
* to session requests, such as request completion, cancellation, failure or
* timeout.
*
* @param remoteAddress the socket address of the remote host.
* @param localAddress the local socket address. Can be <code>null</code>,
* in which can the default local address and a random port will be used.
* @param attachment the attachment object. Can be <code>null</code>.
* @param callback interface. Can be <code>null</code>.
* @return session request object.
*/
SessionRequest connect(
SocketAddress remoteAddress,
SocketAddress localAddress,
Object attachment,
SessionRequestCallback callback);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ConnectingIOReactor.java
|
Java
|
gpl3
| 3,260
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* IOEventDispatch interface is used by I/O reactors to notify clients of I/O
* events pending for a particular session. All methods of this interface are
* executed on a dispatch thread of the I/O reactor. Therefore, it is important
* that processing that takes place in the event methods will not block the
* dispatch thread for too long, as the I/O reactor will be unable to react to
* other events.
*
* @since 4.0
*/
public interface IOEventDispatch {
/**
* Triggered after the given session has been just created.
*
* @param session the I/O session.
*/
void connected(IOSession session);
/**
* Triggered when the given session has input pending.
*
* @param session the I/O session.
*/
void inputReady(IOSession session);
/**
* Triggered when the given session is ready for output.
*
* @param session the I/O session.
*/
void outputReady(IOSession session);
/**
* Triggered when the given session as timed out.
*
* @param session the I/O session.
*/
void timeout(IOSession session);
/**
* Triggered when the given session has been terminated.
*
* @param session the I/O session.
*/
void disconnected(IOSession session);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOEventDispatch.java
|
Java
|
gpl3
| 2,507
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
/**
* I/O exception that can be thrown by an I/O reactor. Usually exceptions
* of this type are fatal and are not recoverable.
*
* @since 4.0
*/
public class IOReactorException extends IOException {
private static final long serialVersionUID = -4248110651729635749L;
public IOReactorException(final String message, final Exception cause) {
super(message);
if (cause != null) {
initCause(cause);
}
}
public IOReactorException(final String message) {
super(message);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorException.java
|
Java
|
gpl3
| 1,794
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.net.SocketAddress;
import java.util.Set;
import java.io.IOException;
/**
* ListeningIOReactor represents an I/O reactor capable of listening for
* incoming connections on one or several ports.
*
* @since 4.0
*/
public interface ListeningIOReactor extends IOReactor {
/**
* Opens a new listener endpoint with the given socket address. Once
* the endpoint is fully initialized it starts accepting incoming
* connections and propagates I/O activity notifications to the I/O event
* dispatcher.
* <p>
* {@link ListenerEndpoint#waitFor()} can be used to wait for the
* listener to be come ready to accept incoming connections.
* <p>
* {@link ListenerEndpoint#close()} can be used to shut down
* the listener even before it is fully initialized.
*
* @param address the socket address to listen on.
* @return listener endpoint.
*/
ListenerEndpoint listen(SocketAddress address);
/**
* Suspends the I/O reactor preventing it from accepting new connections on
* all active endpoints.
*
* @throws IOException in case of an I/O error.
*/
void pause()
throws IOException;
/**
* Resumes the I/O reactor restoring its ability to accept incoming
* connections on all active endpoints.
*
* @throws IOException in case of an I/O error.
*/
void resume()
throws IOException;
/**
* Returns a set of endpoints for this I/O reactor.
*
* @return set of endpoints.
*/
Set<ListenerEndpoint> getEndpoints();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListeningIOReactor.java
|
Java
|
gpl3
| 2,819
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
/**
* ListenerEndpoint interface represents an endpoint used by an I/O reactor
* to listen for incoming connection from remote clients.
*
* @since 4.0
*/
public interface ListenerEndpoint {
/**
* Returns the socket address of this endpoint.
*
* @return socket address.
*/
SocketAddress getAddress();
/**
* Returns an instance of {@link IOException} thrown during initialization
* of this endpoint or <code>null</code>, if initialization was successful.
*
* @return I/O exception object or <code>null</code>.
*/
IOException getException();
/**
* Waits for completion of initialization process of this endpoint.
*
* @throws InterruptedException in case the initialization process was
* interrupted.
*/
void waitFor() throws InterruptedException;
/**
* Determines if this endpoint has been closed and is no longer listens
* for incoming connections.
*
* @return <code>true</code> if the endpoint has been closed,
* <code>false</code> otherwise.
*/
boolean isClosed();
/**
* Closes this endpoint. The endpoint will stop accepting incoming
* connection.
*/
void close();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListenerEndpoint.java
|
Java
|
gpl3
| 2,521
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import org.apache.http.util.CharArrayBuffer;
/**
* Session output buffer for non-blocking connections. This interface
* facilitates intermediate buffering of output data streamed out to
* a destination channel and writing data to the buffer from a source, usually
* {@link ByteBuffer} or {@link ReadableByteChannel}. This interface also
* provides methods for writing lines of text.
*
* @since 4.0
*/
public interface SessionOutputBuffer {
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
boolean hasData();
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
int length();
/**
* Makes an attempt to flush the content of this buffer to the given
* destination {@link WritableByteChannel}.
*
* @param channel the destination channel.
* @return The number of bytes written, possibly zero.
* @throws IOException in case of an I/O error.
*/
int flush(WritableByteChannel channel)
throws IOException;
/**
* Copies content of the source buffer into this buffer. The capacity of
* the destination will be expanded in order to accommodate the entire
* content of the source buffer.
*
* @param src the source buffer.
*/
void write(ByteBuffer src);
/**
* Reads a sequence of bytes from the source channel into this buffer.
*
* @param src the source channel.
*/
void write(ReadableByteChannel src)
throws IOException;
/**
* Copies content of the source buffer into this buffer as one line of text
* including a line delimiter. The capacity of the destination will be
* expanded in order to accommodate the entire content of the source buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param src the source buffer.
*/
void writeLine(CharArrayBuffer src)
throws CharacterCodingException;
/**
* Copies content of the given string into this buffer as one line of text
* including a line delimiter.
* The capacity of the destination will be expanded in order to accommodate
* the entire string.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param s the string.
*/
void writeLine(String s)
throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionOutputBuffer.java
|
Java
|
gpl3
| 4,034
|
ant clean; ant release; adb install -r bin/MetaTracker-release.apk
|
zzy157-running
|
MetaTracker/application/build-install.sh
|
Shell
|
gpl3
| 67
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.content.SharedPreferences;
import android.location.Location;
import org.opentraces.metatracker.Constants;
public class TrackingState
{
public int loggingState;
public boolean newRoadRating;
public int roadRating;
public float distance;
public Track track = new Track();
public Segment segment = new Segment();
public Waypoint waypoint = new Waypoint();
private SharedPreferences sharedPreferences;
public TrackingState(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
reset();
}
public void load()
{
distance = sharedPreferences.getFloat("distance", 0.0f);
track.load();
waypoint.load();
}
public void save()
{
sharedPreferences.edit().putFloat("distance", distance).commit();
track.save();
waypoint.save();
}
public void reset()
{
loggingState = Constants.DOWN;
distance = 0.0f;
waypoint.reset();
track.reset();
}
public class Track
{
public int id = -1;
public String name = "NO TRACK";
public long creationTime;
public void load()
{
id = sharedPreferences.getInt("track.id", -1);
name = sharedPreferences.getString("track.name", "NO TRACK");
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("track.id", id);
editor.putString("track.name", name);
editor.commit();
}
public void reset()
{
name = "NO TRACK";
id = -1;
}
}
public static class Segment
{
public int id = -1;
}
public class Waypoint
{
public int id = -1;
public Location location;
public float speed;
public float accuracy;
public int count;
public void load()
{
id = sharedPreferences.getInt("waypoint.id", -1);
count = sharedPreferences.getInt("waypoint.count", 0);
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("waypoint.id", id);
editor.putInt("waypoint.count", count);
editor.commit();
}
public void reset()
{
count = 0;
id = -1;
location = null;
}
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/activity/TrackingState.java
|
Java
|
gpl3
| 2,800
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.Constants;
import org.opentraces.metatracker.R;
import org.opentraces.metatracker.net.OpenTracesClient;
public class UploadTrackActivity extends Activity
{
protected static final int DIALOG_FILENAME = 11;
protected static final int PROGRESS_STEPS = 10;
private static final int DIALOG_INSTALL_FILEMANAGER = 34;
private static final String TAG = "MT.UploadTrack";
private String filePath;
private TextView fileNameView;
private SharedPreferences sharedPreferences;
private final DialogInterface.OnClickListener mFileManagerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager");
Intent oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiFileManagerDownloadIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk");
oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiFileManagerDownloadIntent);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.uploaddialog);
fileNameView = (TextView) findViewById(R.id.filename);
filePath = null;
pickFile();
Button okay = (Button) findViewById(R.id.okayupload_button);
okay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (filePath == null) {
return;
}
uploadFile(filePath);
}
});
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_FILEMANAGER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nofilemanager)
.setMessage(R.string.dialog_nofilemanager_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mFileManagerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
// Bundle extras = intent.getExtras();
switch (requestCode)
{
case Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY:
if (resultCode == RESULT_OK && intent != null)
{
// obtain the filename
filePath = intent.getDataString();
if (filePath != null)
{
// Get rid of URI prefix:
if (filePath.startsWith("file://"))
{
filePath = filePath.substring(7);
}
fileNameView.setText(filePath);
}
}
break;
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void pickFile()
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
} catch (ActivityNotFoundException e)
{
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_FILEMANAGER);
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void uploadFile(String aFilePath)
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
;
OpenTracesClient openTracesClient = new OpenTracesClient(sharedPreferences.getString(Constants.PREF_SERVER_URL, "http://geotracing.com/tland"));
openTracesClient.createSession();
openTracesClient.login(sharedPreferences.getString(Constants.PREF_SERVER_USER, "no_user"), sharedPreferences.getString(Constants.PREF_SERVER_PASSWORD, "no_passwd"));
openTracesClient.uploadFile(aFilePath);
openTracesClient.logout();
} catch (Throwable e)
{
Log.e(TAG, "Error uploading file : ", e);
}
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/activity/UploadTrackActivity.java
|
Java
|
gpl3
| 6,069
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import org.opentraces.metatracker.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
/**
* Dialog for setting preferences.
*
* @author Just van den Broecke
*/
public class SettingsActivity extends PreferenceActivity
{
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
addPreferencesFromResource( R.layout.settings );
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/activity/SettingsActivity.java
|
Java
|
gpl3
| 1,187
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.*;
import android.content.*;
import android.database.ContentObserver;
import android.database.Cursor;
import android.location.Location;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.*;
import org.opentraces.metatracker.logger.GPSLoggerServiceManager;
import java.text.DecimalFormat;
public class MainActivity extends Activity
{
// MENU'S
private static final int MENU_SETTINGS = 1;
private static final int MENU_TRACKING = 2;
private static final int MENU_UPLOAD = 3;
private static final int MENU_HELP = 4;
private static final int MENU_ABOUT = 5;
private static final int DIALOG_INSTALL_OPENGPSTRACKER = 1;
private static final int DIALOG_INSTALL_ABOUT = 2;
private static DecimalFormat REAL_FORMATTER1 = new DecimalFormat("0.#");
private static DecimalFormat REAL_FORMATTER2 = new DecimalFormat("0.##");
private static final String TAG = "MetaTracker.Main";
private TextView waypointCountView, timeView, distanceView, speedView, roadRatingView, accuracyView;
private GPSLoggerServiceManager loggerServiceManager;
private TrackingState trackingState;
private MediaPlayer mediaPlayer;
// private PowerManager.WakeLock wakeLock = null;
private static final int COLOR_WHITE = 0xFFFFFFFF;
private static final int[] ROAD_RATING_COLORS = {0xFF808080, 0xFFCC0099, 0xFFEE0000, 0xFFFF6600, 0xFFFFCC00, 0xFF33CC33};
private SharedPreferences sharedPreferences;
private Button[] roadRatingButtons = new Button[6];
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
trackingState = new TrackingState(sharedPreferences);
trackingState.load();
setContentView(R.layout.main);
getLastTrackingState();
getApplicationContext().getContentResolver().registerContentObserver(Constants.Tracks.CONTENT_URI, true, trackingObserver);
// mUnits = new UnitsI18n(this, mUnitsChangeListener);
speedView = (TextView) findViewById(R.id.currentSpeed);
timeView = (TextView) findViewById(R.id.currentTime);
distanceView = (TextView) findViewById(R.id.totalDist);
waypointCountView = (TextView) findViewById(R.id.waypointCount);
accuracyView = (TextView) findViewById(R.id.currentAccuracy);
roadRatingView = (TextView) findViewById(R.id.currentRoadRating);
// Capture our button from layout
roadRatingButtons[0] = (Button) findViewById(R.id.road_qual_none);
roadRatingButtons[1] = (Button) findViewById(R.id.road_qual_nogo);
roadRatingButtons[2] = (Button) findViewById(R.id.road_qual_bad);
roadRatingButtons[3] = (Button) findViewById(R.id.road_qual_poor);
roadRatingButtons[4] = (Button) findViewById(R.id.road_qual_good);
roadRatingButtons[5] = (Button) findViewById(R.id.road_qual_best);
for (Button button : roadRatingButtons)
{
button.setOnClickListener(roadRatingButtonListener);
}
bindGPSLoggingService();
}
/**
* Called when the activity is started.
*/
@Override
public void onStart()
{
Log.d(TAG, "onStart()");
super.onStart();
}
/**
* Called when the activity is started.
*/
@Override
public void onRestart()
{
Log.d(TAG, "onRestart()");
super.onRestart();
}
/**
* Called when the activity is resumed.
*/
@Override
public void onResume()
{
Log.d(TAG, "onResume()");
getLastTrackingState();
// updateBlankingBehavior();
drawScreen();
super.onResume();
}
/**
* Called when the activity is paused.
*/
@Override
public void onPause()
{
trackingState.save();
/* if (this.wakeLock != null && this.wakeLock.isHeld())
{
this.wakeLock.release();
Log.w(TAG, "onPause(): Released lock to keep screen on!");
} */
Log.d(TAG, "onPause()");
super.onPause();
}
@Override
protected void onDestroy()
{
Log.d(TAG, "onDestroy()");
trackingState.save();
/* if (wakeLock != null && wakeLock.isHeld())
{
wakeLock.release();
Log.w(TAG, "onDestroy(): Released lock to keep screen on!");
} */
getApplicationContext().getContentResolver().unregisterContentObserver(trackingObserver);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this.sharedPreferenceChangeListener);
unbindGPSLoggingService();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T');
menu.add(ContextMenu.NONE, MENU_UPLOAD, ContextMenu.NONE, R.string.menu_upload).setIcon(R.drawable.ic_menu_upload).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C');
menu.add(ContextMenu.NONE, MENU_HELP, ContextMenu.NONE, R.string.menu_help).setIcon(R.drawable.ic_menu_help).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A');
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MENU_TRACKING:
startOpenGPSTrackerActivity();
break;
case MENU_UPLOAD:
startActivityForClass("org.opentraces.metatracker", "org.opentraces.metatracker.activity.UploadTrackActivity");
break;
case MENU_SETTINGS:
startActivity(new Intent(this, SettingsActivity.class));
break;
case MENU_ABOUT:
try
{
startActivityForResult(new Intent(Constants.OI_ACTION_SHOW_ABOUT_DIALOG), MENU_ABOUT);
}
catch (ActivityNotFoundException e)
{
showDialog(DIALOG_INSTALL_ABOUT);
}
break;
default:
showAlert(R.string.menu_message_unsupported);
break;
}
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
AlertDialog.Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_OPENGPSTRACKER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_noopengpstracker)
.setMessage(R.string.dialog_noopengpstracker_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOpenGPSTrackerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
case DIALOG_INSTALL_ABOUT:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nooiabout)
.setMessage(R.string.dialog_nooiabout_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOiAboutDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
private void drawTitleBar(String s)
{
this.setTitle(s);
}
/**
* Called on any update to Tracks table.
*/
private void onTrackingUpdate()
{
getLastTrackingState();
if (trackingState.waypoint.count == 1)
{
sendRoadRating();
}
drawScreen();
}
/**
* Called on any update to Tracks table.
*/
private synchronized void playPingSound()
{
if (!sharedPreferences.getBoolean(Constants.PREF_ENABLE_SOUND, false)) {
return;
}
try
{
if (mediaPlayer == null)
{
mediaPlayer = MediaPlayer.create(this, R.raw.ping_short);
} else
{
mediaPlayer.stop();
mediaPlayer.prepare();
}
mediaPlayer.start();
} catch (Throwable t)
{
Log.e(TAG, "Error playing sound", t);
}
}
/**
* Retrieve the last point of the current track
*/
private void getLastWaypoint()
{
Cursor waypoint = null;
try
{
ContentResolver resolver = this.getContentResolver();
waypoint = resolver.query(Uri.withAppendedPath(Constants.Tracks.CONTENT_URI, trackingState.track.id + "/" + Constants.Waypoints.TABLE),
new String[]{"max(" + Constants.Waypoints.TABLE + "." + Constants.Waypoints._ID + ")", Constants.Waypoints.LONGITUDE, Constants.Waypoints.LATITUDE, Constants.Waypoints.SPEED, Constants.Waypoints.ACCURACY, Constants.Waypoints.SEGMENT
}, null, null, null);
if (waypoint != null && waypoint.moveToLast())
{
// New point: increase pointcount
int waypointId = waypoint.getInt(0);
if (waypointId > 0 && trackingState.waypoint.id != waypointId)
{
trackingState.waypoint.count++;
trackingState.waypoint.id = waypoint.getInt(0);
// Increase total distance
Location newLocation = new Location(this.getClass().getName());
newLocation.setLongitude(waypoint.getDouble(1));
newLocation.setLatitude(waypoint.getDouble(2));
if (trackingState.waypoint.location != null)
{
float delta = trackingState.waypoint.location.distanceTo(newLocation);
// Log.d(TAG, "trackingState.distance=" + trackingState.distance + " delta=" + delta + " ll=" + waypoint.getDouble(1) + ", " +waypoint.getDouble(2));
trackingState.distance += delta;
}
trackingState.waypoint.location = newLocation;
trackingState.waypoint.speed = waypoint.getFloat(3);
trackingState.waypoint.accuracy = waypoint.getFloat(4);
trackingState.segment.id = waypoint.getInt(5);
playPingSound();
}
}
}
finally
{
if (waypoint != null)
{
waypoint.close();
}
}
}
private void getLastTrack()
{
Cursor cursor = null;
try
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
cursor = resolver.query(Constants.Tracks.CONTENT_URI, new String[]{"max(" + Constants.Tracks._ID + ")", Constants.Tracks.NAME, Constants.Tracks.CREATION_TIME}, null, null, null);
if (cursor != null && cursor.moveToLast())
{
int trackId = cursor.getInt(0);
// Check if new track created
if (trackId != trackingState.track.id)
{
trackingState.reset();
trackingState.save();
}
trackingState.track.id = trackId;
trackingState.track.name = cursor.getString(1);
trackingState.track.creationTime = cursor.getLong(2);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
private void getLastTrackingState()
{
getLastTrack();
getLoggingState();
getLastWaypoint();
}
private void sendRoadRating()
{
if (trackingState.roadRating > 0 && trackingState.newRoadRating && loggerServiceManager != null)
{
Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(trackingState.roadRating + ""));
loggerServiceManager.storeMediaUri(media);
trackingState.newRoadRating = false;
}
}
private void startOpenGPSTrackerActivity()
{
try
{
startActivityForClass("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.viewer.LoggerMap");
}
catch (ActivityNotFoundException e)
{
Log.i(TAG, "Cannot find activity for open-gpstracker");
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_OPENGPSTRACKER);
}
sendRoadRating();
}
private void startActivityForClass(String aPackageName, String aClassName) throws ActivityNotFoundException
{
Intent intent = new Intent();
intent.setClassName(aPackageName, aClassName);
startActivity(intent);
}
private void bindGPSLoggingService()
{
unbindGPSLoggingService();
ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
getLoggingState();
drawTitleBar();
}
public void onServiceDisconnected(ComponentName className)
{
trackingState.loggingState = Constants.DOWN;
}
};
loggerServiceManager = new GPSLoggerServiceManager(this);
loggerServiceManager.startup(serviceConnection);
}
private void unbindGPSLoggingService()
{
if (loggerServiceManager == null)
{
return;
}
try
{
loggerServiceManager.shutdown();
} finally
{
loggerServiceManager = null;
trackingState.loggingState = Constants.DOWN;
}
}
private void getLoggingState()
{
// Get state from logger if bound
trackingState.loggingState = loggerServiceManager == null ? Constants.DOWN : loggerServiceManager.getLoggingState();
// protect for values outside array bounds (set to unknown)
if (trackingState.loggingState < 0 || trackingState.loggingState > Constants.LOGGING_STATES.length - 1)
{
trackingState.loggingState = Constants.UNKNOWN;
}
}
private String getLoggingStateStr()
{
return Constants.LOGGING_STATES[trackingState.loggingState];
}
private void drawTitleBar()
{
drawTitleBar("MT : " + trackingState.track.name + " : " + getLoggingStateStr());
}
private void drawScreen()
{
drawTitleBar();
drawTripStats();
drawRoadRating();
}
/**
* Retrieves the numbers of the measured speed and altitude
* from the most recent waypoint and
* updates UI components with this latest bit of information.
*/
private void drawTripStats()
{
try
{
waypointCountView.setText(trackingState.waypoint.count + "");
long secsDelta = 0L;
long hours = 0L;
long mins = 0L;
long secs = 0L;
if (trackingState.track.creationTime != 0)
{
secsDelta = (System.currentTimeMillis() - trackingState.track.creationTime) / 1000;
hours = secsDelta / 3600L;
mins = (secsDelta % 3600L) / 60L;
secs = ((secsDelta % 3600L) % 60);
}
timeView.setText(formatTimeNum(hours) + ":" + formatTimeNum(mins) + ":" + formatTimeNum(secs));
speedView.setText(REAL_FORMATTER1.format(3.6f * trackingState.waypoint.speed));
accuracyView.setText(REAL_FORMATTER1.format(trackingState.waypoint.accuracy));
distanceView.setText(REAL_FORMATTER2.format(trackingState.distance / 1000f));
}
finally
{
}
}
private String formatTimeNum(long n)
{
return n < 10 ? ("0" + n) : (n + "");
}
private void drawRoadRating()
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
roadRatingButtons[i].setBackgroundColor(COLOR_WHITE);
}
if (trackingState.roadRating >= 0)
{
roadRatingButtons[trackingState.roadRating].setBackgroundColor(ROAD_RATING_COLORS[trackingState.roadRating]);
}
String roadRatingStr = trackingState.roadRating + "";
roadRatingView.setText(roadRatingStr);
}
private void showAlert(int aMessage)
{
new AlertDialog.Builder(this)
.setMessage(aMessage)
.setPositiveButton("Ok", null)
.show();
}
private void updateBlankingBehavior()
{
boolean disableblanking = sharedPreferences.getBoolean(Constants.DISABLEBLANKING, false);
if (disableblanking)
{
/* if (wakeLock == null)
{
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
}
wakeLock.acquire();
Log.w(TAG, "Acquired lock to keep screen on!"); */
}
}
private final DialogInterface.OnClickListener mOiAboutDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.about");
Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiAboutIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/AboutApp-1.0.0.apk");
oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiAboutIntent);
}
}
};
private final DialogInterface.OnClickListener mOpenGPSTrackerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri marketUri = Uri.parse("market://details?id=nl.sogeti.android.gpstracker");
Intent downloadIntent = new Intent(Intent.ACTION_VIEW, marketUri);
try
{
startActivity(downloadIntent);
}
catch (ActivityNotFoundException e)
{
showAlert(R.string.dialog_failinstallopengpstracker_message);
}
}
};
// Create an anonymous implementation of OnClickListener
private View.OnClickListener roadRatingButtonListener = new View.OnClickListener()
{
public void onClick(View v)
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
if (v.getId() == roadRatingButtons[i].getId())
{
trackingState.roadRating = i;
}
}
trackingState.newRoadRating = true;
drawRoadRating();
sendRoadRating();
}
};
private final ContentObserver trackingObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
onTrackingUpdate();
Log.d(TAG, "trackingObserver onTrackingUpdate lastWaypointId=" + trackingState.waypoint.id);
} else
{
Log.w(TAG, "trackingObserver skipping change");
}
}
};
private final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(Constants.DISABLEBLANKING))
{
updateBlankingBehavior();
}
}
};
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/activity/MainActivity.java
|
Java
|
gpl3
| 18,582
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* Implements a Visitor that does nothin'
* $Id: DefaultVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class DefaultVisitor implements Visitor
{
public void visitDocumentPre(Document document)
{
}
public void visitDocumentPost(Document document)
{
}
public void visitElementPre(Element element)
{
}
public void visitElementPost(Element element)
{
}
public void visitText(Text element)
{
}
}
/*
* $Log: DefaultVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/xml/DefaultVisitor.java
|
Java
|
gpl3
| 1,669
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Makes deep copy of an Element for another Document.
* $Id: ElementCopyVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class ElementCopyVisitor extends DefaultVisitor
{
Document ownerDocument;
Element elementOrig;
Element elementCopy;
Element elementPointer;
int level = 0;
public ElementCopyVisitor(Document theOwnerDocument, Element theElement)
{
ownerDocument = theOwnerDocument;
elementOrig = theElement;
}
public Element getCopy()
{
new TreeWalker(this).traverse(elementOrig);
return elementCopy;
}
public void visitDocumentPre(Document document)
{
p("visitDocumentPre: level=" + level);
}
public void visitDocumentPost(Document document)
{
p("visitDocumentPost: level=" + level);
}
public void visitElementPre(Element element)
{
p("visitElementPre: " + element.getTagName() + " level=" + level);
// Create the copy; must use target document as factory
Element newElement = ownerDocument.createElement(element.getTagName());
// If first time we need to create the copy
if (elementCopy == null)
{
elementCopy = newElement;
} else
{
elementPointer.appendChild(newElement);
}
// Always point to the last created and appended element
elementPointer = newElement;
level++;
}
public void visitElementPost(Element element)
{
p("visitElementPost: " + element.getTagName() + " level=" + level);
DOMUtil.copyAttributes(element, elementPointer);
level--;
if (level == 0) return;
// Always transfer attributes if any
if (level > 0)
{
elementPointer = (Element) elementPointer.getParentNode();
}
}
public void visitText(Text element)
{
// Create the copy; must use target document as factory
Text newText = ownerDocument.createTextNode(element.getData());
// If first time we need to create the copy
if (elementPointer == null)
{
p("ERROR no element copy");
return;
} else
{
elementPointer.appendChild(newText);
}
}
private void p(String s)
{
//System.out.println("ElementCopyVisitor: "+s);
}
}
/*
* $Log: ElementCopyVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/xml/ElementCopyVisitor.java
|
Java
|
gpl3
| 3,342
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Utility methods for working with a DOM tree.
* $Id: DOMUtil.java,v 1.18 2004/09/10 14:20:50 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class DOMUtil
{
/**
* Clears all childnodes in document
*/
public static void clearDocument(Document document)
{
NodeList nodeList = document.getChildNodes();
if (nodeList == null)
{
return;
}
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
document.removeChild(nodeList.item(i));
}
}
/**
* Create empty document TO BE DEBUGGED!.
*/
public static Document createDocument()
{
DocumentBuilder documentBuilder = null;
// System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
try
{
documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException pce)
{
warn("ParserConfigurationException: " + pce);
return null;
}
return documentBuilder.newDocument();
}
/**
* Copies all attributes from one element to another in the official way.
*/
public static void copyAttributes(Element elementFrom, Element elementTo)
{
NamedNodeMap nodeList = elementFrom.getAttributes();
if (nodeList == null)
{
// No attributes to copy: just return
return;
}
Attr attrFrom = null;
Attr attrTo = null;
// Needed as factory to create attrs
Document documentTo = elementTo.getOwnerDocument();
int len = nodeList.getLength();
// Copy each attr by making/setting a new one and
// adding to the target element.
for (int i = 0; i < len; i++)
{
attrFrom = (Attr) nodeList.item(i);
// Create an set value
attrTo = documentTo.createAttribute(attrFrom.getName());
attrTo.setValue(attrFrom.getValue());
// Set in target element
elementTo.setAttributeNode(attrTo);
}
}
public static Element getFirstElementByTagName(Document document, String tag)
{
// Get all elements matching the tagname
NodeList nodeList = document.getElementsByTagName(tag);
if (nodeList == null)
{
p("no list of elements with tag=" + tag);
return null;
}
// Get the first if any.
Element element = (Element) nodeList.item(0);
if (element == null)
{
p("no element for tag=" + tag);
return null;
}
return element;
}
public static Element getElementById(Document document, String id)
{
return getElementById(document.getDocumentElement(), id);
}
public static Element getElementById(Element element, String id)
{
return getElementById(element.getChildNodes(), id);
}
/**
* Get Element that has attribute id="xyz".
*/
public static Element getElementById(NodeList nodeList, String id)
{
// Note we should really use the Query here !!
Element element = null;
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
Node node = (Node) nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
element = (Element) node;
if (((Element) node).getAttribute("id").equals(id))
{
// found it !
break;
}
}
}
// returns found element or null
return element;
}
public static Document parse(InputStream anInputStream)
{
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(anInputStream);
} catch (Exception e)
{
throw new RuntimeException(e);
}
return document;
}
/**
* Prints an XML DOM.
*/
public static void printAsXML(Document document, PrintWriter printWriter)
{
new TreeWalker(new XMLPrintVisitor(printWriter)).traverse(document);
}
/**
* Prints an XML DOM.
*/
public static String dom2String(Document document)
{
StringWriter sw = new StringWriter();
DOMUtil.printAsXML(document, new PrintWriter(sw));
return sw.toString();
}
/**
* Replaces an element in document.
*/
public static void replaceElement(Element newElement, Element oldElement)
{
// Must be 1
Node parent = oldElement.getParentNode();
if (parent == null)
{
warn("replaceElement: no parent of oldElement found");
return;
}
// Create a copy owned by the document
ElementCopyVisitor ecv = new ElementCopyVisitor(oldElement.getOwnerDocument(), newElement);
Element newElementCopy = ecv.getCopy();
// Replace the old element with the new copy
parent.replaceChild(newElementCopy, oldElement);
}
/**
* Write Document structure to XML file.
*/
static public void document2File(Document document, String fileName)
{
new TreeWalker(new XMLPrintVisitor(fileName)).traverse(document);
}
public static void warn(String s)
{
p("DOMUtil: WARNING " + s);
}
public static void p(String s)
{
// System.out.println("DOMUtil: "+s);
}
}
/*
* $Log: DOMUtil.java,v $
* Revision 1.18 2004/09/10 14:20:50 just
* expandIncludes() tab to 2 spaces
*
* Revision 1.17 2004/09/10 12:48:11 just
* ok
*
* Revision 1.16 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.15 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.14 2002/06/18 10:30:02 just
* no rel change
*
* Revision 1.13 2001/08/01 15:20:23 kstroke
* fix for expand includes (added rootDir)
*
* Revision 1.12 2001/02/17 14:28:16 just
* added comments and changed interface for expandIds()
*
* Revision 1.11 2000/12/09 14:35:35 just
* added parse() method with optional DTD validation
*
* Revision 1.10 2000/09/21 22:37:20 just
* removed print statements
*
* Revision 1.9 2000/08/28 00:07:46 just
* changes for introduction of EntityResolverImpl
*
* Revision 1.8 2000/08/24 10:11:12 just
* added XML file verfication
*
* Revision 1.7 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/xml/DOMUtil.java
|
Java
|
gpl3
| 7,126
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This interface specifies the callbacks from the TreeWalker.
* $Id: Visitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Callback methods from the TreeWalker.
*/
public interface Visitor
{
public void visitDocumentPre(Document document);
public void visitDocumentPost(Document document);
public void visitElementPre(Element element);
public void visitElementPost(Element element);
public void visitText(Text element);
}
/*
* $Log: Visitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/xml/Visitor.java
|
Java
|
gpl3
| 1,671
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This class does a pre-order walk of a DOM tree or Node, calling an ElementVisitor
* interface as it goes.
* <p>The numbered nodes in the trees below indicate the order of traversal given
* the specified <code>startNode</code> of "1".
* <pre>
*
* 1 x x
* / \ / \ / \
* 2 6 1 x x x
* /|\ \ /|\ \ /|\ \
* 3 4 5 7 2 3 4 x x 1 x x
*
* </pre>
* $Id: TreeWalker.java,v 1.5 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
public class TreeWalker
{
private Visitor visitor;
private Node topNode;
/**
* Constructor.
*
* @param
*/
public TreeWalker(Visitor theVisitor)
{
visitor = theVisitor;
}
/**
* Disabled default constructor.
*/
private TreeWalker()
{
}
/**
* Perform a pre-order traversal non-recursive style.
*/
public void traverse(Node node)
{
// Remember the top node
if (topNode == null)
{
topNode = node;
}
while (node != null)
{
visitPre(node);
Node nextNode = node.getFirstChild();
while (nextNode == null)
{
visitPost(node);
// We are ready after post-visiting the topnode
if (node == topNode)
{
return;
}
try
{
nextNode = node.getNextSibling();
}
catch (IndexOutOfBoundsException e)
{
nextNode = null;
}
if (nextNode == null)
{
node = node.getParentNode();
if (node == null)
{
nextNode = node;
break;
}
}
}
node = nextNode;
}
}
protected void visitPre(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPre((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPre((Element) node);
break;
case Node.TEXT_NODE:
visitor.visitText((Text) node);
break;
// Not yet
case Node.ENTITY_REFERENCE_NODE:
System.out.println("ENTITY_REFERENCE_NODE");
default:
break;
}
}
protected void visitPost(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPost((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPost((Element) node);
break;
case Node.TEXT_NODE:
break;
default:
break;
}
}
}
/*
* $Log: TreeWalker.java,v $
* Revision 1.5 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.4 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.3 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/xml/TreeWalker.java
|
Java
|
gpl3
| 3,723
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* XMLPrintVisitor implements the Visitor interface in the visitor design pattern for the
* purpose of printing in HTML-like format the various DOM-Nodes.
* <p>In HTML-like printing, only the following Nodes are printed:
* <DL>
* <DT>Document</DT>
* <DD>Only the doctype provided on this constructor is written (i.e. no XML declaration, <!DOCTYPE>, or internal DTD).</DD>
* <DT>Element</DT>
* <DD>All element names are uppercased.</DD>
* <DD>Empty elements are written as <code><BR></code> instead of <code><BR/></code>.</DD>
* <DT>Attr</DT>
* <DD>All attribute names are lowercased.</DD>
* <DT>Text</DT>
* </DL>
* <p/>
* <p>The following sample code uses the XMLPrintVisitor on a hierarchy of nodes:
* <pre>
* <p/>
* PrintWriter printWriter = new PrintWriter();
* Visitor htmlPrintVisitor = new XMLPrintVisitor(printWriter);
* TreeWalker treeWalker = new TreeWalker(htmlPrintVisitor);
* treeWalker.traverse(document);
* printWriter.close();
* <p/>
* </pre>
* <p/>
* <P>By default, this doesn't print non-specified attributes.</P>
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
* @version $Id: XMLPrintVisitor.java,v 1.8 2003/01/06 00:23:49 just Exp $
* @see Visitor
* @see TreeWalker
*/
public class XMLPrintVisitor implements Visitor
{
protected Writer writer = null;
protected int level = 0;
protected String doctype = null;
/**
* Constructor for customized encoding and doctype.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
* @param doctype String to be printed at the top of the document.
*/
public XMLPrintVisitor(Writer writer, String encoding, String doctype)
{
this.writer = writer;
this.doctype = doctype;
// this.isPrintNonSpecifiedAttributes = false;
}
/**
* Constructor for customized encoding.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
*/
public XMLPrintVisitor(Writer writer, String encoding)
{
this(writer, encoding, null);
}
/**
* Constructor for default encoding.
*
* @param writer The character output stream to use.
*/
public XMLPrintVisitor(Writer writer)
{
this(writer, null, null);
}
/**
* Constructor for default encoding.
*
* @param fileName the filepath to write to
*/
public XMLPrintVisitor(String fileName)
{
try
{
writer = new FileWriter(fileName);
} catch (IOException ioe)
{
}
}
/**
* Writes the <var>doctype</var> from the constructor (if any).
*
* @param document Node print as HTML.
*/
public void visitDocumentPre(Document document)
{
}
/**
* Flush the writer.
*
* @param document Node to print as HTML.
*/
public void visitDocumentPost(Document document)
{
write("\n");
flush();
}
/**
* Creates a formatted string representation of the start of the specified <var>element</var> Node
* and its associated attributes, and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPre(Element element)
{
this.level++;
write("<" + element.getTagName());
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
Attr attr = (Attr) attributes.item(i);
visitAttributePre(attr);
}
write(">\n");
}
/**
* Creates a formatted string representation of the end of the specified <var>element</var> Node,
* and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPost(Element element)
{
String tagName = element.getTagName();
// if (element.hasChildNodes()) {
write("</" + tagName + ">\n");
// }
level--;
}
/**
* Creates a formatted string representation of the specified <var>attribute</var> Node
* and its associated attributes, and directs it to the print writer.
* <p>Note that TXAttribute Nodes are not parsed into the document object hierarchy by the
* XML4J parser; attributes exist as part of a Element Node.
*
* @param attr attr to print.
*/
public void visitAttributePre(Attr attr)
{
write(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
}
/**
* Creates a formatted string representation of the specified <var>text</var> Node,
* and directs it to the print writer. CDATASections are respected.
*
* @param text Node to print with format.
*/
public void visitText(Text text)
{
if (this.level > 0)
{
write(text.getData());
}
}
private void write(String s)
{
try
{
writer.write(s);
} catch (IOException e)
{
}
}
private void flush()
{
try
{
writer.flush();
} catch (IOException e)
{
}
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/xml/XMLPrintVisitor.java
|
Java
|
gpl3
| 5,835
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker;
import android.net.Uri;
/**
* Various application wide constants
*
* @author Just van den Broecke
* @version $Id:$
*/
public class Constants
{
/**
* The authority of the track data provider
*/
public static final String AUTHORITY = "nl.sogeti.android.gpstracker";
/**
* The content:// style URL for the track data provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
/**
* Logging states, slightly adapted from GPSService states
*/
public static final int DOWN = 0;
public static final int LOGGING = 1;
public static final int PAUSED = 2;
public static final int STOPPED = 3;
public static final int UNKNOWN = 4;
public static String[] LOGGING_STATES = {"down", "logging", "paused", "stopped", "unknown"};
public static final String DISABLEBLANKING = "disableblanking";
public static final String PREF_ENABLE_SOUND = "pref_enablesound";
public static final String PREF_SERVER_URL = "pref_server_url";
public static final String PREF_SERVER_USER = "pref_server_user";
public static final String PREF_SERVER_PASSWORD = "pref_server_password";
public static final String SERVICE_GPS_LOGGING = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService";
public static final String EXTERNAL_DIR = "/OpenGPSTracker/";
public static final Uri NAME_URI = Uri.parse("content://" + AUTHORITY + ".string");
/**
* Activity Action: Pick a file through the file manager, or let user
* specify a custom file name.
* Data is the current file name or file name suggestion.
* Returns a new file name as file URI in data.
* <p/>
* <p>Constant Value: "org.openintents.action.PICK_FILE"</p>
*/
public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE";
public static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1;
/**
* Activity Action: Show an about dialog to display
* information about the application.
* <p/>
* The application information is retrieved from the
* application's manifest. In order to send the package
* you have to launch this activity through
* startActivityForResult().
* <p/>
* Alternatively, you can specify the package name
* manually through the extra EXTRA_PACKAGE.
* <p/>
* All data can be replaced using optional intent extras.
* <p/>
* <p>
* Constant Value: "org.openintents.action.SHOW_ABOUT_DIALOG"
* </p>
*/
public static final String OI_ACTION_SHOW_ABOUT_DIALOG =
"org.openintents.action.SHOW_ABOUT_DIALOG";
/**
* Definitions for tracks.
*
*/
public static final class Tracks implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "tracks";
/**
* The end time
*/
public static final String NAME = "name";
public static final String CREATION_TIME = "creationtime";
/**
* The MIME type of a CONTENT_URI subdirectory of a single track.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track";
/**
* The content:// style URL for this provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for segments.
*/
public static final class Segments implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "segments";
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
static final String TRACK_TYPE = "INTEGER NOT NULL";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
/**
* The MIME type of a CONTENT_URI subdirectory of a single segment.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment";
/**
* The MIME type of CONTENT_URI providing a directory of segments.
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for media URI's.
*
*/
public static final class Media implements android.provider.BaseColumns
{
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
public static final String SEGMENT = "segment";
public static final String WAYPOINT = "waypoint";
public static final String URI = "uri";
/**
* The name of this table
*/
public static final String TABLE = "media";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for waypoints.
*
*/
public static final class Waypoints implements android.provider.BaseColumns
{
/**
* The name of this table
*/
public static final String TABLE = "waypoints";
/**
* The latitude
*/
public static final String LATITUDE = "latitude";
/**
* The longitude
*/
public static final String LONGITUDE = "longitude";
/**
* The recorded time
*/
public static final String TIME = "time";
/**
* The speed in meters per second
*/
public static final String SPEED = "speed";
/**
* The segment _id to which this segment belongs
*/
public static final String SEGMENT = "tracksegment";
/**
* The accuracy of the fix
*/
public static final String ACCURACY = "accuracy";
/**
* The altitude
*/
public static final String ALTITUDE = "altitude";
/**
* the bearing of the fix
*/
public static final String BEARING = "bearing";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/Constants.java
|
Java
|
gpl3
| 6,401
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.logger;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import nl.sogeti.android.gpstracker.logger.IGPSLoggerServiceRemote;
import org.opentraces.metatracker.Constants;
/**
* Class to interact with the service that tracks and logs the locations
*
* @author rene (c) Jan 18, 2009, Sogeti B.V. adapted by Just van den Broecke
* @version $Id: GPSLoggerServiceManager.java 455 2010-03-14 08:16:44Z rcgroot $
*/
public class GPSLoggerServiceManager
{
private static final String TAG = "MT.GPSLoggerServiceManager";
private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION";
private Context mCtx;
private IGPSLoggerServiceRemote mGPSLoggerRemote;
private final Object mStartLock = new Object();
private boolean mStarted = false;
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mServiceConnection = null;
public GPSLoggerServiceManager(Context ctx)
{
this.mCtx = ctx;
}
public boolean isStarted()
{
synchronized (mStartLock)
{
return mStarted;
}
}
public int getLoggingState()
{
synchronized (mStartLock)
{
int logging = Constants.UNKNOWN;
try
{
if (this.mGPSLoggerRemote != null)
{
logging = this.mGPSLoggerRemote.loggingState();
Log.d(TAG, "mGPSLoggerRemote tells state to be " + logging);
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return logging;
}
}
public boolean isMediaPrepared()
{
synchronized (mStartLock)
{
boolean prepared = false;
try
{
if (this.mGPSLoggerRemote != null)
{
prepared = this.mGPSLoggerRemote.isMediaPrepared();
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return prepared;
}
}
public long startGPSLogging(String name)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.startLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void pauseGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.pauseLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
}
}
public long resumeGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.resumeLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void stopGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.stopLogging();
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
public void storeMediaUri(Uri mediaUri)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.storeMediaUri(mediaUri);
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void startup(final ServiceConnection observer)
{
Log.d(TAG, "connectToGPSLoggerService()");
if (!mStarted)
{
this.mServiceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
synchronized (mStartLock)
{
Log.d(TAG, "onServiceConnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface(service);
mStarted = true;
if (observer != null)
{
observer.onServiceConnected(className, service);
}
}
}
public void onServiceDisconnected(ComponentName className)
{
synchronized (mStartLock)
{
Log.e(TAG, "onServiceDisconnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = null;
mStarted = false;
if (observer != null)
{
observer.onServiceDisconnected(className);
}
}
}
};
this.mCtx.bindService(new Intent(Constants.SERVICE_GPS_LOGGING), this.mServiceConnection, Context.BIND_AUTO_CREATE);
} else
{
Log.w(TAG, "Attempting to connect whilst connected");
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void shutdown()
{
Log.d(TAG, "disconnectFromGPSLoggerService()");
try
{
this.mCtx.unbindService(this.mServiceConnection);
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Failed to unbind a service, prehaps the service disapeared?", e);
}
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/logger/GPSLoggerServiceManager.java
|
Java
|
gpl3
| 6,466
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
/**
* Generic exception wrapper. $Id: ClientException.java,v 1.2 2005/07/22 22:25:20 just Exp $
*
* @author $Author: Just van den Broecke$
* @version $Revision: $
*/
public class ClientException extends Exception
{
private int errorId;
String error;
protected ClientException()
{
}
public ClientException(String aMessage, Throwable t)
{
super(aMessage + "\n embedded exception=" + t.toString());
}
public ClientException(String aMessage)
{
super(aMessage);
}
public ClientException(int anErrorId, String anError, String someDetails)
{
super(someDetails);
errorId = anErrorId;
error = anError;
}
public ClientException(Throwable t)
{
this("ClientException: ", t);
}
public String toString()
{
return "ClientException: " + getMessage();
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/net/ClientException.java
|
Java
|
gpl3
| 1,533
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Constants and utilities for the KW protocol.
*
* @author $Author: $
* @version $Id: Protocol.java,v 1.2 2005/07/22 22:25:20 just Exp $
*/
public class Protocol
{
/**
* AMUSE Protocol version.
*/
public static final String PROTOCOL_VERSION = "4.0";
/**
* Postfixes
*/
public static final String POSTFIX_REQ = "-req";
public static final String POSTFIX_RSP = "-rsp";
public static final String POSTFIX_NRSP = "-nrsp";
public static final String POSTFIX_IND = "-ind";
/**
* Service id's
*/
public static final String SERVICE_SESSION_CREATE = "ses-create";
public static final String SERVICE_LOGIN = "ses-login";
public static final String SERVICE_LOGOUT = "ses-logout";
public static final String SERVICE_SESSION_PING = "ses-ping";
public static final String SERVICE_QUERY_STORE = "query-store";
public static final String SERVICE_MAP_AVAIL = "map-avail";
public static final String SERVICE_MULTI_REQ = "multi-req";
/**
* Common Attributes *
*/
public static final String ATTR_DEVID = "devid";
public static final String ATTR_USER = "user";
public static final String ATTR_AGENT = "agent";
public static final String ATTR_AGENTKEY = "agentkey";
public static final String ATTR_SECTIONS = "sections";
public static final String ATTR_ID = "id";
public static final String ATTR_CMD = "cmd";
public static final String ATTR_ERROR = "error";
public static final String ATTR_ERRORID = "errorId"; // yes id must be Id !!
public static final String ATTR_PASSWORD = "password";
public static final String ATTR_PROTOCOLVERSION = "protocolversion";
public static final String ATTR_STOPONERROR = "stoponerror";
public static final String ATTR_T = "t";
public static final String ATTR_TIME = "time";
public static final String ATTR_DETAILS = "details";
public static final String ATTR_NAME = "name";
/**
* Error ids returned in -nrsp as attribute ATTR_ERRORID
*/
public final static int
// 4000-4999 are "user-correctable" errors (user sends wrong input)
// 5000-5999 are server failures
ERR4004_ILLEGAL_COMMAND_FOR_STATE = 4003,
ERR4004_INVALID_ATTR_VALUE = 4004,
ERR4007_AGENT_LEASE_EXPIRED = 4007,
//_Portal/Application_error_codes_(4100-4199)
ERR4100_INVALID_USERNAME = 4100,
ERR4101_INVALID_PASSWORD = 4101,
ERR4102_MAX_LOGIN_ATTEMPTS_EXCEEDED = 4102,
//_General_Server_Error_Codes
ERR5000_INTERNAL_SERVER_ERROR = 5000;
/**
* Create login protocol request.
*/
public static Element createLoginRequest(String aName, String aPassword)
{
Element request = createRequest(SERVICE_LOGIN);
request.setAttribute(ATTR_NAME, aName);
request.setAttribute(ATTR_PASSWORD, aPassword);
request.setAttribute(ATTR_PROTOCOLVERSION, PROTOCOL_VERSION);
return request;
}
/**
* Create create-session protocol request.
*/
public static Element createSessionCreateRequest()
{
return createRequest(SERVICE_SESSION_CREATE);
}
/**
* Create a positive response element.
*/
public static Element createRequest(String aService)
{
Element element = null;
try
{
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
element = doc.createElement(aService + POSTFIX_REQ);
doc.appendChild(element);
} catch (Throwable t)
{
}
return element;
}
/**
* Return service name for a message tag.
*
* @param aMessageTag
* @return
*/
public static String getServiceName(String aMessageTag)
{
try
{
return aMessageTag.substring(0, aMessageTag.lastIndexOf('-'));
}
catch (Throwable t)
{
throw new IllegalArgumentException("getServiceName: invalid tag: " + aMessageTag);
}
}
/**
* Is message a (negative) response..
*
* @param message
* @return
*/
public static boolean isResponse(Element message)
{
String tag = message.getTagName();
return tag.endsWith(POSTFIX_RSP) || tag.endsWith(POSTFIX_NRSP);
}
/**
* Is message a positive response..
*
* @param message
* @return
*/
public static boolean isPositiveResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_RSP);
}
/**
* Is message a negative response..
*
* @param message
* @return
*/
public static boolean isNegativeResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_NRSP);
}
public static boolean isPositiveServiceResponse(Element message, String service)
{
return isPositiveResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isNegativeServiceResponse(Element message, String service)
{
return isNegativeResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isService(Element message, String service)
{
return service.equals(getServiceName(message.getTagName()));
}
protected Protocol()
{
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/net/Protocol.java
|
Java
|
gpl3
| 5,814
|
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.opentraces.metatracker.xml.DOMUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Basic OpenTraces client using XML over HTTP.
* <p/>
* Use this class within Android HTTP clients.
*
* @author $Author: Just van den Broecke$
* @version $Revision: 3043 $ $Id: HTTPClient.java 3043 2009-01-17 16:25:21Z just $
* @see
*/
public class OpenTracesClient extends Protocol
{
private static final String LOG_TAG = "MT.OpenTracesClient";
/**
* Default KW session timeout (minutes).
*/
public static final int DEFAULT_TIMEOUT_MINS = 5;
/**
* Full KW protocol URL.
*/
private String protocolURL;
/**
* Debug flag for verbose output.
*/
private boolean debug;
/**
* Key gotten on login ack
*/
private String agentKey;
/**
* Keyworx session timeout (minutes).
*/
private int timeout;
/**
* Saved login request for session restore on timeout.
*/
private Element loginRequest;
/**
* Constructor with full protocol URL e.g. http://www.bla.com/proto.srv.
*/
public OpenTracesClient(String aProtocolURL)
{
this(aProtocolURL, DEFAULT_TIMEOUT_MINS);
}
/**
* Constructor with protocol URL and timeout.
*/
public OpenTracesClient(String aProtocolURL, int aTimeout)
{
protocolURL = aProtocolURL;
if (!protocolURL.endsWith("/proto.srv")) {
protocolURL += "/proto.srv";
}
timeout = aTimeout;
}
/**
* Create session.
*/
synchronized public Element createSession() throws ClientException
{
agentKey = null;
// Create XML request
Element request = createRequest(SERVICE_SESSION_CREATE);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
public String getAgentKey()
{
return agentKey;
}
public boolean hasSession()
{
return agentKey != null;
}
public boolean isLoggedIn()
{
return hasSession() && loginRequest != null;
}
/**
* Login on portal.
*/
synchronized public Element login(String aName, String aPassword) throws ClientException
{
// Create XML request
Element request = createLoginRequest(aName, aPassword);
// Execute request
Element response = doRequest(request);
// Filter session-related attrs
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
/**
* Keep alive service.
*/
synchronized public Element ping() throws ClientException
{
return service(createRequest(SERVICE_SESSION_PING));
}
/**
* perform TWorx service request.
*/
synchronized public Element service(Element request) throws ClientException
{
throwOnInvalidSession();
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Positive response: return wrapped handler response
return response;
}
/**
* perform TWorx multi-service request.
*/
synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException
{
// We don't need a valid session as one of the requests
// may be a login or create-session request.
// Create multi-req request with individual requests as children
Element request = createRequest(SERVICE_MULTI_REQ);
request.setAttribute(ATTR_STOPONERROR, stopOnError + "");
for (Element req : requests)
{
request.appendChild(req);
}
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Filter child responses for session-based responses
NodeList responseList = response.getChildNodes();
List<Element> responses = new ArrayList(responseList.getLength());
for (int i = 0; i < responseList.getLength(); i++)
{
handleResponse(requests.get(i), (Element) responseList.item(i));
responses.add((Element) responseList.item(i));
}
// Positive multi-req response: return child responses
return responses;
}
/**
* Logout from portal.
*/
synchronized public Element logout() throws ClientException
{
throwOnInvalidSession();
// Create XML request
Element request = createRequest(SERVICE_LOGOUT);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
// Throw exception or return positive response
// throwOnNrsp(response);
return response;
}
/*
http://brainflush.wordpress.com/2008/10/17/talking-to-web-servers-via-http-in-android-10/
*/
public void uploadFile(String fileName)
{
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
File f = new File(fileName);
HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myIdentifier", new StringBody("somevalue"));
entity.addPart("myFile", new FileBody(f));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
Log.d(LOG_TAG, "Upload result: " + response.getStatusLine());
if (entity != null)
{
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
} catch (Throwable ex)
{
Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
}
}
public void setDebug(boolean b)
{
debug = b;
}
/**
* Filter responses for session-related requests.
*/
private void handleResponse(Element request, Element response) throws ClientException
{
if (isNegativeResponse(response))
{
return;
}
String service = Protocol.getServiceName(request.getTagName());
if (service.equals(SERVICE_LOGIN))
{
// Save for later session restore
loginRequest = request;
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// if (response.hasAttribute(ATTR_TIME)) {
// DateTimeUtils.setTime(response.getLongAttr(ATTR_TIME));
// }
} else if (service.equals(SERVICE_SESSION_CREATE))
{
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
} else if (service.equals(SERVICE_LOGOUT))
{
loginRequest = null;
agentKey = null;
}
}
/**
* Throw exception on negative protocol response.
*/
private void throwOnNrsp(Element anElement) throws ClientException
{
if (isNegativeResponse(anElement))
{
String details = "no details";
if (anElement.hasAttribute(ATTR_DETAILS))
{
details = anElement.getAttribute(ATTR_DETAILS);
}
throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)),
anElement.getAttribute(ATTR_ERROR), details);
}
}
/**
* Throw exception when not logged in.
*/
private void throwOnInvalidSession() throws ClientException
{
if (agentKey == null)
{
throw new ClientException("Invalid tworx session");
}
}
/**
* .
*/
private Element redoRequestOnSessionTimeout(Element request, Element response) throws ClientException
{
// Check for session timeout
if (isNegativeResponse(response) && Integer.parseInt(response.getAttribute(ATTR_ERRORID)) == Protocol.ERR4007_AGENT_LEASE_EXPIRED)
{
p("Reestablishing session...");
// Reset session
agentKey = null;
// Do login if already logged in
if (loginRequest != null)
{
response = doRequest(loginRequest);
throwOnNrsp(response);
} else
{
response = createSession();
throwOnNrsp(response);
}
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// Re-issue service request and return new response
return doRequest(request);
}
// No session timeout so same response
return response;
}
/**
* Do XML over HTTP request and retun response.
*/
private Element doRequest(Element anElement) throws ClientException
{
// Create URL to use
String url = protocolURL;
if (agentKey != null)
{
url = url + "?agentkey=" + agentKey;
} else
{
// Must be login
url = url + "?timeout=" + timeout;
}
p("doRequest: " + url + " req=" + anElement.getTagName());
// Perform request/response
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Element replyElement = null;
try
{
// Make sure the server knows what kind of a response we will accept
httpPost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httpPost.addHeader("Content-Type", "application/xml");
String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument());
StringEntity entity = new StringEntity(xmlString, "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
// Parse response
Document replyDoc = DOMUtil.parse(response.getEntity().getContent());
replyElement = replyDoc.getDocumentElement();
p("doRequest: rsp=" + replyElement.getTagName());
}
catch (Throwable t)
{
throw new ClientException("Error in doRequest: " + t);
}
finally
{
}
return replyElement;
}
/**
* Util: print.
*/
private void p(String s)
{
if (debug)
{
Log.d(LOG_TAG, s);
}
}
/**
* Util: warn.
*/
private void warn(String s)
{
warn(s, null);
}
/**
* Util: warn with exception.
*/
private void warn(String s, Throwable t)
{
Log.e(LOG_TAG, s + " ex=" + t, t);
}
}
|
zzy157-running
|
MetaTracker/application/src/org/opentraces/metatracker/net/OpenTracesClient.java
|
Java
|
gpl3
| 10,842
|
package nl.sogeti.android.gpstracker.logger;
import android.net.Uri;
interface IGPSLoggerServiceRemote {
int loggingState();
long startLogging();
void pauseLogging();
long resumeLogging();
void stopLogging();
Uri storeMediaUri(in Uri mediaUri);
boolean isMediaPrepared();
}
|
zzy157-running
|
MetaTracker/application/src/nl/sogeti/android/gpstracker/logger/IGPSLoggerServiceRemote.aidl
|
AIDL
|
gpl3
| 295
|
//
// AsyncSocket.h
//
// This class is in the public domain.
// Originally created by Dustin Voss on Wed Jan 29 2003.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import <Foundation/Foundation.h>
@class AsyncSocket;
@class AsyncReadPacket;
@class AsyncWritePacket;
extern NSString *const AsyncSocketException;
extern NSString *const AsyncSocketErrorDomain;
enum AsyncSocketError
{
AsyncSocketCFSocketError = kCFSocketError, // From CFSocketError enum.
AsyncSocketNoError = 0, // Never used.
AsyncSocketCanceledError, // onSocketWillConnect: returned NO.
AsyncSocketConnectTimeoutError,
AsyncSocketReadMaxedOutError, // Reached set maxLength without completing
AsyncSocketReadTimeoutError,
AsyncSocketWriteTimeoutError
};
typedef enum AsyncSocketError AsyncSocketError;
@protocol AsyncSocketDelegate
@optional
/**
* In the event of an error, the socket is closed.
* You may call "unreadData" during this call-back to get the last bit of data off the socket.
* When connecting, this delegate method may be called
* before"onSocket:didAcceptNewSocket:" or "onSocket:didConnectToHost:".
**/
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err;
/**
* Called when a socket disconnects with or without error. If you want to release a socket after it disconnects,
* do so here. It is not safe to do that during "onSocket:willDisconnectWithError:".
*
* If you call the disconnect method, and the socket wasn't already disconnected,
* this delegate method will be called before the disconnect method returns.
**/
- (void)onSocketDidDisconnect:(AsyncSocket *)sock;
/**
* Called when a socket accepts a connection. Another socket is spawned to handle it. The new socket will have
* the same delegate and will call "onSocket:didConnectToHost:port:".
**/
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket;
/**
* Called when a new socket is spawned to handle a connection. This method should return the run-loop of the
* thread on which the new socket and its delegate should operate. If omitted, [NSRunLoop currentRunLoop] is used.
**/
- (NSRunLoop *)onSocket:(AsyncSocket *)sock wantsRunLoopForNewSocket:(AsyncSocket *)newSocket;
/**
* Called when a socket is about to connect. This method should return YES to continue, or NO to abort.
* If aborted, will result in AsyncSocketCanceledError.
*
* If the connectToHost:onPort:error: method was called, the delegate will be able to access and configure the
* CFReadStream and CFWriteStream as desired prior to connection.
*
* If the connectToAddress:error: method was called, the delegate will be able to access and configure the
* CFSocket and CFSocketNativeHandle (BSD socket) as desired prior to connection. You will be able to access and
* configure the CFReadStream and CFWriteStream in the onSocket:didConnectToHost:port: method.
**/
- (BOOL)onSocketWillConnect:(AsyncSocket *)sock;
/**
* Called when a socket connects and is ready for reading and writing.
* The host parameter will be an IP address, not a DNS name.
**/
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port;
/**
* Called when a socket has completed reading the requested data into memory.
* Not called if there is an error.
**/
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
/**
* Called when a socket has read in data, but has not yet completed the read.
* This would occur if using readToData: or readToLength: methods.
* It may be used to for things such as updating progress bars.
**/
- (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
/**
* Called when a socket has completed writing the requested data. Not called if there is an error.
**/
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag;
/**
* Called when a socket has written some data, but has not yet completed the entire write.
* It may be used to for things such as updating progress bars.
**/
- (void)onSocket:(AsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
/**
* Called if a read operation has reached its timeout without completing.
* This method allows you to optionally extend the timeout.
* If you return a positive time interval (> 0) the read's timeout will be extended by the given amount.
* If you don't implement this method, or return a non-positive time interval (<= 0) the read will timeout as usual.
*
* The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
* The length parameter is the number of bytes that have been read so far for the read operation.
*
* Note that this method may be called multiple times for a single read if you return positive numbers.
**/
- (NSTimeInterval)onSocket:(AsyncSocket *)sock
shouldTimeoutReadWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length;
/**
* Called if a write operation has reached its timeout without completing.
* This method allows you to optionally extend the timeout.
* If you return a positive time interval (> 0) the write's timeout will be extended by the given amount.
* If you don't implement this method, or return a non-positive time interval (<= 0) the write will timeout as usual.
*
* The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
* The length parameter is the number of bytes that have been written so far for the write operation.
*
* Note that this method may be called multiple times for a single write if you return positive numbers.
**/
- (NSTimeInterval)onSocket:(AsyncSocket *)sock
shouldTimeoutWriteWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length;
/**
* Called after the socket has successfully completed SSL/TLS negotiation.
* This method is not called unless you use the provided startTLS method.
*
* If a SSL/TLS negotiation fails (invalid certificate, etc) then the socket will immediately close,
* and the onSocket:willDisconnectWithError: delegate method will be called with the specific SSL error code.
**/
- (void)onSocketDidSecure:(AsyncSocket *)sock;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface AsyncSocket : NSObject
{
CFSocketNativeHandle theNativeSocket4;
CFSocketNativeHandle theNativeSocket6;
CFSocketRef theSocket4; // IPv4 accept or connect socket
CFSocketRef theSocket6; // IPv6 accept or connect socket
CFReadStreamRef theReadStream;
CFWriteStreamRef theWriteStream;
CFRunLoopSourceRef theSource4; // For theSocket4
CFRunLoopSourceRef theSource6; // For theSocket6
CFRunLoopRef theRunLoop;
CFSocketContext theContext;
NSArray *theRunLoopModes;
NSTimer *theConnectTimer;
NSMutableArray *theReadQueue;
AsyncReadPacket *theCurrentRead;
NSTimer *theReadTimer;
NSMutableData *partialReadBuffer;
NSMutableArray *theWriteQueue;
AsyncWritePacket *theCurrentWrite;
NSTimer *theWriteTimer;
id theDelegate;
UInt16 theFlags;
long theUserData;
}
- (id)init;
- (id)initWithDelegate:(id)delegate;
- (id)initWithDelegate:(id)delegate userData:(long)userData;
/* String representation is long but has no "\n". */
- (NSString *)description;
/**
* Use "canSafelySetDelegate" to see if there is any pending business (reads and writes) with the current delegate
* before changing it. It is, of course, safe to change the delegate before connecting or accepting connections.
**/
- (id)delegate;
- (BOOL)canSafelySetDelegate;
- (void)setDelegate:(id)delegate;
/* User data can be a long, or an id or void * cast to a long. */
- (long)userData;
- (void)setUserData:(long)userData;
/* Don't use these to read or write. And don't close them either! */
- (CFSocketRef)getCFSocket;
- (CFReadStreamRef)getCFReadStream;
- (CFWriteStreamRef)getCFWriteStream;
// Once one of the accept or connect methods are called, the AsyncSocket instance is locked in
// and the other accept/connect methods can't be called without disconnecting the socket first.
// If the attempt fails or times out, these methods either return NO or
// call "onSocket:willDisconnectWithError:" and "onSockedDidDisconnect:".
// When an incoming connection is accepted, AsyncSocket invokes several delegate methods.
// These methods are (in chronological order):
// 1. onSocket:didAcceptNewSocket:
// 2. onSocket:wantsRunLoopForNewSocket:
// 3. onSocketWillConnect:
//
// Your server code will need to retain the accepted socket (if you want to accept it).
// The best place to do this is probably in the onSocket:didAcceptNewSocket: method.
//
// After the read and write streams have been setup for the newly accepted socket,
// the onSocket:didConnectToHost:port: method will be called on the proper run loop.
//
// Multithreading Note: If you're going to be moving the newly accepted socket to another run
// loop by implementing onSocket:wantsRunLoopForNewSocket:, then you should wait until the
// onSocket:didConnectToHost:port: method before calling read, write, or startTLS methods.
// Otherwise read/write events are scheduled on the incorrect runloop, and chaos may ensue.
/**
* Tells the socket to begin listening and accepting connections on the given port.
* When a connection comes in, the AsyncSocket instance will call the various delegate methods (see above).
* The socket will listen on all available interfaces (e.g. wifi, ethernet, etc)
**/
- (BOOL)acceptOnPort:(UInt16)port error:(NSError **)errPtr;
/**
* This method is the same as acceptOnPort:error: with the additional option
* of specifying which interface to listen on. So, for example, if you were writing code for a server that
* has multiple IP addresses, you could specify which address you wanted to listen on. Or you could use it
* to specify that the socket should only accept connections over ethernet, and not other interfaces such as wifi.
* You may also use the special strings "localhost" or "loopback" to specify that
* the socket only accept connections from the local machine.
*
* To accept connections on any interface pass nil, or simply use the acceptOnPort:error: method.
**/
- (BOOL)acceptOnInterface:(NSString *)interface port:(UInt16)port error:(NSError **)errPtr;
/**
* Connects to the given host and port.
* The host may be a domain name (e.g. "deusty.com") or an IP address string (e.g. "192.168.0.2")
**/
- (BOOL)connectToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr;
/**
* This method is the same as connectToHost:onPort:error: with an additional timeout option.
* To not time out use a negative time interval, or simply use the connectToHost:onPort:error: method.
**/
- (BOOL)connectToHost:(NSString *)hostname
onPort:(UInt16)port
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr;
/**
* Connects to the given address, specified as a sockaddr structure wrapped in a NSData object.
* For example, a NSData object returned from NSNetservice's addresses method.
*
* If you have an existing struct sockaddr you can convert it to a NSData object like so:
* struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
* struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
/**
* This method is the same as connectToAddress:error: with an additional timeout option.
* To not time out use a negative time interval, or simply use the connectToAddress:error: method.
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr;
- (BOOL)connectToAddress:(NSData *)remoteAddr
viaInterfaceAddress:(NSData *)interfaceAddr
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr;
/**
* Disconnects immediately. Any pending reads or writes are dropped.
* If the socket is not already disconnected, the onSocketDidDisconnect delegate method
* will be called immediately, before this method returns.
*
* Please note the recommended way of releasing an AsyncSocket instance (e.g. in a dealloc method)
* [asyncSocket setDelegate:nil];
* [asyncSocket disconnect];
* [asyncSocket release];
**/
- (void)disconnect;
/**
* Disconnects after all pending reads have completed.
* After calling this, the read and write methods will do nothing.
* The socket will disconnect even if there are still pending writes.
**/
- (void)disconnectAfterReading;
/**
* Disconnects after all pending writes have completed.
* After calling this, the read and write methods will do nothing.
* The socket will disconnect even if there are still pending reads.
**/
- (void)disconnectAfterWriting;
/**
* Disconnects after all pending reads and writes have completed.
* After calling this, the read and write methods will do nothing.
**/
- (void)disconnectAfterReadingAndWriting;
/* Returns YES if the socket and streams are open, connected, and ready for reading and writing. */
- (BOOL)isConnected;
/**
* Returns the local or remote host and port to which this socket is connected, or nil and 0 if not connected.
* The host will be an IP address.
**/
- (NSString *)connectedHost;
- (UInt16)connectedPort;
- (NSString *)localHost;
- (UInt16)localPort;
/**
* Returns the local or remote address to which this socket is connected,
* specified as a sockaddr structure wrapped in a NSData object.
*
* See also the connectedHost, connectedPort, localHost and localPort methods.
**/
- (NSData *)connectedAddress;
- (NSData *)localAddress;
/**
* Returns whether the socket is IPv4 or IPv6.
* An accepting socket may be both.
**/
- (BOOL)isIPv4;
- (BOOL)isIPv6;
// The readData and writeData methods won't block (they are asynchronous).
//
// When a read is complete the onSocket:didReadData:withTag: delegate method is called.
// When a write is complete the onSocket:didWriteDataWithTag: delegate method is called.
//
// You may optionally set a timeout for any read/write operation. (To not timeout, use a negative time interval.)
// If a read/write opertion times out, the corresponding "onSocket:shouldTimeout..." delegate method
// is called to optionally allow you to extend the timeout.
// Upon a timeout, the "onSocket:willDisconnectWithError:" method is called, followed by "onSocketDidDisconnect".
//
// The tag is for your convenience.
// You can use it as an array index, step number, state id, pointer, etc.
/**
* Reads the first available bytes that become available on the socket.
*
* If the timeout value is negative, the read operation will not use a timeout.
**/
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Reads the first available bytes that become available on the socket.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, the socket will create a buffer for you.
*
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
**/
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag;
/**
* Reads the first available bytes that become available on the socket.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
* A maximum of length bytes will be read.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
* If maxLength is zero, no length restriction is enforced.
*
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
**/
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag;
/**
* Reads the given number of bytes.
*
* If the timeout value is negative, the read operation will not use a timeout.
*
* If the length is 0, this method does nothing and the delegate is not called.
**/
- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Reads the given number of bytes.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
*
* If the length is 0, this method does nothing and the delegate is not called.
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
**/
- (void)readDataToLength:(NSUInteger)length
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
*
* If the timeout value is negative, the read operation will not use a timeout.
*
* If you pass nil or zero-length data as the "data" parameter,
* the method will do nothing, and the delegate will not be called.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
*
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
*
* If the timeout value is negative, the read operation will not use a timeout.
*
* If maxLength is zero, no length restriction is enforced.
* Otherwise if maxLength bytes are read without completing the read,
* it is treated similarly to a timeout - the socket is closed with a AsyncSocketReadMaxedOutError.
* The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
*
* If you pass nil or zero-length data as the "data" parameter,
* the method will do nothing, and the delegate will not be called.
* If you pass a maxLength parameter that is less than the length of the data parameter,
* the method will do nothing, and the delegate will not be called.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
* A maximum of length bytes will be read.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
*
* If maxLength is zero, no length restriction is enforced.
* Otherwise if maxLength bytes are read without completing the read,
* it is treated similarly to a timeout - the socket is closed with a AsyncSocketReadMaxedOutError.
* The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
*
* If you pass a maxLength parameter that is less than the length of the data parameter,
* the method will do nothing, and the delegate will not be called.
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag;
/**
* Writes data to the socket, and calls the delegate when finished.
*
* If you pass in nil or zero-length data, this method does nothing and the delegate will not be called.
* If the timeout value is negative, the write operation will not use a timeout.
**/
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Returns progress of current read or write, from 0.0 to 1.0, or NaN if no read/write (use isnan() to check).
* "tag", "done" and "total" will be filled in if they aren't NULL.
**/
- (float)progressOfReadReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total;
- (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total;
/**
* Secures the connection using SSL/TLS.
*
* This method may be called at any time, and the TLS handshake will occur after all pending reads and writes
* are finished. This allows one the option of sending a protocol dependent StartTLS message, and queuing
* the upgrade to TLS at the same time, without having to wait for the write to finish.
* Any reads or writes scheduled after this method is called will occur over the secured connection.
*
* The possible keys and values for the TLS settings are well documented.
* Some possible keys are:
* - kCFStreamSSLLevel
* - kCFStreamSSLAllowsExpiredCertificates
* - kCFStreamSSLAllowsExpiredRoots
* - kCFStreamSSLAllowsAnyRoot
* - kCFStreamSSLValidatesCertificateChain
* - kCFStreamSSLPeerName
* - kCFStreamSSLCertificates
* - kCFStreamSSLIsServer
*
* Please refer to Apple's documentation for associated values, as well as other possible keys.
*
* If you pass in nil or an empty dictionary, the default settings will be used.
*
* The default settings will check to make sure the remote party's certificate is signed by a
* trusted 3rd party certificate agency (e.g. verisign) and that the certificate is not expired.
* However it will not verify the name on the certificate unless you
* give it a name to verify against via the kCFStreamSSLPeerName key.
* The security implications of this are important to understand.
* Imagine you are attempting to create a secure connection to MySecureServer.com,
* but your socket gets directed to MaliciousServer.com because of a hacked DNS server.
* If you simply use the default settings, and MaliciousServer.com has a valid certificate,
* the default settings will not detect any problems since the certificate is valid.
* To properly secure your connection in this particular scenario you
* should set the kCFStreamSSLPeerName property to "MySecureServer.com".
* If you do not know the peer name of the remote host in advance (for example, you're not sure
* if it will be "domain.com" or "www.domain.com"), then you can use the default settings to validate the
* certificate, and then use the X509Certificate class to verify the issuer after the socket has been secured.
* The X509Certificate class is part of the CocoaAsyncSocket open source project.
**/
- (void)startTLS:(NSDictionary *)tlsSettings;
/**
* For handling readDataToData requests, data is necessarily read from the socket in small increments.
* The performance can be much improved by allowing AsyncSocket to read larger chunks at a time and
* store any overflow in a small internal buffer.
* This is termed pre-buffering, as some data may be read for you before you ask for it.
* If you use readDataToData a lot, enabling pre-buffering will result in better performance, especially on the iPhone.
*
* The default pre-buffering state is controlled by the DEFAULT_PREBUFFERING definition.
* It is highly recommended one leave this set to YES.
*
* This method exists in case pre-buffering needs to be disabled by default for some unforeseen reason.
* In that case, this method exists to allow one to easily enable pre-buffering when ready.
**/
- (void)enablePreBuffering;
/**
* When you create an AsyncSocket, it is added to the runloop of the current thread.
* So for manually created sockets, it is easiest to simply create the socket on the thread you intend to use it.
*
* If a new socket is accepted, the delegate method onSocket:wantsRunLoopForNewSocket: is called to
* allow you to place the socket on a separate thread. This works best in conjunction with a thread pool design.
*
* If, however, you need to move the socket to a separate thread at a later time, this
* method may be used to accomplish the task.
*
* This method must be called from the thread/runloop the socket is currently running on.
*
* Note: After calling this method, all further method calls to this object should be done from the given runloop.
* Also, all delegate calls will be sent on the given runloop.
**/
- (BOOL)moveToRunLoop:(NSRunLoop *)runLoop;
/**
* Allows you to configure which run loop modes the socket uses.
* The default set of run loop modes is NSDefaultRunLoopMode.
*
* If you'd like your socket to continue operation during other modes, you may want to add modes such as
* NSModalPanelRunLoopMode or NSEventTrackingRunLoopMode. Or you may simply want to use NSRunLoopCommonModes.
*
* Accepted sockets will automatically inherit the same run loop modes as the listening socket.
*
* Note: NSRunLoopCommonModes is defined in 10.5. For previous versions one can use kCFRunLoopCommonModes.
**/
- (BOOL)setRunLoopModes:(NSArray *)runLoopModes;
- (BOOL)addRunLoopMode:(NSString *)runLoopMode;
- (BOOL)removeRunLoopMode:(NSString *)runLoopMode;
/**
* Returns the current run loop modes the AsyncSocket instance is operating in.
* The default set of run loop modes is NSDefaultRunLoopMode.
**/
- (NSArray *)runLoopModes;
/**
* In the event of an error, this method may be called during onSocket:willDisconnectWithError: to read
* any data that's left on the socket.
**/
- (NSData *)unreadData;
/* A few common line separators, for use with the readDataToData:... methods. */
+ (NSData *)CRLFData; // 0x0D0A
+ (NSData *)CRData; // 0x0D
+ (NSData *)LFData; // 0x0A
+ (NSData *)ZeroData; // 0x00
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/AsyncSocket.h
|
Objective-C
|
oos
| 30,005
|
//
// AsyncUdpSocket.m
//
// This class is in the public domain.
// Originally created by Robbie Hanson on Wed Oct 01 2008.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import "AsyncUdpSocket.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <netdb.h>
#if TARGET_OS_IPHONE
// Note: You may need to add the CFNetwork Framework to your project
#import <CFNetwork/CFNetwork.h>
#endif
#define SENDQUEUE_CAPACITY 5 // Initial capacity
#define RECEIVEQUEUE_CAPACITY 5 // Initial capacity
#define DEFAULT_MAX_RECEIVE_BUFFER_SIZE 9216
NSString *const AsyncUdpSocketException = @"AsyncUdpSocketException";
NSString *const AsyncUdpSocketErrorDomain = @"AsyncUdpSocketErrorDomain";
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Mutex lock used by all instances of AsyncUdpSocket, to protect getaddrinfo.
// Prior to Mac OS X 10.5 this method was not thread-safe.
static NSString *getaddrinfoLock = @"lock";
#endif
enum AsyncUdpSocketFlags
{
kDidBind = 1 << 0, // If set, bind has been called.
kDidConnect = 1 << 1, // If set, connect has been called.
kSock4CanAcceptBytes = 1 << 2, // If set, we know socket4 can accept bytes. If unset, it's unknown.
kSock6CanAcceptBytes = 1 << 3, // If set, we know socket6 can accept bytes. If unset, it's unknown.
kSock4HasBytesAvailable = 1 << 4, // If set, we know socket4 has bytes available. If unset, it's unknown.
kSock6HasBytesAvailable = 1 << 5, // If set, we know socket6 has bytes available. If unset, it's unknown.
kForbidSendReceive = 1 << 6, // If set, no new send or receive operations are allowed to be queued.
kCloseAfterSends = 1 << 7, // If set, close as soon as no more sends are queued.
kCloseAfterReceives = 1 << 8, // If set, close as soon as no more receives are queued.
kDidClose = 1 << 9, // If set, the socket has been closed, and should not be used anymore.
kDequeueSendScheduled = 1 << 10, // If set, a maybeDequeueSend operation is already scheduled.
kDequeueReceiveScheduled = 1 << 11, // If set, a maybeDequeueReceive operation is already scheduled.
kFlipFlop = 1 << 12, // Used to alternate between IPv4 and IPv6 sockets.
};
@interface AsyncUdpSocket (Private)
// Run Loop
- (void)runLoopAddSource:(CFRunLoopSourceRef)source;
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source;
- (void)runLoopAddTimer:(NSTimer *)timer;
- (void)runLoopRemoveTimer:(NSTimer *)timer;
// Utilities
- (NSString *)addressHost4:(struct sockaddr_in *)pSockaddr4;
- (NSString *)addressHost6:(struct sockaddr_in6 *)pSockaddr6;
- (NSString *)addressHost:(struct sockaddr *)pSockaddr;
// Disconnect Implementation
- (void)emptyQueues;
- (void)closeSocket4;
- (void)closeSocket6;
- (void)maybeScheduleClose;
// Errors
- (NSError *)getErrnoError;
- (NSError *)getSocketError;
- (NSError *)getIPv4UnavailableError;
- (NSError *)getIPv6UnavailableError;
- (NSError *)getSendTimeoutError;
- (NSError *)getReceiveTimeoutError;
// Diagnostics
- (NSString *)connectedHost:(CFSocketRef)socket;
- (UInt16)connectedPort:(CFSocketRef)socket;
- (NSString *)localHost:(CFSocketRef)socket;
- (UInt16)localPort:(CFSocketRef)socket;
// Sending
- (BOOL)canAcceptBytes:(CFSocketRef)sockRef;
- (void)scheduleDequeueSend;
- (void)maybeDequeueSend;
- (void)doSend:(CFSocketRef)sockRef;
- (void)completeCurrentSend;
- (void)failCurrentSend:(NSError *)error;
- (void)endCurrentSend;
- (void)doSendTimeout:(NSTimer *)timer;
// Receiving
- (BOOL)hasBytesAvailable:(CFSocketRef)sockRef;
- (void)scheduleDequeueReceive;
- (void)maybeDequeueReceive;
- (void)doReceive4;
- (void)doReceive6;
- (void)doReceive:(CFSocketRef)sockRef;
- (BOOL)maybeCompleteCurrentReceive;
- (void)failCurrentReceive:(NSError *)error;
- (void)endCurrentReceive;
- (void)doReceiveTimeout:(NSTimer *)timer;
@end
static void MyCFSocketCallback(CFSocketRef, CFSocketCallBackType, CFDataRef, const void *, void *);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncSendPacket encompasses the instructions for a single send/write.
**/
@interface AsyncSendPacket : NSObject
{
@public
NSData *buffer;
NSData *address;
NSTimeInterval timeout;
long tag;
}
- (id)initWithData:(NSData *)d address:(NSData *)a timeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation AsyncSendPacket
- (id)initWithData:(NSData *)d address:(NSData *)a timeout:(NSTimeInterval)t tag:(long)i
{
if((self = [super init]))
{
buffer = [d retain];
address = [a retain];
timeout = t;
tag = i;
}
return self;
}
- (void)dealloc
{
[buffer release];
[address release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncReceivePacket encompasses the instructions for a single receive/read.
**/
@interface AsyncReceivePacket : NSObject
{
@public
NSTimeInterval timeout;
long tag;
NSMutableData *buffer;
NSString *host;
UInt16 port;
}
- (id)initWithTimeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation AsyncReceivePacket
- (id)initWithTimeout:(NSTimeInterval)t tag:(long)i
{
if((self = [super init]))
{
timeout = t;
tag = i;
buffer = nil;
host = nil;
port = 0;
}
return self;
}
- (void)dealloc
{
[buffer release];
[host release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation AsyncUdpSocket
- (id)initWithDelegate:(id)delegate userData:(long)userData enableIPv4:(BOOL)enableIPv4 enableIPv6:(BOOL)enableIPv6
{
if((self = [super init]))
{
theFlags = 0;
theDelegate = delegate;
theUserData = userData;
maxReceiveBufferSize = DEFAULT_MAX_RECEIVE_BUFFER_SIZE;
theSendQueue = [[NSMutableArray alloc] initWithCapacity:SENDQUEUE_CAPACITY];
theCurrentSend = nil;
theSendTimer = nil;
theReceiveQueue = [[NSMutableArray alloc] initWithCapacity:RECEIVEQUEUE_CAPACITY];
theCurrentReceive = nil;
theReceiveTimer = nil;
// Socket context
theContext.version = 0;
theContext.info = self;
theContext.retain = nil;
theContext.release = nil;
theContext.copyDescription = nil;
// Create the sockets
theSocket4 = NULL;
theSocket6 = NULL;
if(enableIPv4)
{
theSocket4 = CFSocketCreate(kCFAllocatorDefault,
PF_INET,
SOCK_DGRAM,
IPPROTO_UDP,
kCFSocketReadCallBack | kCFSocketWriteCallBack,
(CFSocketCallBack)&MyCFSocketCallback,
&theContext);
}
if(enableIPv6)
{
theSocket6 = CFSocketCreate(kCFAllocatorDefault,
PF_INET6,
SOCK_DGRAM,
IPPROTO_UDP,
kCFSocketReadCallBack | kCFSocketWriteCallBack,
(CFSocketCallBack)&MyCFSocketCallback,
&theContext);
}
// Disable continuous callbacks for read and write.
// If we don't do this, the socket(s) will just sit there firing read callbacks
// at us hundreds of times a second if we don't immediately read the available data.
if(theSocket4)
{
CFSocketSetSocketFlags(theSocket4, kCFSocketCloseOnInvalidate);
}
if(theSocket6)
{
CFSocketSetSocketFlags(theSocket6, kCFSocketCloseOnInvalidate);
}
// Get the CFRunLoop to which the socket should be attached.
theRunLoop = CFRunLoopGetCurrent();
// Set default run loop modes
theRunLoopModes = [[NSArray arrayWithObject:NSDefaultRunLoopMode] retain];
// Attach the sockets to the run loop
if(theSocket4)
{
theSource4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, theSocket4, 0);
[self runLoopAddSource:theSource4];
}
if(theSocket6)
{
theSource6 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, theSocket6, 0);
[self runLoopAddSource:theSource6];
}
cachedLocalPort = 0;
cachedConnectedPort = 0;
}
return self;
}
- (id)init
{
return [self initWithDelegate:nil userData:0 enableIPv4:YES enableIPv6:YES];
}
- (id)initWithDelegate:(id)delegate
{
return [self initWithDelegate:delegate userData:0 enableIPv4:YES enableIPv6:YES];
}
- (id)initWithDelegate:(id)delegate userData:(long)userData
{
return [self initWithDelegate:delegate userData:userData enableIPv4:YES enableIPv6:YES];
}
- (id)initIPv4
{
return [self initWithDelegate:nil userData:0 enableIPv4:YES enableIPv6:NO];
}
- (id)initIPv6
{
return [self initWithDelegate:nil userData:0 enableIPv4:NO enableIPv6:YES];
}
- (void) dealloc
{
[self close];
[theSendQueue release];
[theReceiveQueue release];
[theRunLoopModes release];
[cachedLocalHost release];
[cachedConnectedHost release];
[NSObject cancelPreviousPerformRequestsWithTarget:theDelegate selector:@selector(onUdpSocketDidClose:) object:self];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accessors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (id)delegate
{
return theDelegate;
}
- (void)setDelegate:(id)delegate
{
theDelegate = delegate;
}
- (long)userData
{
return theUserData;
}
- (void)setUserData:(long)userData
{
theUserData = userData;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Run Loop
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)runLoopAddSource:(CFRunLoopSourceRef)source
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopAddSource(theRunLoop, source, runLoopMode);
}
}
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopRemoveSource(theRunLoop, source, runLoopMode);
}
}
- (void)runLoopAddTimer:(NSTimer *)timer
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopAddTimer(theRunLoop, (CFRunLoopTimerRef)timer, runLoopMode);
}
}
- (void)runLoopRemoveTimer:(NSTimer *)timer
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopRemoveTimer(theRunLoop, (CFRunLoopTimerRef)timer, runLoopMode);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (UInt32)maxReceiveBufferSize
{
return maxReceiveBufferSize;
}
- (void)setMaxReceiveBufferSize:(UInt32)max
{
maxReceiveBufferSize = max;
}
/**
* See the header file for a full explanation of this method.
**/
- (BOOL)moveToRunLoop:(NSRunLoop *)runLoop
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"moveToRunLoop must be called from within the current RunLoop!");
if(runLoop == nil)
{
return NO;
}
if(theRunLoop == [runLoop getCFRunLoop])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueSendScheduled;
theFlags &= ~kDequeueReceiveScheduled;
if(theSource4) [self runLoopRemoveSource:theSource4];
if(theSource6) [self runLoopRemoveSource:theSource6];
// We do not retain the timers - they get retained by the runloop when we add them as a source.
// Since we're about to remove them as a source, we retain now, and release again below.
[theSendTimer retain];
[theReceiveTimer retain];
if(theSendTimer) [self runLoopRemoveTimer:theSendTimer];
if(theReceiveTimer) [self runLoopRemoveTimer:theReceiveTimer];
theRunLoop = [runLoop getCFRunLoop];
if(theSendTimer) [self runLoopAddTimer:theSendTimer];
if(theReceiveTimer) [self runLoopAddTimer:theReceiveTimer];
// Release timers since we retained them above
[theSendTimer release];
[theReceiveTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
[runLoop performSelector:@selector(maybeDequeueSend) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeDequeueReceive) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeScheduleClose) target:self argument:nil order:0 modes:theRunLoopModes];
return YES;
}
/**
* See the header file for a full explanation of this method.
**/
- (BOOL)setRunLoopModes:(NSArray *)runLoopModes
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"setRunLoopModes must be called from within the current RunLoop!");
if([runLoopModes count] == 0)
{
return NO;
}
if([theRunLoopModes isEqualToArray:runLoopModes])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueSendScheduled;
theFlags &= ~kDequeueReceiveScheduled;
if(theSource4) [self runLoopRemoveSource:theSource4];
if(theSource6) [self runLoopRemoveSource:theSource6];
// We do not retain the timers - they get retained by the runloop when we add them as a source.
// Since we're about to remove them as a source, we retain now, and release again below.
[theSendTimer retain];
[theReceiveTimer retain];
if(theSendTimer) [self runLoopRemoveTimer:theSendTimer];
if(theReceiveTimer) [self runLoopRemoveTimer:theReceiveTimer];
[theRunLoopModes release];
theRunLoopModes = [runLoopModes copy];
if(theSendTimer) [self runLoopAddTimer:theSendTimer];
if(theReceiveTimer) [self runLoopAddTimer:theReceiveTimer];
// Release timers since we retained them above
[theSendTimer release];
[theReceiveTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
[self performSelector:@selector(maybeDequeueSend) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeDequeueReceive) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeScheduleClose) withObject:nil afterDelay:0 inModes:theRunLoopModes];
return YES;
}
- (NSArray *)runLoopModes
{
return [[theRunLoopModes retain] autorelease];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Utilities:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Attempts to convert the given host/port into and IPv4 and/or IPv6 data structure.
* The data structure is of type sockaddr_in for IPv4 and sockaddr_in6 for IPv6.
*
* Returns zero on success, or one of the error codes listed in gai_strerror if an error occurs (as per getaddrinfo).
**/
- (int)convertForBindHost:(NSString *)host
port:(UInt16)port
intoAddress4:(NSData **)address4
address6:(NSData **)address6
{
if(host == nil || ([host length] == 0))
{
// Use ANY address
struct sockaddr_in nativeAddr;
nativeAddr.sin_len = sizeof(struct sockaddr_in);
nativeAddr.sin_family = AF_INET;
nativeAddr.sin_port = htons(port);
nativeAddr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(&(nativeAddr.sin_zero), 0, sizeof(nativeAddr.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_any;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:&nativeAddr length:sizeof(nativeAddr)];
if(address6) *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
return 0;
}
else if([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"])
{
// Note: getaddrinfo("localhost",...) fails on 10.5.3
// Use LOOPBACK address
struct sockaddr_in nativeAddr;
nativeAddr.sin_len = sizeof(struct sockaddr_in);
nativeAddr.sin_family = AF_INET;
nativeAddr.sin_port = htons(port);
nativeAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
memset(&(nativeAddr.sin_zero), 0, sizeof(nativeAddr.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_loopback;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:&nativeAddr length:sizeof(nativeAddr)];
if(address6) *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
return 0;
}
else
{
NSString *portStr = [NSString stringWithFormat:@"%hu", port];
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
@synchronized (getaddrinfoLock)
#endif
{
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_PASSIVE;
int error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
if(error) return error;
for(res = res0; res; res = res->ai_next)
{
if(address4 && !*address4 && (res->ai_family == AF_INET))
{
// Found IPv4 address
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
else if(address6 && !*address6 && (res->ai_family == AF_INET6))
{
// Found IPv6 address
// Wrap the native address structures for CFSocketSetAddress.
if(address6) *address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
}
freeaddrinfo(res0);
}
return 0;
}
}
/**
* Attempts to convert the given host/port into and IPv4 and/or IPv6 data structure.
* The data structure is of type sockaddr_in for IPv4 and sockaddr_in6 for IPv6.
*
* Returns zero on success, or one of the error codes listed in gai_strerror if an error occurs (as per getaddrinfo).
**/
- (int)convertForSendHost:(NSString *)host
port:(UInt16)port
intoAddress4:(NSData **)address4
address6:(NSData **)address6
{
if(host == nil || ([host length] == 0))
{
// We're not binding, so what are we supposed to do with this?
return EAI_NONAME;
}
else if([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"])
{
// Note: getaddrinfo("localhost",...) fails on 10.5.3
// Use LOOPBACK address
struct sockaddr_in nativeAddr;
nativeAddr.sin_len = sizeof(struct sockaddr_in);
nativeAddr.sin_family = AF_INET;
nativeAddr.sin_port = htons(port);
nativeAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
memset(&(nativeAddr.sin_zero), 0, sizeof(nativeAddr.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_loopback;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:&nativeAddr length:sizeof(nativeAddr)];
if(address6) *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
return 0;
}
else
{
NSString *portStr = [NSString stringWithFormat:@"%hu", port];
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
@synchronized (getaddrinfoLock)
#endif
{
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
// No passive flag on a send or connect
int error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
if(error) return error;
for(res = res0; res; res = res->ai_next)
{
if(address4 && !*address4 && (res->ai_family == AF_INET))
{
// Found IPv4 address
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
else if(address6 && !*address6 && (res->ai_family == AF_INET6))
{
// Found IPv6 address
// Wrap the native address structures for CFSocketSetAddress.
if(address6) *address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
}
freeaddrinfo(res0);
}
return 0;
}
}
- (NSString *)addressHost4:(struct sockaddr_in *)pSockaddr4
{
char addrBuf[INET_ADDRSTRLEN];
if(inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, sizeof(addrBuf)) == NULL)
{
[NSException raise:NSInternalInconsistencyException format:@"Cannot convert address to string."];
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
- (NSString *)addressHost6:(struct sockaddr_in6 *)pSockaddr6
{
char addrBuf[INET6_ADDRSTRLEN];
if(inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, sizeof(addrBuf)) == NULL)
{
[NSException raise:NSInternalInconsistencyException format:@"Cannot convert address to string."];
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
- (NSString *)addressHost:(struct sockaddr *)pSockaddr
{
if(pSockaddr->sa_family == AF_INET)
{
return [self addressHost4:(struct sockaddr_in *)pSockaddr];
}
else
{
return [self addressHost6:(struct sockaddr_in6 *)pSockaddr];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Socket Implementation:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Binds the underlying socket(s) to the given port.
* The socket(s) will be able to receive data on any interface.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)bindToPort:(UInt16)port error:(NSError **)errPtr
{
return [self bindToAddress:nil port:port error:errPtr];
}
/**
* Binds the underlying socket(s) to the given address and port.
* The sockets(s) will be able to receive data only on the given interface.
*
* To receive data on any interface, pass nil or "".
* To receive data only on the loopback interface, pass "localhost" or "loopback".
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)bindToAddress:(NSString *)host port:(UInt16)port error:(NSError **)errPtr
{
if(theFlags & kDidClose)
{
[NSException raise:AsyncUdpSocketException
format:@"The socket is closed."];
}
if(theFlags & kDidBind)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot bind a socket more than once."];
}
if(theFlags & kDidConnect)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot bind after connecting. If needed, bind first, then connect."];
}
// Convert the given host/port into native address structures for CFSocketSetAddress
NSData *address4 = nil, *address6 = nil;
int gai_error = [self convertForBindHost:host port:port intoAddress4:&address4 address6:&address6];
if(gai_error)
{
if(errPtr)
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(gai_error) encoding:NSASCIIStringEncoding];
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:gai_error userInfo:info];
}
return NO;
}
NSAssert((address4 || address6), @"address4 and address6 are nil");
// Set the SO_REUSEADDR flags
int reuseOn = 1;
if (theSocket4) setsockopt(CFSocketGetNative(theSocket4), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
if (theSocket6) setsockopt(CFSocketGetNative(theSocket6), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
// Bind the sockets
if(address4)
{
if(theSocket4)
{
CFSocketError error = CFSocketSetAddress(theSocket4, (CFDataRef)address4);
if(error != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
if(!address6)
{
// Using IPv4 only
[self closeSocket6];
}
}
else if(!address6)
{
if(errPtr) *errPtr = [self getIPv4UnavailableError];
return NO;
}
}
if(address6)
{
// Note: The iPhone doesn't currently support IPv6
if(theSocket6)
{
CFSocketError error = CFSocketSetAddress(theSocket6, (CFDataRef)address6);
if(error != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
if(!address4)
{
// Using IPv6 only
[self closeSocket4];
}
}
else if(!address4)
{
if(errPtr) *errPtr = [self getIPv6UnavailableError];
return NO;
}
}
theFlags |= kDidBind;
return YES;
}
/**
* Connects the underlying UDP socket to the given host and port.
* If an IPv4 address is resolved, the IPv4 socket is connected, and the IPv6 socket is invalidated and released.
* If an IPv6 address is resolved, the IPv6 socket is connected, and the IPv4 socket is invalidated and released.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)connectToHost:(NSString *)host onPort:(UInt16)port error:(NSError **)errPtr
{
if(theFlags & kDidClose)
{
[NSException raise:AsyncUdpSocketException
format:@"The socket is closed."];
}
if(theFlags & kDidConnect)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot connect a socket more than once."];
}
// Convert the given host/port into native address structures for CFSocketSetAddress
NSData *address4 = nil, *address6 = nil;
int error = [self convertForSendHost:host port:port intoAddress4:&address4 address6:&address6];
if(error)
{
if(errPtr)
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(error) encoding:NSASCIIStringEncoding];
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:error userInfo:info];
}
return NO;
}
NSAssert((address4 || address6), @"address4 and address6 are nil");
// We only want to connect via a single interface.
// IPv4 is currently preferred, but this may change in the future.
if(address4)
{
if(theSocket4)
{
CFSocketError sockErr = CFSocketConnectToAddress(theSocket4, (CFDataRef)address4, (CFTimeInterval)0.0);
if(sockErr != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
theFlags |= kDidConnect;
// We're connected to an IPv4 address, so no need for the IPv6 socket
[self closeSocket6];
return YES;
}
else if(!address6)
{
if(errPtr) *errPtr = [self getIPv4UnavailableError];
return NO;
}
}
if(address6)
{
// Note: The iPhone doesn't currently support IPv6
if(theSocket6)
{
CFSocketError sockErr = CFSocketConnectToAddress(theSocket6, (CFDataRef)address6, (CFTimeInterval)0.0);
if(sockErr != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
theFlags |= kDidConnect;
// We're connected to an IPv6 address, so no need for the IPv4 socket
[self closeSocket4];
return YES;
}
else
{
if(errPtr) *errPtr = [self getIPv6UnavailableError];
return NO;
}
}
// It shouldn't be possible to get to this point because either address4 or address6 was non-nil.
if(errPtr) *errPtr = nil;
return NO;
}
/**
* Connects the underlying UDP socket to the remote address.
* If the address is an IPv4 address, the IPv4 socket is connected, and the IPv6 socket is invalidated and released.
* If the address is an IPv6 address, the IPv6 socket is connected, and the IPv4 socket is invalidated and released.
*
* The address is a native address structure, as may be returned from API's such as Bonjour.
* An address may be created manually by simply wrapping a sockaddr_in or sockaddr_in6 in an NSData object.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr
{
if(theFlags & kDidClose)
{
[NSException raise:AsyncUdpSocketException
format:@"The socket is closed."];
}
if(theFlags & kDidConnect)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot connect a socket more than once."];
}
// Is remoteAddr an IPv4 address?
if([remoteAddr length] == sizeof(struct sockaddr_in))
{
if(theSocket4)
{
CFSocketError error = CFSocketConnectToAddress(theSocket4, (CFDataRef)remoteAddr, (CFTimeInterval)0.0);
if(error != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
theFlags |= kDidConnect;
// We're connected to an IPv4 address, so no need for the IPv6 socket
[self closeSocket6];
return YES;
}
else
{
if(errPtr) *errPtr = [self getIPv4UnavailableError];
return NO;
}
}
// Is remoteAddr an IPv6 address?
if([remoteAddr length] == sizeof(struct sockaddr_in6))
{
if(theSocket6)
{
CFSocketError error = CFSocketConnectToAddress(theSocket6, (CFDataRef)remoteAddr, (CFTimeInterval)0.0);
if(error != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
theFlags |= kDidConnect;
// We're connected to an IPv6 address, so no need for the IPv4 socket
[self closeSocket4];
return YES;
}
else
{
if(errPtr) *errPtr = [self getIPv6UnavailableError];
return NO;
}
}
// The remoteAddr was invalid
if(errPtr)
{
NSString *errMsg = @"remoteAddr parameter is not a valid address";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:AsyncUdpSocketErrorDomain
code:AsyncUdpSocketBadParameter
userInfo:info];
}
return NO;
}
/**
* Join multicast group
*
* Group should be a multicast IP address (eg. @"239.255.250.250" for IPv4).
* Address is local interface for IPv4, but currently defaults under IPv6.
**/
- (BOOL)joinMulticastGroup:(NSString *)group error:(NSError **)errPtr
{
return [self joinMulticastGroup:group withAddress:nil error:errPtr];
}
- (BOOL)joinMulticastGroup:(NSString *)group withAddress:(NSString *)address error:(NSError **)errPtr
{
if(theFlags & kDidClose)
{
[NSException raise:AsyncUdpSocketException
format:@"The socket is closed."];
}
if(!(theFlags & kDidBind))
{
[NSException raise:AsyncUdpSocketException
format:@"Must bind a socket before joining a multicast group."];
}
if(theFlags & kDidConnect)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot join a multicast group if connected."];
}
// Get local interface address
// Convert the given host/port into native address structures for CFSocketSetAddress
NSData *address4 = nil, *address6 = nil;
int error = [self convertForBindHost:address port:0 intoAddress4:&address4 address6:&address6];
if(error)
{
if(errPtr)
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(error) encoding:NSASCIIStringEncoding];
NSString *errDsc = [NSString stringWithFormat:@"Invalid parameter 'address': %@", errMsg];
NSDictionary *info = [NSDictionary dictionaryWithObject:errDsc forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:error userInfo:info];
}
return NO;
}
NSAssert((address4 || address6), @"address4 and address6 are nil");
// Get multicast address (group)
NSData *group4 = nil, *group6 = nil;
error = [self convertForBindHost:group port:0 intoAddress4:&group4 address6:&group6];
if(error)
{
if(errPtr)
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(error) encoding:NSASCIIStringEncoding];
NSString *errDsc = [NSString stringWithFormat:@"Invalid parameter 'group': %@", errMsg];
NSDictionary *info = [NSDictionary dictionaryWithObject:errDsc forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:error userInfo:info];
}
return NO;
}
NSAssert((group4 || group6), @"group4 and group6 are nil");
if(theSocket4 && group4 && address4)
{
const struct sockaddr_in* nativeAddress = [address4 bytes];
const struct sockaddr_in* nativeGroup = [group4 bytes];
struct ip_mreq imreq;
imreq.imr_multiaddr = nativeGroup->sin_addr;
imreq.imr_interface = nativeAddress->sin_addr;
// JOIN multicast group on default interface
error = setsockopt(CFSocketGetNative(theSocket4), IPPROTO_IP, IP_ADD_MEMBERSHIP,
(const void *)&imreq, sizeof(struct ip_mreq));
if(error)
{
if(errPtr)
{
NSString *errMsg = @"Unable to join IPv4 multicast group";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainPOSIX" code:error userInfo:info];
}
return NO;
}
// Using IPv4 only
[self closeSocket6];
return YES;
}
if(theSocket6 && group6 && address6)
{
const struct sockaddr_in6* nativeGroup = [group6 bytes];
struct ipv6_mreq imreq;
imreq.ipv6mr_multiaddr = nativeGroup->sin6_addr;
imreq.ipv6mr_interface = 0;
// JOIN multicast group on default interface
error = setsockopt(CFSocketGetNative(theSocket6), IPPROTO_IP, IPV6_JOIN_GROUP,
(const void *)&imreq, sizeof(struct ipv6_mreq));
if(error)
{
if(errPtr)
{
NSString *errMsg = @"Unable to join IPv6 multicast group";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainPOSIX" code:error userInfo:info];
}
return NO;
}
// Using IPv6 only
[self closeSocket4];
return YES;
}
// The given address and group didn't match the existing socket(s).
// This means there were no compatible combination of all IPv4 or IPv6 socket, group and address.
if(errPtr)
{
NSString *errMsg = @"Invalid group and/or address, not matching existing socket(s)";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:AsyncUdpSocketErrorDomain
code:AsyncUdpSocketBadParameter
userInfo:info];
}
return NO;
}
/**
* By default, the underlying socket in the OS will not allow you to send broadcast messages.
* In order to send broadcast messages, you need to enable this functionality in the socket.
*
* A broadcast is a UDP message to addresses like "192.168.255.255" or "255.255.255.255" that is
* delivered to every host on the network.
* The reason this is generally disabled by default is to prevent
* accidental broadcast messages from flooding the network.
**/
- (BOOL)enableBroadcast:(BOOL)flag error:(NSError **)errPtr
{
if (theSocket4)
{
int value = flag ? 1 : 0;
int error = setsockopt(CFSocketGetNative(theSocket4), SOL_SOCKET, SO_BROADCAST,
(const void *)&value, sizeof(value));
if(error)
{
if(errPtr)
{
NSString *errMsg = @"Unable to enable broadcast message sending";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainPOSIX" code:error userInfo:info];
}
return NO;
}
}
// IPv6 does not implement broadcast, the ability to send a packet to all hosts on the attached link.
// The same effect can be achieved by sending a packet to the link-local all hosts multicast group.
return YES;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Disconnect Implementation:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)emptyQueues
{
if (theCurrentSend) [self endCurrentSend];
if (theCurrentReceive) [self endCurrentReceive];
[theSendQueue removeAllObjects];
[theReceiveQueue removeAllObjects];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(maybeDequeueSend) object:nil];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(maybeDequeueReceive) object:nil];
theFlags &= ~kDequeueSendScheduled;
theFlags &= ~kDequeueReceiveScheduled;
}
- (void)closeSocket4
{
if (theSocket4 != NULL)
{
CFSocketInvalidate(theSocket4);
CFRelease(theSocket4);
theSocket4 = NULL;
}
if (theSource4 != NULL)
{
[self runLoopRemoveSource:theSource4];
CFRelease(theSource4);
theSource4 = NULL;
}
}
- (void)closeSocket6
{
if (theSocket6 != NULL)
{
CFSocketInvalidate(theSocket6);
CFRelease(theSocket6);
theSocket6 = NULL;
}
if (theSource6 != NULL)
{
[self runLoopRemoveSource:theSource6];
CFRelease(theSource6);
theSource6 = NULL;
}
}
- (void)close
{
[self emptyQueues];
[self closeSocket4];
[self closeSocket6];
theRunLoop = NULL;
// Delay notification to give user freedom to release without returning here and core-dumping.
if ([theDelegate respondsToSelector:@selector(onUdpSocketDidClose:)])
{
[theDelegate performSelector:@selector(onUdpSocketDidClose:)
withObject:self
afterDelay:0
inModes:theRunLoopModes];
}
theFlags |= kDidClose;
}
- (void)closeAfterSending
{
if(theFlags & kDidClose) return;
theFlags |= (kForbidSendReceive | kCloseAfterSends);
[self maybeScheduleClose];
}
- (void)closeAfterReceiving
{
if(theFlags & kDidClose) return;
theFlags |= (kForbidSendReceive | kCloseAfterReceives);
[self maybeScheduleClose];
}
- (void)closeAfterSendingAndReceiving
{
if(theFlags & kDidClose) return;
theFlags |= (kForbidSendReceive | kCloseAfterSends | kCloseAfterReceives);
[self maybeScheduleClose];
}
- (void)maybeScheduleClose
{
BOOL shouldDisconnect = NO;
if(theFlags & kCloseAfterSends)
{
if(([theSendQueue count] == 0) && (theCurrentSend == nil))
{
if(theFlags & kCloseAfterReceives)
{
if(([theReceiveQueue count] == 0) && (theCurrentReceive == nil))
{
shouldDisconnect = YES;
}
}
else
{
shouldDisconnect = YES;
}
}
}
else if(theFlags & kCloseAfterReceives)
{
if(([theReceiveQueue count] == 0) && (theCurrentReceive == nil))
{
shouldDisconnect = YES;
}
}
if(shouldDisconnect)
{
[self performSelector:@selector(close) withObject:nil afterDelay:0 inModes:theRunLoopModes];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Errors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns a standard error object for the current errno value.
* Errno is used for low-level BSD socket errors.
**/
- (NSError *)getErrnoError
{
NSString *errorMsg = [NSString stringWithUTF8String:strerror(errno)];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo];
}
/**
* Returns a standard error message for a CFSocket error.
* Unfortunately, CFSocket offers no feedback on its errors.
**/
- (NSError *)getSocketError
{
NSString *errMsg = @"General CFSocket error";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncUdpSocketErrorDomain code:AsyncUdpSocketCFSocketError userInfo:info];
}
- (NSError *)getIPv4UnavailableError
{
NSString *errMsg = @"IPv4 is unavailable due to binding/connecting using IPv6 only";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncUdpSocketErrorDomain code:AsyncUdpSocketIPv4Unavailable userInfo:info];
}
- (NSError *)getIPv6UnavailableError
{
NSString *errMsg = @"IPv6 is unavailable due to binding/connecting using IPv4 only or is not supported on this platform";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncUdpSocketErrorDomain code:AsyncUdpSocketIPv6Unavailable userInfo:info];
}
- (NSError *)getSendTimeoutError
{
NSString *errMsg = @"Send operation timed out";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncUdpSocketErrorDomain code:AsyncUdpSocketSendTimeoutError userInfo:info];
}
- (NSError *)getReceiveTimeoutError
{
NSString *errMsg = @"Receive operation timed out";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncUdpSocketErrorDomain code:AsyncUdpSocketReceiveTimeoutError userInfo:info];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Diagnostics
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString *)localHost
{
if(cachedLocalHost) return cachedLocalHost;
if(theSocket4)
return [self localHost:theSocket4];
else
return [self localHost:theSocket6];
}
- (UInt16)localPort
{
if(cachedLocalPort > 0) return cachedLocalPort;
if(theSocket4)
return [self localPort:theSocket4];
else
return [self localPort:theSocket6];
}
- (NSString *)connectedHost
{
if(cachedConnectedHost) return cachedConnectedHost;
if(theSocket4)
return [self connectedHost:theSocket4];
else
return [self connectedHost:theSocket6];
}
- (UInt16)connectedPort
{
if(cachedConnectedPort > 0) return cachedConnectedPort;
if(theSocket4)
return [self connectedPort:theSocket4];
else
return [self connectedPort:theSocket6];
}
- (NSString *)localHost:(CFSocketRef)theSocket
{
if(theSocket == NULL) return nil;
// Unfortunately we can't use CFSocketCopyAddress.
// The CFSocket library caches the address the first time you call CFSocketCopyAddress.
// So if this is called prior to binding/connecting/sending, it won't be updated again when necessary,
// and will continue to return the old value of the socket address.
NSString *result = nil;
if(theSocket == theSocket4)
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getsockname(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return nil;
}
result = [self addressHost4:&sockaddr4];
}
else
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getsockname(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return nil;
}
result = [self addressHost6:&sockaddr6];
}
if(theFlags & kDidBind)
{
[cachedLocalHost release];
cachedLocalHost = [result copy];
}
return result;
}
- (UInt16)localPort:(CFSocketRef)theSocket
{
if(theSocket == NULL) return 0;
// Unfortunately we can't use CFSocketCopyAddress.
// The CFSocket library caches the address the first time you call CFSocketCopyAddress.
// So if this is called prior to binding/connecting/sending, it won't be updated again when necessary,
// and will continue to return the old value of the socket address.
UInt16 result = 0;
if(theSocket == theSocket4)
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getsockname(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return 0;
}
result = ntohs(sockaddr4.sin_port);
}
else
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getsockname(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return 0;
}
result = ntohs(sockaddr6.sin6_port);
}
if(theFlags & kDidBind)
{
cachedLocalPort = result;
}
return result;
}
- (NSString *)connectedHost:(CFSocketRef)theSocket
{
if(theSocket == NULL) return nil;
// Unfortunately we can't use CFSocketCopyPeerAddress.
// The CFSocket library caches the address the first time you call CFSocketCopyPeerAddress.
// So if this is called prior to binding/connecting/sending, it may not be updated again when necessary,
// and will continue to return the old value of the socket peer address.
NSString *result = nil;
if(theSocket == theSocket4)
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getpeername(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return nil;
}
result = [self addressHost4:&sockaddr4];
}
else
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getpeername(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return nil;
}
result = [self addressHost6:&sockaddr6];
}
if(theFlags & kDidConnect)
{
[cachedConnectedHost release];
cachedConnectedHost = [result copy];
}
return result;
}
- (UInt16)connectedPort:(CFSocketRef)theSocket
{
if(theSocket == NULL) return 0;
// Unfortunately we can't use CFSocketCopyPeerAddress.
// The CFSocket library caches the address the first time you call CFSocketCopyPeerAddress.
// So if this is called prior to binding/connecting/sending, it may not be updated again when necessary,
// and will continue to return the old value of the socket peer address.
UInt16 result = 0;
if(theSocket == theSocket4)
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getpeername(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return 0;
}
result = ntohs(sockaddr4.sin_port);
}
else
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getpeername(CFSocketGetNative(theSocket), (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return 0;
}
result = ntohs(sockaddr6.sin6_port);
}
if(theFlags & kDidConnect)
{
cachedConnectedPort = result;
}
return result;
}
- (BOOL)isConnected
{
return (((theFlags & kDidConnect) != 0) && ((theFlags & kDidClose) == 0));
}
- (BOOL)isConnectedToHost:(NSString *)host port:(UInt16)port
{
return [[self connectedHost] isEqualToString:host] && ([self connectedPort] == port);
}
- (BOOL)isClosed
{
return (theFlags & kDidClose) ? YES : NO;
}
- (BOOL)isIPv4
{
return (theSocket4 != NULL);
}
- (BOOL)isIPv6
{
return (theSocket6 != NULL);
}
- (unsigned int)maximumTransmissionUnit
{
CFSocketNativeHandle theNativeSocket;
if(theSocket4)
theNativeSocket = CFSocketGetNative(theSocket4);
else if(theSocket6)
theNativeSocket = CFSocketGetNative(theSocket6);
else
return 0;
if(theNativeSocket == 0)
{
return 0;
}
struct ifreq ifr;
bzero(&ifr, sizeof(ifr));
if(if_indextoname(theNativeSocket, ifr.ifr_name) == NULL)
{
return 0;
}
if(ioctl(theNativeSocket, SIOCGIFMTU, &ifr) >= 0)
{
return ifr.ifr_mtu;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Sending
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)sendData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
if((data == nil) || ([data length] == 0)) return NO;
if(theFlags & kForbidSendReceive) return NO;
if(theFlags & kDidClose) return NO;
// This method is only for connected sockets
if(![self isConnected]) return NO;
AsyncSendPacket *packet = [[AsyncSendPacket alloc] initWithData:data address:nil timeout:timeout tag:tag];
[theSendQueue addObject:packet];
[self scheduleDequeueSend];
[packet release];
return YES;
}
- (BOOL)sendData:(NSData *)data toHost:(NSString *)host port:(UInt16)port withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
if((data == nil) || ([data length] == 0)) return NO;
if(theFlags & kForbidSendReceive) return NO;
if(theFlags & kDidClose) return NO;
// This method is only for non-connected sockets
if([self isConnected]) return NO;
NSData *address4 = nil, *address6 = nil;
[self convertForSendHost:host port:port intoAddress4:&address4 address6:&address6];
AsyncSendPacket *packet = nil;
if(address4 && theSocket4)
packet = [[AsyncSendPacket alloc] initWithData:data address:address4 timeout:timeout tag:tag];
else if(address6 && theSocket6)
packet = [[AsyncSendPacket alloc] initWithData:data address:address6 timeout:timeout tag:tag];
else
return NO;
[theSendQueue addObject:packet];
[self scheduleDequeueSend];
[packet release];
return YES;
}
- (BOOL)sendData:(NSData *)data toAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
if((data == nil) || ([data length] == 0)) return NO;
if(theFlags & kForbidSendReceive) return NO;
if(theFlags & kDidClose) return NO;
// This method is only for non-connected sockets
if([self isConnected]) return NO;
if([remoteAddr length] == sizeof(struct sockaddr_in) && !theSocket4)
return NO;
if([remoteAddr length] == sizeof(struct sockaddr_in6) && !theSocket6)
return NO;
AsyncSendPacket *packet = [[AsyncSendPacket alloc] initWithData:data address:remoteAddr timeout:timeout tag:tag];
[theSendQueue addObject:packet];
[self scheduleDequeueSend];
[packet release];
return YES;
}
- (BOOL)canAcceptBytes:(CFSocketRef)sockRef
{
if(sockRef == theSocket4)
{
if(theFlags & kSock4CanAcceptBytes) return YES;
}
else
{
if(theFlags & kSock6CanAcceptBytes) return YES;
}
CFSocketNativeHandle theNativeSocket = CFSocketGetNative(sockRef);
if(theNativeSocket == 0)
{
NSLog(@"Error - Could not get CFSocketNativeHandle from CFSocketRef");
return NO;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(theNativeSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
return select(FD_SETSIZE, NULL, &fds, NULL, &timeout) > 0;
}
- (CFSocketRef)socketForPacket:(AsyncSendPacket *)packet
{
if(!theSocket4)
return theSocket6;
if(!theSocket6)
return theSocket4;
return ([packet->address length] == sizeof(struct sockaddr_in)) ? theSocket4 : theSocket6;
}
/**
* Puts a maybeDequeueSend on the run loop.
**/
- (void)scheduleDequeueSend
{
if((theFlags & kDequeueSendScheduled) == 0)
{
theFlags |= kDequeueSendScheduled;
[self performSelector:@selector(maybeDequeueSend) withObject:nil afterDelay:0 inModes:theRunLoopModes];
}
}
/**
* This method starts a new send, if needed.
* It is called when a user requests a send.
**/
- (void)maybeDequeueSend
{
// Unset the flag indicating a call to this method is scheduled
theFlags &= ~kDequeueSendScheduled;
if(theCurrentSend == nil)
{
if([theSendQueue count] > 0)
{
// Dequeue next send packet
theCurrentSend = [[theSendQueue objectAtIndex:0] retain];
[theSendQueue removeObjectAtIndex:0];
// Start time-out timer.
if(theCurrentSend->timeout >= 0.0)
{
theSendTimer = [NSTimer timerWithTimeInterval:theCurrentSend->timeout
target:self
selector:@selector(doSendTimeout:)
userInfo:nil
repeats:NO];
[self runLoopAddTimer:theSendTimer];
}
// Immediately send, if possible.
[self doSend:[self socketForPacket:theCurrentSend]];
}
else if(theFlags & kCloseAfterSends)
{
if(theFlags & kCloseAfterReceives)
{
if(([theReceiveQueue count] == 0) && (theCurrentReceive == nil))
{
[self close];
}
}
else
{
[self close];
}
}
}
}
/**
* This method is called when a new read is taken from the read queue or when new data becomes available on the stream.
**/
- (void)doSend:(CFSocketRef)theSocket
{
if(theCurrentSend != nil)
{
if(theSocket != [self socketForPacket:theCurrentSend])
{
// Current send is for the other socket
return;
}
if([self canAcceptBytes:theSocket])
{
ssize_t result;
CFSocketNativeHandle theNativeSocket = CFSocketGetNative(theSocket);
const void *buf = [theCurrentSend->buffer bytes];
NSUInteger bufSize = [theCurrentSend->buffer length];
if([self isConnected])
{
result = send(theNativeSocket, buf, (size_t)bufSize, 0);
}
else
{
const void *dst = [theCurrentSend->address bytes];
NSUInteger dstSize = [theCurrentSend->address length];
result = sendto(theNativeSocket, buf, (size_t)bufSize, 0, dst, (socklen_t)dstSize);
}
if(theSocket == theSocket4)
theFlags &= ~kSock4CanAcceptBytes;
else
theFlags &= ~kSock6CanAcceptBytes;
if(result < 0)
{
[self failCurrentSend:[self getErrnoError]];
}
else
{
// If it wasn't bound before, it's bound now
theFlags |= kDidBind;
[self completeCurrentSend];
}
[self scheduleDequeueSend];
}
else
{
// Request notification when the socket is ready to send more data
CFSocketEnableCallBacks(theSocket, kCFSocketReadCallBack | kCFSocketWriteCallBack);
}
}
}
- (void)completeCurrentSend
{
NSAssert (theCurrentSend, @"Trying to complete current send when there is no current send.");
if ([theDelegate respondsToSelector:@selector(onUdpSocket:didSendDataWithTag:)])
{
[theDelegate onUdpSocket:self didSendDataWithTag:theCurrentSend->tag];
}
if (theCurrentSend != nil) [self endCurrentSend]; // Caller may have disconnected.
}
- (void)failCurrentSend:(NSError *)error
{
NSAssert (theCurrentSend, @"Trying to fail current send when there is no current send.");
if ([theDelegate respondsToSelector:@selector(onUdpSocket:didNotSendDataWithTag:dueToError:)])
{
[theDelegate onUdpSocket:self didNotSendDataWithTag:theCurrentSend->tag dueToError:error];
}
if (theCurrentSend != nil) [self endCurrentSend]; // Caller may have disconnected.
}
/**
* Ends the current send, and all associated variables such as the send timer.
**/
- (void)endCurrentSend
{
NSAssert (theCurrentSend, @"Trying to end current send when there is no current send.");
[theSendTimer invalidate];
theSendTimer = nil;
[theCurrentSend release];
theCurrentSend = nil;
}
- (void)doSendTimeout:(NSTimer *)timer
{
if (timer != theSendTimer) return; // Old timer. Ignore it.
if (theCurrentSend != nil)
{
[self failCurrentSend:[self getSendTimeoutError]];
[self scheduleDequeueSend];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Receiving
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)receiveWithTimeout:(NSTimeInterval)timeout tag:(long)tag
{
if(theFlags & kForbidSendReceive) return;
if(theFlags & kDidClose) return;
AsyncReceivePacket *packet = [[AsyncReceivePacket alloc] initWithTimeout:timeout tag:tag];
[theReceiveQueue addObject:packet];
[self scheduleDequeueReceive];
[packet release];
}
- (BOOL)hasBytesAvailable:(CFSocketRef)sockRef
{
if(sockRef == theSocket4)
{
if(theFlags & kSock4HasBytesAvailable) return YES;
}
else
{
if(theFlags & kSock6HasBytesAvailable) return YES;
}
CFSocketNativeHandle theNativeSocket = CFSocketGetNative(sockRef);
if(theNativeSocket == 0)
{
NSLog(@"Error - Could not get CFSocketNativeHandle from CFSocketRef");
return NO;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(theNativeSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
return select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0;
}
/**
* Puts a maybeDequeueReceive on the run loop.
**/
- (void)scheduleDequeueReceive
{
if((theFlags & kDequeueReceiveScheduled) == 0)
{
theFlags |= kDequeueReceiveScheduled;
[self performSelector:@selector(maybeDequeueReceive) withObject:nil afterDelay:0 inModes:theRunLoopModes];
}
}
/**
* Starts a new receive operation if needed
**/
- (void)maybeDequeueReceive
{
// Unset the flag indicating a call to this method is scheduled
theFlags &= ~kDequeueReceiveScheduled;
if (theCurrentReceive == nil)
{
if([theReceiveQueue count] > 0)
{
// Dequeue next receive packet
theCurrentReceive = [[theReceiveQueue objectAtIndex:0] retain];
[theReceiveQueue removeObjectAtIndex:0];
// Start time-out timer.
if (theCurrentReceive->timeout >= 0.0)
{
theReceiveTimer = [NSTimer timerWithTimeInterval:theCurrentReceive->timeout
target:self
selector:@selector(doReceiveTimeout:)
userInfo:nil
repeats:NO];
[self runLoopAddTimer:theReceiveTimer];
}
// Immediately receive, if possible
// We always check both sockets so we don't ever starve one of them.
// We also check them in alternating orders to prevent starvation if both of them
// have a continuous flow of incoming data.
if(theFlags & kFlipFlop)
{
[self doReceive4];
[self doReceive6];
}
else
{
[self doReceive6];
[self doReceive4];
}
theFlags ^= kFlipFlop;
}
else if(theFlags & kCloseAfterReceives)
{
if(theFlags & kCloseAfterSends)
{
if(([theSendQueue count] == 0) && (theCurrentSend == nil))
{
[self close];
}
}
else
{
[self close];
}
}
}
}
- (void)doReceive4
{
if(theSocket4) [self doReceive:theSocket4];
}
- (void)doReceive6
{
if(theSocket6) [self doReceive:theSocket6];
}
- (void)doReceive:(CFSocketRef)theSocket
{
if (theCurrentReceive != nil)
{
BOOL appIgnoredReceivedData;
BOOL userIgnoredReceivedData;
do
{
// Set or reset ignored variables.
// If the app or user ignores the received data, we'll continue this do-while loop.
appIgnoredReceivedData = NO;
userIgnoredReceivedData = NO;
if([self hasBytesAvailable:theSocket])
{
ssize_t result;
CFSocketNativeHandle theNativeSocket = CFSocketGetNative(theSocket);
// Allocate buffer for recvfrom operation.
// If the operation is successful, we'll realloc the buffer to the appropriate size,
// and create an NSData wrapper around it without needing to copy any bytes around.
void *buf = malloc(maxReceiveBufferSize);
size_t bufSize = maxReceiveBufferSize;
if(theSocket == theSocket4)
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
result = recvfrom(theNativeSocket, buf, bufSize, 0, (struct sockaddr *)&sockaddr4, &sockaddr4len);
if(result >= 0)
{
NSString *host = [self addressHost4:&sockaddr4];
UInt16 port = ntohs(sockaddr4.sin_port);
if([self isConnected] && ![self isConnectedToHost:host port:port])
{
// The user connected to an address, and the received data doesn't match the address.
// This may happen if the data is received by the kernel prior to the connect call.
appIgnoredReceivedData = YES;
}
else
{
if(result != bufSize)
{
buf = realloc(buf, result);
}
theCurrentReceive->buffer = [[NSData alloc] initWithBytesNoCopy:buf
length:result
freeWhenDone:YES];
theCurrentReceive->host = [host retain];
theCurrentReceive->port = port;
}
}
theFlags &= ~kSock4HasBytesAvailable;
}
else
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
result = recvfrom(theNativeSocket, buf, bufSize, 0, (struct sockaddr *)&sockaddr6, &sockaddr6len);
if(result >= 0)
{
NSString *host = [self addressHost6:&sockaddr6];
UInt16 port = ntohs(sockaddr6.sin6_port);
if([self isConnected] && ![self isConnectedToHost:host port:port])
{
// The user connected to an address, and the received data doesn't match the address.
// This may happen if the data is received by the kernel prior to the connect call.
appIgnoredReceivedData = YES;
}
else
{
if(result != bufSize)
{
buf = realloc(buf, result);
}
theCurrentReceive->buffer = [[NSData alloc] initWithBytesNoCopy:buf
length:result
freeWhenDone:YES];
theCurrentReceive->host = [host retain];
theCurrentReceive->port = port;
}
}
theFlags &= ~kSock6HasBytesAvailable;
}
// Check to see if we need to free our alloc'd buffer
// If the buffer is non-nil, this means it has taken ownership of the buffer
if(theCurrentReceive->buffer == nil)
{
free(buf);
}
if(result < 0)
{
[self failCurrentReceive:[self getErrnoError]];
[self scheduleDequeueReceive];
}
else if(!appIgnoredReceivedData)
{
BOOL finished = [self maybeCompleteCurrentReceive];
if(finished)
{
[self scheduleDequeueReceive];
}
else
{
[theCurrentReceive->buffer release];
[theCurrentReceive->host release];
theCurrentReceive->buffer = nil;
theCurrentReceive->host = nil;
userIgnoredReceivedData = YES;
}
}
}
else
{
// Request notification when the socket is ready to receive more data
CFSocketEnableCallBacks(theSocket, kCFSocketReadCallBack | kCFSocketWriteCallBack);
}
} while(appIgnoredReceivedData || userIgnoredReceivedData);
}
}
- (BOOL)maybeCompleteCurrentReceive
{
NSAssert (theCurrentReceive, @"Trying to complete current receive when there is no current receive.");
BOOL finished = YES;
if ([theDelegate respondsToSelector:@selector(onUdpSocket:didReceiveData:withTag:fromHost:port:)])
{
finished = [theDelegate onUdpSocket:self
didReceiveData:theCurrentReceive->buffer
withTag:theCurrentReceive->tag
fromHost:theCurrentReceive->host
port:theCurrentReceive->port];
}
if (finished)
{
if (theCurrentReceive != nil) [self endCurrentReceive]; // Caller may have disconnected.
}
return finished;
}
- (void)failCurrentReceive:(NSError *)error
{
NSAssert (theCurrentReceive, @"Trying to fail current receive when there is no current receive.");
if ([theDelegate respondsToSelector:@selector(onUdpSocket:didNotReceiveDataWithTag:dueToError:)])
{
[theDelegate onUdpSocket:self didNotReceiveDataWithTag:theCurrentReceive->tag dueToError:error];
}
if (theCurrentReceive != nil) [self endCurrentReceive]; // Caller may have disconnected.
}
- (void)endCurrentReceive
{
NSAssert (theCurrentReceive, @"Trying to end current receive when there is no current receive.");
[theReceiveTimer invalidate];
theReceiveTimer = nil;
[theCurrentReceive release];
theCurrentReceive = nil;
}
- (void)doReceiveTimeout:(NSTimer *)timer
{
if (timer != theReceiveTimer) return; // Old timer. Ignore it.
if (theCurrentReceive != nil)
{
[self failCurrentReceive:[self getReceiveTimeoutError]];
[self scheduleDequeueReceive];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark CF Callbacks
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)doCFSocketCallback:(CFSocketCallBackType)type
forSocket:(CFSocketRef)sock
withAddress:(NSData *)address
withData:(const void *)pData
{
NSParameterAssert((sock == theSocket4) || (sock == theSocket6));
switch (type)
{
case kCFSocketReadCallBack:
if(sock == theSocket4)
theFlags |= kSock4HasBytesAvailable;
else
theFlags |= kSock6HasBytesAvailable;
[self doReceive:sock];
break;
case kCFSocketWriteCallBack:
if(sock == theSocket4)
theFlags |= kSock4CanAcceptBytes;
else
theFlags |= kSock6CanAcceptBytes;
[self doSend:sock];
break;
default:
NSLog (@"AsyncUdpSocket %p received unexpected CFSocketCallBackType %lu.", self, (unsigned long)type);
break;
}
}
/**
* This is the callback we setup for CFSocket.
* This method does nothing but forward the call to it's Objective-C counterpart
**/
static void MyCFSocketCallback(CFSocketRef sref, CFSocketCallBackType type, CFDataRef address, const void *pData, void *pInfo)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AsyncUdpSocket *theSocket = [[(AsyncUdpSocket *)pInfo retain] autorelease];
[theSocket doCFSocketCallback:type forSocket:sref withAddress:(NSData *)address withData:pData];
[pool release];
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/AsyncUdpSocket.m
|
Objective-C
|
oos
| 66,311
|
//
// AsyncSocket.m
//
// This class is in the public domain.
// Originally created by Dustin Voss on Wed Jan 29 2003.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import "AsyncSocket.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>
#if TARGET_OS_IPHONE
// Note: You may need to add the CFNetwork Framework to your project
#import <CFNetwork/CFNetwork.h>
#endif
#pragma mark Declarations
#define DEFAULT_PREBUFFERING YES // Whether pre-buffering is enabled by default
#define READQUEUE_CAPACITY 5 // Initial capacity
#define WRITEQUEUE_CAPACITY 5 // Initial capacity
#define READALL_CHUNKSIZE 256 // Incremental increase in buffer size
#define WRITE_CHUNKSIZE (1024 * 4) // Limit on size of each write pass
// AsyncSocket is RunLoop based, and is thus not thread-safe.
// You must always access your AsyncSocket instance from the thread/runloop in which the instance is running.
// You can use methods such as performSelectorOnThread to accomplish this.
// Failure to comply with these thread-safety rules may result in errors.
// You can enable this option to help diagnose where you are incorrectly accessing your socket.
#define DEBUG_THREAD_SAFETY 0
//
// If you constantly need to access your socket from multiple threads
// then you may consider using GCDAsyncSocket instead, which is thread-safe.
NSString *const AsyncSocketException = @"AsyncSocketException";
NSString *const AsyncSocketErrorDomain = @"AsyncSocketErrorDomain";
enum AsyncSocketFlags
{
kEnablePreBuffering = 1 << 0, // If set, pre-buffering is enabled
kDidStartDelegate = 1 << 1, // If set, disconnection results in delegate call
kDidCompleteOpenForRead = 1 << 2, // If set, open callback has been called for read stream
kDidCompleteOpenForWrite = 1 << 3, // If set, open callback has been called for write stream
kStartingReadTLS = 1 << 4, // If set, we're waiting for TLS negotiation to complete
kStartingWriteTLS = 1 << 5, // If set, we're waiting for TLS negotiation to complete
kForbidReadsWrites = 1 << 6, // If set, no new reads or writes are allowed
kDisconnectAfterReads = 1 << 7, // If set, disconnect after no more reads are queued
kDisconnectAfterWrites = 1 << 8, // If set, disconnect after no more writes are queued
kClosingWithError = 1 << 9, // If set, the socket is being closed due to an error
kDequeueReadScheduled = 1 << 10, // If set, a maybeDequeueRead operation is already scheduled
kDequeueWriteScheduled = 1 << 11, // If set, a maybeDequeueWrite operation is already scheduled
kSocketCanAcceptBytes = 1 << 12, // If set, we know socket can accept bytes. If unset, it's unknown.
kSocketHasBytesAvailable = 1 << 13, // If set, we know socket has bytes available. If unset, it's unknown.
};
@interface AsyncSocket (Private)
// Connecting
- (void)startConnectTimeout:(NSTimeInterval)timeout;
- (void)endConnectTimeout;
- (void)doConnectTimeout:(NSTimer *)timer;
// Socket Implementation
- (CFSocketRef)newAcceptSocketForAddress:(NSData *)addr error:(NSError **)errPtr;
- (BOOL)createSocketForAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
- (BOOL)bindSocketToAddress:(NSData *)interfaceAddr error:(NSError **)errPtr;
- (BOOL)attachSocketsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr;
- (BOOL)configureSocketAndReturnError:(NSError **)errPtr;
- (BOOL)connectSocketToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
- (void)doAcceptWithSocket:(CFSocketNativeHandle)newSocket;
- (void)doSocketOpen:(CFSocketRef)sock withCFSocketError:(CFSocketError)err;
// Stream Implementation
- (BOOL)createStreamsFromNative:(CFSocketNativeHandle)native error:(NSError **)errPtr;
- (BOOL)createStreamsToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr;
- (BOOL)attachStreamsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr;
- (BOOL)configureStreamsAndReturnError:(NSError **)errPtr;
- (BOOL)openStreamsAndReturnError:(NSError **)errPtr;
- (void)doStreamOpen;
- (BOOL)setSocketFromStreamsAndReturnError:(NSError **)errPtr;
// Disconnect Implementation
- (void)closeWithError:(NSError *)err;
- (void)recoverUnreadData;
- (void)emptyQueues;
- (void)close;
// Errors
- (NSError *)getErrnoError;
- (NSError *)getAbortError;
- (NSError *)getStreamError;
- (NSError *)getSocketError;
- (NSError *)getConnectTimeoutError;
- (NSError *)getReadMaxedOutError;
- (NSError *)getReadTimeoutError;
- (NSError *)getWriteTimeoutError;
- (NSError *)errorFromCFStreamError:(CFStreamError)err;
// Diagnostics
- (BOOL)isDisconnected;
- (BOOL)areStreamsConnected;
- (NSString *)connectedHostFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)connectedHostFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)connectedHostFromCFSocket4:(CFSocketRef)socket;
- (NSString *)connectedHostFromCFSocket6:(CFSocketRef)socket;
- (UInt16)connectedPortFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)connectedPortFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)connectedPortFromCFSocket4:(CFSocketRef)socket;
- (UInt16)connectedPortFromCFSocket6:(CFSocketRef)socket;
- (NSString *)localHostFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)localHostFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)localHostFromCFSocket4:(CFSocketRef)socket;
- (NSString *)localHostFromCFSocket6:(CFSocketRef)socket;
- (UInt16)localPortFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)localPortFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)localPortFromCFSocket4:(CFSocketRef)socket;
- (UInt16)localPortFromCFSocket6:(CFSocketRef)socket;
- (NSString *)hostFromAddress4:(struct sockaddr_in *)pSockaddr4;
- (NSString *)hostFromAddress6:(struct sockaddr_in6 *)pSockaddr6;
- (UInt16)portFromAddress4:(struct sockaddr_in *)pSockaddr4;
- (UInt16)portFromAddress6:(struct sockaddr_in6 *)pSockaddr6;
// Reading
- (void)doBytesAvailable;
- (void)completeCurrentRead;
- (void)endCurrentRead;
- (void)scheduleDequeueRead;
- (void)maybeDequeueRead;
- (void)doReadTimeout:(NSTimer *)timer;
// Writing
- (void)doSendBytes;
- (void)completeCurrentWrite;
- (void)endCurrentWrite;
- (void)scheduleDequeueWrite;
- (void)maybeDequeueWrite;
- (void)maybeScheduleDisconnect;
- (void)doWriteTimeout:(NSTimer *)timer;
// Run Loop
- (void)runLoopAddSource:(CFRunLoopSourceRef)source;
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source;
- (void)runLoopAddTimer:(NSTimer *)timer;
- (void)runLoopRemoveTimer:(NSTimer *)timer;
- (void)runLoopUnscheduleReadStream;
- (void)runLoopUnscheduleWriteStream;
// Security
- (void)maybeStartTLS;
- (void)onTLSHandshakeSuccessful;
// Callbacks
- (void)doCFCallback:(CFSocketCallBackType)type
forSocket:(CFSocketRef)sock withAddress:(NSData *)address withData:(const void *)pData;
- (void)doCFReadStreamCallback:(CFStreamEventType)type forStream:(CFReadStreamRef)stream;
- (void)doCFWriteStreamCallback:(CFStreamEventType)type forStream:(CFWriteStreamRef)stream;
@end
static void MyCFSocketCallback(CFSocketRef, CFSocketCallBackType, CFDataRef, const void *, void *);
static void MyCFReadStreamCallback(CFReadStreamRef stream, CFStreamEventType type, void *pInfo);
static void MyCFWriteStreamCallback(CFWriteStreamRef stream, CFStreamEventType type, void *pInfo);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncReadPacket encompasses the instructions for any given read.
* The content of a read packet allows the code to determine if we're:
* - reading to a certain length
* - reading to a certain separator
* - or simply reading the first chunk of available data
**/
@interface AsyncReadPacket : NSObject
{
@public
NSMutableData *buffer;
NSUInteger startOffset;
NSUInteger bytesDone;
NSUInteger maxLength;
NSTimeInterval timeout;
NSUInteger readLength;
NSData *term;
BOOL bufferOwner;
NSUInteger originalBufferLength;
long tag;
}
- (id)initWithData:(NSMutableData *)d
startOffset:(NSUInteger)s
maxLength:(NSUInteger)m
timeout:(NSTimeInterval)t
readLength:(NSUInteger)l
terminator:(NSData *)e
tag:(long)i;
- (NSUInteger)readLengthForNonTerm;
- (NSUInteger)readLengthForTerm;
- (NSUInteger)readLengthForTermWithPreBuffer:(NSData *)preBuffer found:(BOOL *)foundPtr;
- (NSUInteger)prebufferReadLengthForTerm;
- (NSInteger)searchForTermAfterPreBuffering:(NSUInteger)numBytes;
@end
@implementation AsyncReadPacket
- (id)initWithData:(NSMutableData *)d
startOffset:(NSUInteger)s
maxLength:(NSUInteger)m
timeout:(NSTimeInterval)t
readLength:(NSUInteger)l
terminator:(NSData *)e
tag:(long)i
{
if((self = [super init]))
{
if (d)
{
buffer = [d retain];
startOffset = s;
bufferOwner = NO;
originalBufferLength = [d length];
}
else
{
if (readLength > 0)
buffer = [[NSMutableData alloc] initWithLength:readLength];
else
buffer = [[NSMutableData alloc] initWithLength:0];
startOffset = 0;
bufferOwner = YES;
originalBufferLength = 0;
}
bytesDone = 0;
maxLength = m;
timeout = t;
readLength = l;
term = [e copy];
tag = i;
}
return self;
}
/**
* For read packets without a set terminator, returns the safe length of data that can be read
* without exceeding the maxLength, or forcing a resize of the buffer if at all possible.
**/
- (NSUInteger)readLengthForNonTerm
{
NSAssert(term == nil, @"This method does not apply to term reads");
if (readLength > 0)
{
// Read a specific length of data
return readLength - bytesDone;
// No need to avoid resizing the buffer.
// It should be resized if the buffer space is less than the requested read length.
}
else
{
// Read all available data
NSUInteger result = READALL_CHUNKSIZE;
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
if (!bufferOwner)
{
// We did NOT create the buffer.
// It is owned by the caller.
// Avoid resizing the buffer if at all possible.
if ([buffer length] == originalBufferLength)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffSpace = buffSize - startOffset - bytesDone;
if (buffSpace > 0)
{
result = MIN(result, buffSpace);
}
}
}
return result;
}
}
/**
* For read packets with a set terminator, returns the safe length of data that can be read
* without going over a terminator, or the maxLength, or forcing a resize of the buffer if at all possible.
*
* It is assumed the terminator has not already been read.
**/
- (NSUInteger)readLengthForTerm
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
// What we're going to do is look for a partial sequence of the terminator at the end of the buffer.
// If a partial sequence occurs, then we must assume the next bytes to arrive will be the rest of the term,
// and we can only read that amount.
// Otherwise, we're safe to read the entire length of the term.
NSUInteger termLength = [term length];
// Shortcuts
if (bytesDone == 0) return termLength;
if (termLength == 1) return termLength;
// i = index within buffer at which to check data
// j = length of term to check against
NSUInteger i, j;
if (bytesDone >= termLength)
{
i = bytesDone - termLength + 1;
j = termLength - 1;
}
else
{
i = 0;
j = bytesDone;
}
NSUInteger result = termLength;
void *buf = [buffer mutableBytes];
const void *termBuf = [term bytes];
while (i < bytesDone)
{
void *subbuf = buf + startOffset + i;
if (memcmp(subbuf, termBuf, j) == 0)
{
result = termLength - j;
break;
}
i++;
j--;
}
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
if (!bufferOwner)
{
// We did NOT create the buffer.
// It is owned by the caller.
// Avoid resizing the buffer if at all possible.
if ([buffer length] == originalBufferLength)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffSpace = buffSize - startOffset - bytesDone;
if (buffSpace > 0)
{
result = MIN(result, buffSpace);
}
}
}
return result;
}
/**
* For read packets with a set terminator,
* returns the safe length of data that can be read from the given preBuffer,
* without going over a terminator or the maxLength.
*
* It is assumed the terminator has not already been read.
**/
- (NSUInteger)readLengthForTermWithPreBuffer:(NSData *)preBuffer found:(BOOL *)foundPtr
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSAssert([preBuffer length] > 0, @"Invoked with empty pre buffer!");
// We know that the terminator, as a whole, doesn't exist in our own buffer.
// But it is possible that a portion of it exists in our buffer.
// So we're going to look for the terminator starting with a portion of our own buffer.
//
// Example:
//
// term length = 3 bytes
// bytesDone = 5 bytes
// preBuffer length = 5 bytes
//
// If we append the preBuffer to our buffer,
// it would look like this:
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------------------
//
// So we start our search here:
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// -------^-^-^---------
//
// And move forwards...
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------^-^-^-------
//
// Until we find the terminator or reach the end.
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------------^-^-^-
BOOL found = NO;
NSUInteger termLength = [term length];
NSUInteger preBufferLength = [preBuffer length];
if ((bytesDone + preBufferLength) < termLength)
{
// Not enough data for a full term sequence yet
return preBufferLength;
}
NSUInteger maxPreBufferLength;
if (maxLength > 0) {
maxPreBufferLength = MIN(preBufferLength, (maxLength - bytesDone));
// Note: maxLength >= termLength
}
else {
maxPreBufferLength = preBufferLength;
}
Byte seq[termLength];
const void *termBuf = [term bytes];
NSUInteger bufLen = MIN(bytesDone, (termLength - 1));
void *buf = [buffer mutableBytes] + startOffset + bytesDone - bufLen;
NSUInteger preLen = termLength - bufLen;
void *pre = (void *)[preBuffer bytes];
NSUInteger loopCount = bufLen + maxPreBufferLength - termLength + 1; // Plus one. See example above.
NSUInteger result = preBufferLength;
NSUInteger i;
for (i = 0; i < loopCount; i++)
{
if (bufLen > 0)
{
// Combining bytes from buffer and preBuffer
memcpy(seq, buf, bufLen);
memcpy(seq + bufLen, pre, preLen);
if (memcmp(seq, termBuf, termLength) == 0)
{
result = preLen;
found = YES;
break;
}
buf++;
bufLen--;
preLen++;
}
else
{
// Comparing directly from preBuffer
if (memcmp(pre, termBuf, termLength) == 0)
{
NSUInteger preOffset = pre - [preBuffer bytes]; // pointer arithmetic
result = preOffset + termLength;
found = YES;
break;
}
pre++;
}
}
// There is no need to avoid resizing the buffer in this particular situation.
if (foundPtr) *foundPtr = found;
return result;
}
/**
* Assuming pre-buffering is enabled, returns the amount of data that can be read
* without going over the maxLength.
**/
- (NSUInteger)prebufferReadLengthForTerm
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSUInteger result = READALL_CHUNKSIZE;
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
if (!bufferOwner)
{
// We did NOT create the buffer.
// It is owned by the caller.
// Avoid resizing the buffer if at all possible.
if ([buffer length] == originalBufferLength)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffSpace = buffSize - startOffset - bytesDone;
if (buffSpace > 0)
{
result = MIN(result, buffSpace);
}
}
}
return result;
}
/**
* For read packets with a set terminator, scans the packet buffer for the term.
* It is assumed the terminator had not been fully read prior to the new bytes.
*
* If the term is found, the number of excess bytes after the term are returned.
* If the term is not found, this method will return -1.
*
* Note: A return value of zero means the term was found at the very end.
**/
- (NSInteger)searchForTermAfterPreBuffering:(NSUInteger)numBytes
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSAssert(bytesDone >= numBytes, @"Invoked with invalid numBytes!");
// We try to start the search such that the first new byte read matches up with the last byte of the term.
// We continue searching forward after this until the term no longer fits into the buffer.
NSUInteger termLength = [term length];
const void *termBuffer = [term bytes];
// Remember: This method is called after the bytesDone variable has been updated.
NSUInteger prevBytesDone = bytesDone - numBytes;
NSUInteger i;
if (prevBytesDone >= termLength)
i = prevBytesDone - termLength + 1;
else
i = 0;
while ((i + termLength) <= bytesDone)
{
void *subBuffer = [buffer mutableBytes] + startOffset + i;
if(memcmp(subBuffer, termBuffer, termLength) == 0)
{
return bytesDone - (i + termLength);
}
i++;
}
return -1;
}
- (void)dealloc
{
[buffer release];
[term release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncWritePacket encompasses the instructions for any given write.
**/
@interface AsyncWritePacket : NSObject
{
@public
NSData *buffer;
NSUInteger bytesDone;
long tag;
NSTimeInterval timeout;
}
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation AsyncWritePacket
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
{
if((self = [super init]))
{
buffer = [d retain];
timeout = t;
tag = i;
bytesDone = 0;
}
return self;
}
- (void)dealloc
{
[buffer release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncSpecialPacket encompasses special instructions for interruptions in the read/write queues.
* This class my be altered to support more than just TLS in the future.
**/
@interface AsyncSpecialPacket : NSObject
{
@public
NSDictionary *tlsSettings;
}
- (id)initWithTLSSettings:(NSDictionary *)settings;
@end
@implementation AsyncSpecialPacket
- (id)initWithTLSSettings:(NSDictionary *)settings
{
if((self = [super init]))
{
tlsSettings = [settings copy];
}
return self;
}
- (void)dealloc
{
[tlsSettings release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation AsyncSocket
- (id)init
{
return [self initWithDelegate:nil userData:0];
}
- (id)initWithDelegate:(id)delegate
{
return [self initWithDelegate:delegate userData:0];
}
// Designated initializer.
- (id)initWithDelegate:(id)delegate userData:(long)userData
{
if((self = [super init]))
{
theFlags = DEFAULT_PREBUFFERING ? kEnablePreBuffering : 0;
theDelegate = delegate;
theUserData = userData;
theNativeSocket4 = 0;
theNativeSocket6 = 0;
theSocket4 = NULL;
theSource4 = NULL;
theSocket6 = NULL;
theSource6 = NULL;
theRunLoop = NULL;
theReadStream = NULL;
theWriteStream = NULL;
theConnectTimer = nil;
theReadQueue = [[NSMutableArray alloc] initWithCapacity:READQUEUE_CAPACITY];
theCurrentRead = nil;
theReadTimer = nil;
partialReadBuffer = [[NSMutableData alloc] initWithCapacity:READALL_CHUNKSIZE];
theWriteQueue = [[NSMutableArray alloc] initWithCapacity:WRITEQUEUE_CAPACITY];
theCurrentWrite = nil;
theWriteTimer = nil;
// Socket context
NSAssert(sizeof(CFSocketContext) == sizeof(CFStreamClientContext), @"CFSocketContext != CFStreamClientContext");
theContext.version = 0;
theContext.info = self;
theContext.retain = nil;
theContext.release = nil;
theContext.copyDescription = nil;
// Default run loop modes
theRunLoopModes = [[NSArray arrayWithObject:NSDefaultRunLoopMode] retain];
}
return self;
}
// The socket may been initialized in a connected state and auto-released, so this should close it down cleanly.
- (void)dealloc
{
[self close];
[theReadQueue release];
[theWriteQueue release];
[theRunLoopModes release];
[partialReadBuffer release];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Thread-Safety
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)checkForThreadSafety
{
if (theRunLoop && (theRunLoop != CFRunLoopGetCurrent()))
{
// AsyncSocket is RunLoop based.
// It is designed to be run and accessed from a particular thread/runloop.
// As such, it is faster as it does not have the overhead of locks/synchronization.
//
// However, this places a minimal requirement on the developer to maintain thread-safety.
// If you are seeing errors or crashes in AsyncSocket,
// it is very likely that thread-safety has been broken.
// This method may be enabled via the DEBUG_THREAD_SAFETY macro,
// and will allow you to discover the place in your code where thread-safety is being broken.
[NSException raise:AsyncSocketException
format:@"Attempting to access AsyncSocket instance from incorrect thread."];
// Note:
//
// If you find you constantly need to access your socket from various threads,
// you may prefer to use GCDAsyncSocket which is thread-safe.
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accessors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (long)userData
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theUserData;
}
- (void)setUserData:(long)userData
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theUserData = userData;
}
- (id)delegate
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theDelegate;
}
- (void)setDelegate:(id)delegate
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theDelegate = delegate;
}
- (BOOL)canSafelySetDelegate
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return ([theReadQueue count] == 0 && [theWriteQueue count] == 0 && theCurrentRead == nil && theCurrentWrite == nil);
}
- (CFSocketRef)getCFSocket
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if(theSocket4)
return theSocket4;
else
return theSocket6;
}
- (CFReadStreamRef)getCFReadStream
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theReadStream;
}
- (CFWriteStreamRef)getCFWriteStream
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theWriteStream;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Progress
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (float)progressOfReadReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
// Check to make sure we're actually reading something right now,
// and that the read packet isn't an AsyncSpecialPacket (upgrade to TLS).
if (!theCurrentRead || ![theCurrentRead isKindOfClass:[AsyncReadPacket class]])
{
if (tag != NULL) *tag = 0;
if (done != NULL) *done = 0;
if (total != NULL) *total = 0;
return NAN;
}
// It's only possible to know the progress of our read if we're reading to a certain length.
// If we're reading to data, we of course have no idea when the data will arrive.
// If we're reading to timeout, then we have no idea when the next chunk of data will arrive.
NSUInteger d = theCurrentRead->bytesDone;
NSUInteger t = theCurrentRead->readLength;
if (tag != NULL) *tag = theCurrentRead->tag;
if (done != NULL) *done = d;
if (total != NULL) *total = t;
if (t > 0.0)
return (float)d / (float)t;
else
return 1.0F;
}
- (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
// Check to make sure we're actually writing something right now,
// and that the write packet isn't an AsyncSpecialPacket (upgrade to TLS).
if (!theCurrentWrite || ![theCurrentWrite isKindOfClass:[AsyncWritePacket class]])
{
if (tag != NULL) *tag = 0;
if (done != NULL) *done = 0;
if (total != NULL) *total = 0;
return NAN;
}
NSUInteger d = theCurrentWrite->bytesDone;
NSUInteger t = [theCurrentWrite->buffer length];
if (tag != NULL) *tag = theCurrentWrite->tag;
if (done != NULL) *done = d;
if (total != NULL) *total = t;
return (float)d / (float)t;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Run Loop
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)runLoopAddSource:(CFRunLoopSourceRef)source
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopAddSource(theRunLoop, source, (CFStringRef)runLoopMode);
}
}
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopRemoveSource(theRunLoop, source, (CFStringRef)runLoopMode);
}
}
- (void)runLoopAddSource:(CFRunLoopSourceRef)source mode:(NSString *)runLoopMode
{
CFRunLoopAddSource(theRunLoop, source, (CFStringRef)runLoopMode);
}
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source mode:(NSString *)runLoopMode
{
CFRunLoopRemoveSource(theRunLoop, source, (CFStringRef)runLoopMode);
}
- (void)runLoopAddTimer:(NSTimer *)timer
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopAddTimer(theRunLoop, (CFRunLoopTimerRef)timer, (CFStringRef)runLoopMode);
}
}
- (void)runLoopRemoveTimer:(NSTimer *)timer
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopRemoveTimer(theRunLoop, (CFRunLoopTimerRef)timer, (CFStringRef)runLoopMode);
}
}
- (void)runLoopAddTimer:(NSTimer *)timer mode:(NSString *)runLoopMode
{
CFRunLoopAddTimer(theRunLoop, (CFRunLoopTimerRef)timer, (CFStringRef)runLoopMode);
}
- (void)runLoopRemoveTimer:(NSTimer *)timer mode:(NSString *)runLoopMode
{
CFRunLoopRemoveTimer(theRunLoop, (CFRunLoopTimerRef)timer, (CFStringRef)runLoopMode);
}
- (void)runLoopUnscheduleReadStream
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFReadStreamUnscheduleFromRunLoop(theReadStream, theRunLoop, (CFStringRef)runLoopMode);
}
CFReadStreamSetClient(theReadStream, kCFStreamEventNone, NULL, NULL);
}
- (void)runLoopUnscheduleWriteStream
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFWriteStreamUnscheduleFromRunLoop(theWriteStream, theRunLoop, (CFStringRef)runLoopMode);
}
CFWriteStreamSetClient(theWriteStream, kCFStreamEventNone, NULL, NULL);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* See the header file for a full explanation of pre-buffering.
**/
- (void)enablePreBuffering
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theFlags |= kEnablePreBuffering;
}
/**
* See the header file for a full explanation of this method.
**/
- (BOOL)moveToRunLoop:(NSRunLoop *)runLoop
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"moveToRunLoop must be called from within the current RunLoop!");
if(runLoop == nil)
{
return NO;
}
if(theRunLoop == [runLoop getCFRunLoop])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
if(theReadStream && theWriteStream)
{
[self runLoopUnscheduleReadStream];
[self runLoopUnscheduleWriteStream];
}
if(theSource4) [self runLoopRemoveSource:theSource4];
if(theSource6) [self runLoopRemoveSource:theSource6];
// We do not retain the timers - they get retained by the runloop when we add them as a source.
// Since we're about to remove them as a source, we retain now, and release again below.
[theReadTimer retain];
[theWriteTimer retain];
if(theReadTimer) [self runLoopRemoveTimer:theReadTimer];
if(theWriteTimer) [self runLoopRemoveTimer:theWriteTimer];
theRunLoop = [runLoop getCFRunLoop];
if(theReadTimer) [self runLoopAddTimer:theReadTimer];
if(theWriteTimer) [self runLoopAddTimer:theWriteTimer];
// Release timers since we retained them above
[theReadTimer release];
[theWriteTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
if(theReadStream && theWriteStream)
{
if(![self attachStreamsToRunLoop:runLoop error:nil])
{
return NO;
}
}
[runLoop performSelector:@selector(maybeDequeueRead) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeDequeueWrite) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeScheduleDisconnect) target:self argument:nil order:0 modes:theRunLoopModes];
return YES;
}
/**
* See the header file for a full explanation of this method.
**/
- (BOOL)setRunLoopModes:(NSArray *)runLoopModes
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"setRunLoopModes must be called from within the current RunLoop!");
if([runLoopModes count] == 0)
{
return NO;
}
if([theRunLoopModes isEqualToArray:runLoopModes])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
if(theReadStream && theWriteStream)
{
[self runLoopUnscheduleReadStream];
[self runLoopUnscheduleWriteStream];
}
if(theSource4) [self runLoopRemoveSource:theSource4];
if(theSource6) [self runLoopRemoveSource:theSource6];
// We do not retain the timers - they get retained by the runloop when we add them as a source.
// Since we're about to remove them as a source, we retain now, and release again below.
[theReadTimer retain];
[theWriteTimer retain];
if(theReadTimer) [self runLoopRemoveTimer:theReadTimer];
if(theWriteTimer) [self runLoopRemoveTimer:theWriteTimer];
[theRunLoopModes release];
theRunLoopModes = [runLoopModes copy];
if(theReadTimer) [self runLoopAddTimer:theReadTimer];
if(theWriteTimer) [self runLoopAddTimer:theWriteTimer];
// Release timers since we retained them above
[theReadTimer release];
[theWriteTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
if(theReadStream && theWriteStream)
{
// Note: theRunLoop variable is a CFRunLoop, and NSRunLoop is NOT toll-free bridged with CFRunLoop.
// So we cannot pass theRunLoop to the method below, which is expecting a NSRunLoop parameter.
// Instead we pass nil, which will result in the method properly using the current run loop.
if(![self attachStreamsToRunLoop:nil error:nil])
{
return NO;
}
}
[self performSelector:@selector(maybeDequeueRead) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeDequeueWrite) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeScheduleDisconnect) withObject:nil afterDelay:0 inModes:theRunLoopModes];
return YES;
}
- (BOOL)addRunLoopMode:(NSString *)runLoopMode
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"addRunLoopMode must be called from within the current RunLoop!");
if(runLoopMode == nil)
{
return NO;
}
if([theRunLoopModes containsObject:runLoopMode])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
NSArray *newRunLoopModes = [theRunLoopModes arrayByAddingObject:runLoopMode];
[theRunLoopModes release];
theRunLoopModes = [newRunLoopModes retain];
if(theReadTimer) [self runLoopAddTimer:theReadTimer mode:runLoopMode];
if(theWriteTimer) [self runLoopAddTimer:theWriteTimer mode:runLoopMode];
if(theSource4) [self runLoopAddSource:theSource4 mode:runLoopMode];
if(theSource6) [self runLoopAddSource:theSource6 mode:runLoopMode];
if(theReadStream && theWriteStream)
{
CFReadStreamScheduleWithRunLoop(theReadStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);
CFWriteStreamScheduleWithRunLoop(theWriteStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);
}
[self performSelector:@selector(maybeDequeueRead) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeDequeueWrite) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeScheduleDisconnect) withObject:nil afterDelay:0 inModes:theRunLoopModes];
return YES;
}
- (BOOL)removeRunLoopMode:(NSString *)runLoopMode
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"addRunLoopMode must be called from within the current RunLoop!");
if(runLoopMode == nil)
{
return NO;
}
if(![theRunLoopModes containsObject:runLoopMode])
{
return YES;
}
NSMutableArray *newRunLoopModes = [[theRunLoopModes mutableCopy] autorelease];
[newRunLoopModes removeObject:runLoopMode];
if([newRunLoopModes count] == 0)
{
return NO;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
[theRunLoopModes release];
theRunLoopModes = [newRunLoopModes copy];
if(theReadTimer) [self runLoopRemoveTimer:theReadTimer mode:runLoopMode];
if(theWriteTimer) [self runLoopRemoveTimer:theWriteTimer mode:runLoopMode];
if(theSource4) [self runLoopRemoveSource:theSource4 mode:runLoopMode];
if(theSource6) [self runLoopRemoveSource:theSource6 mode:runLoopMode];
if(theReadStream && theWriteStream)
{
CFReadStreamScheduleWithRunLoop(theReadStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);
CFWriteStreamScheduleWithRunLoop(theWriteStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);
}
[self performSelector:@selector(maybeDequeueRead) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeDequeueWrite) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeScheduleDisconnect) withObject:nil afterDelay:0 inModes:theRunLoopModes];
return YES;
}
- (NSArray *)runLoopModes
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return [[theRunLoopModes retain] autorelease];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accepting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)acceptOnPort:(UInt16)port error:(NSError **)errPtr
{
return [self acceptOnInterface:nil port:port error:errPtr];
}
/**
* To accept on a certain interface, pass the address to accept on.
* To accept on any interface, pass nil or an empty string.
* To accept only connections from localhost pass "localhost" or "loopback".
**/
- (BOOL)acceptOnInterface:(NSString *)interface port:(UInt16)port error:(NSError **)errPtr
{
if (theDelegate == NULL)
{
[NSException raise:AsyncSocketException
format:@"Attempting to accept without a delegate. Set a delegate first."];
}
if (![self isDisconnected])
{
[NSException raise:AsyncSocketException
format:@"Attempting to accept while connected or accepting connections. Disconnect first."];
}
// Clear queues (spurious read/write requests post disconnect)
[self emptyQueues];
// Set up the listen sockaddr structs if needed.
NSData *address4 = nil, *address6 = nil;
if(interface == nil || ([interface length] == 0))
{
// Accept on ANY address
struct sockaddr_in nativeAddr4;
nativeAddr4.sin_len = sizeof(struct sockaddr_in);
nativeAddr4.sin_family = AF_INET;
nativeAddr4.sin_port = htons(port);
nativeAddr4.sin_addr.s_addr = htonl(INADDR_ANY);
memset(&(nativeAddr4.sin_zero), 0, sizeof(nativeAddr4.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_any;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
address4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
}
else if([interface isEqualToString:@"localhost"] || [interface isEqualToString:@"loopback"])
{
// Accept only on LOOPBACK address
struct sockaddr_in nativeAddr4;
nativeAddr4.sin_len = sizeof(struct sockaddr_in);
nativeAddr4.sin_family = AF_INET;
nativeAddr4.sin_port = htons(port);
nativeAddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
memset(&(nativeAddr4.sin_zero), 0, sizeof(nativeAddr4.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_loopback;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
address4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
}
else
{
NSString *portStr = [NSString stringWithFormat:@"%hu", port];
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
int error = getaddrinfo([interface UTF8String], [portStr UTF8String], &hints, &res0);
if (error)
{
if (errPtr)
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(error) encoding:NSASCIIStringEncoding];
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:error userInfo:info];
}
}
else
{
for (res = res0; res; res = res->ai_next)
{
if (!address4 && (res->ai_family == AF_INET))
{
// Found IPv4 address
// Wrap the native address structures for CFSocketSetAddress.
address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
else if (!address6 && (res->ai_family == AF_INET6))
{
// Found IPv6 address
// Wrap the native address structures for CFSocketSetAddress.
address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
}
freeaddrinfo(res0);
}
if(!address4 && !address6) return NO;
}
// Create the sockets.
if (address4)
{
theSocket4 = [self newAcceptSocketForAddress:address4 error:errPtr];
if (theSocket4 == NULL) goto Failed;
}
if (address6)
{
theSocket6 = [self newAcceptSocketForAddress:address6 error:errPtr];
// Note: The iPhone doesn't currently support IPv6
#if !TARGET_OS_IPHONE
if (theSocket6 == NULL) goto Failed;
#endif
}
// Attach the sockets to the run loop so that callback methods work
[self attachSocketsToRunLoop:nil error:nil];
// Set the SO_REUSEADDR flags.
int reuseOn = 1;
if (theSocket4) setsockopt(CFSocketGetNative(theSocket4), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
if (theSocket6) setsockopt(CFSocketGetNative(theSocket6), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
// Set the local bindings which causes the sockets to start listening.
CFSocketError err;
if (theSocket4)
{
err = CFSocketSetAddress(theSocket4, (CFDataRef)address4);
if (err != kCFSocketSuccess) goto Failed;
//NSLog(@"theSocket4: %hu", [self localPortFromCFSocket4:theSocket4]);
}
if(port == 0 && theSocket4 && theSocket6)
{
// The user has passed in port 0, which means he wants to allow the kernel to choose the port for them
// However, the kernel will choose a different port for both theSocket4 and theSocket6
// So we grab the port the kernel choose for theSocket4, and set it as the port for theSocket6
UInt16 chosenPort = [self localPortFromCFSocket4:theSocket4];
struct sockaddr_in6 *pSockAddr6 = (struct sockaddr_in6 *)[address6 bytes];
if (pSockAddr6) // If statement to quiet the static analyzer
{
pSockAddr6->sin6_port = htons(chosenPort);
}
}
if (theSocket6)
{
err = CFSocketSetAddress(theSocket6, (CFDataRef)address6);
if (err != kCFSocketSuccess) goto Failed;
//NSLog(@"theSocket6: %hu", [self localPortFromCFSocket6:theSocket6]);
}
theFlags |= kDidStartDelegate;
return YES;
Failed:
if(errPtr) *errPtr = [self getSocketError];
if(theSocket4 != NULL)
{
CFSocketInvalidate(theSocket4);
CFRelease(theSocket4);
theSocket4 = NULL;
}
if(theSocket6 != NULL)
{
CFSocketInvalidate(theSocket6);
CFRelease(theSocket6);
theSocket6 = NULL;
}
return NO;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connecting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)connectToHost:(NSString*)hostname onPort:(UInt16)port error:(NSError **)errPtr
{
return [self connectToHost:hostname onPort:port withTimeout:-1 error:errPtr];
}
/**
* This method creates an initial CFReadStream and CFWriteStream to the given host on the given port.
* The connection is then opened, and the corresponding CFSocket will be extracted after the connection succeeds.
*
* Thus the delegate will have access to the CFReadStream and CFWriteStream prior to connection,
* specifically in the onSocketWillConnect: method.
**/
- (BOOL)connectToHost:(NSString *)hostname
onPort:(UInt16)port
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr
{
if (theDelegate == NULL)
{
[NSException raise:AsyncSocketException
format:@"Attempting to connect without a delegate. Set a delegate first."];
}
if (![self isDisconnected])
{
[NSException raise:AsyncSocketException
format:@"Attempting to connect while connected or accepting connections. Disconnect first."];
}
// Clear queues (spurious read/write requests post disconnect)
[self emptyQueues];
if(![self createStreamsToHost:hostname onPort:port error:errPtr]) goto Failed;
if(![self attachStreamsToRunLoop:nil error:errPtr]) goto Failed;
if(![self configureStreamsAndReturnError:errPtr]) goto Failed;
if(![self openStreamsAndReturnError:errPtr]) goto Failed;
[self startConnectTimeout:timeout];
theFlags |= kDidStartDelegate;
return YES;
Failed:
[self close];
return NO;
}
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr
{
return [self connectToAddress:remoteAddr viaInterfaceAddress:nil withTimeout:-1 error:errPtr];
}
/**
* This method creates an initial CFSocket to the given address.
* The connection is then opened, and the corresponding CFReadStream and CFWriteStream will be
* created from the low-level sockets after the connection succeeds.
*
* Thus the delegate will have access to the CFSocket and CFSocketNativeHandle (BSD socket) prior to connection,
* specifically in the onSocketWillConnect: method.
*
* Note: The NSData parameter is expected to be a sockaddr structure. For example, an NSData object returned from
* NSNetservice addresses method.
* If you have an existing struct sockaddr you can convert it to an NSData object like so:
* struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
* struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr
{
return [self connectToAddress:remoteAddr viaInterfaceAddress:nil withTimeout:timeout error:errPtr];
}
/**
* This method is similar to the one above, but allows you to specify which socket interface
* the connection should run over. E.g. ethernet, wifi, bluetooth, etc.
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr
viaInterfaceAddress:(NSData *)interfaceAddr
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr
{
if (theDelegate == NULL)
{
[NSException raise:AsyncSocketException
format:@"Attempting to connect without a delegate. Set a delegate first."];
}
if (![self isDisconnected])
{
[NSException raise:AsyncSocketException
format:@"Attempting to connect while connected or accepting connections. Disconnect first."];
}
// Clear queues (spurious read/write requests post disconnect)
[self emptyQueues];
if(![self createSocketForAddress:remoteAddr error:errPtr]) goto Failed;
if(![self bindSocketToAddress:interfaceAddr error:errPtr]) goto Failed;
if(![self attachSocketsToRunLoop:nil error:errPtr]) goto Failed;
if(![self configureSocketAndReturnError:errPtr]) goto Failed;
if(![self connectSocketToAddress:remoteAddr error:errPtr]) goto Failed;
[self startConnectTimeout:timeout];
theFlags |= kDidStartDelegate;
return YES;
Failed:
[self close];
return NO;
}
- (void)startConnectTimeout:(NSTimeInterval)timeout
{
if(timeout >= 0.0)
{
theConnectTimer = [NSTimer timerWithTimeInterval:timeout
target:self
selector:@selector(doConnectTimeout:)
userInfo:nil
repeats:NO];
[self runLoopAddTimer:theConnectTimer];
}
}
- (void)endConnectTimeout
{
[theConnectTimer invalidate];
theConnectTimer = nil;
}
- (void)doConnectTimeout:(NSTimer *)timer
{
#pragma unused(timer)
[self endConnectTimeout];
[self closeWithError:[self getConnectTimeoutError]];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Socket Implementation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Creates the accept sockets.
* Returns true if either IPv4 or IPv6 is created.
* If either is missing, an error is returned (even though the method may return true).
**/
- (CFSocketRef)newAcceptSocketForAddress:(NSData *)addr error:(NSError **)errPtr
{
struct sockaddr *pSockAddr = (struct sockaddr *)[addr bytes];
int addressFamily = pSockAddr->sa_family;
CFSocketRef theSocket = CFSocketCreate(kCFAllocatorDefault,
addressFamily,
SOCK_STREAM,
0,
kCFSocketAcceptCallBack, // Callback flags
(CFSocketCallBack)&MyCFSocketCallback, // Callback method
&theContext);
if(theSocket == NULL)
{
if(errPtr) *errPtr = [self getSocketError];
}
return theSocket;
}
- (BOOL)createSocketForAddress:(NSData *)remoteAddr error:(NSError **)errPtr
{
struct sockaddr *pSockAddr = (struct sockaddr *)[remoteAddr bytes];
if(pSockAddr->sa_family == AF_INET)
{
theSocket4 = CFSocketCreate(NULL, // Default allocator
PF_INET, // Protocol Family
SOCK_STREAM, // Socket Type
IPPROTO_TCP, // Protocol
kCFSocketConnectCallBack, // Callback flags
(CFSocketCallBack)&MyCFSocketCallback, // Callback method
&theContext); // Socket Context
if(theSocket4 == NULL)
{
if (errPtr) *errPtr = [self getSocketError];
return NO;
}
}
else if(pSockAddr->sa_family == AF_INET6)
{
theSocket6 = CFSocketCreate(NULL, // Default allocator
PF_INET6, // Protocol Family
SOCK_STREAM, // Socket Type
IPPROTO_TCP, // Protocol
kCFSocketConnectCallBack, // Callback flags
(CFSocketCallBack)&MyCFSocketCallback, // Callback method
&theContext); // Socket Context
if(theSocket6 == NULL)
{
if (errPtr) *errPtr = [self getSocketError];
return NO;
}
}
else
{
if (errPtr)
{
NSString *errMsg = @"Remote address is not IPv4 or IPv6";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketCFSocketError userInfo:info];
}
return NO;
}
return YES;
}
- (BOOL)bindSocketToAddress:(NSData *)interfaceAddr error:(NSError **)errPtr
{
if (interfaceAddr == nil) return YES;
struct sockaddr *pSockAddr = (struct sockaddr *)[interfaceAddr bytes];
CFSocketRef theSocket = (theSocket4 != NULL) ? theSocket4 : theSocket6;
NSAssert((theSocket != NULL), @"bindSocketToAddress called without valid socket");
CFSocketNativeHandle nativeSocket = CFSocketGetNative(theSocket);
if (pSockAddr->sa_family == AF_INET || pSockAddr->sa_family == AF_INET6)
{
int result = bind(nativeSocket, pSockAddr, (socklen_t)[interfaceAddr length]);
if (result != 0)
{
if (errPtr) *errPtr = [self getErrnoError];
return NO;
}
}
else
{
if (errPtr)
{
NSString *errMsg = @"Interface address is not IPv4 or IPv6";
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketCFSocketError userInfo:info];
}
return NO;
}
return YES;
}
/**
* Adds the CFSocket's to the run-loop so that callbacks will work properly.
**/
- (BOOL)attachSocketsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr
{
#pragma unused(errPtr)
// Get the CFRunLoop to which the socket should be attached.
theRunLoop = (runLoop == nil) ? CFRunLoopGetCurrent() : [runLoop getCFRunLoop];
if(theSocket4)
{
theSource4 = CFSocketCreateRunLoopSource (kCFAllocatorDefault, theSocket4, 0);
[self runLoopAddSource:theSource4];
}
if(theSocket6)
{
theSource6 = CFSocketCreateRunLoopSource (kCFAllocatorDefault, theSocket6, 0);
[self runLoopAddSource:theSource6];
}
return YES;
}
/**
* Allows the delegate method to configure the CFSocket or CFNativeSocket as desired before we connect.
* Note that the CFReadStream and CFWriteStream will not be available until after the connection is opened.
**/
- (BOOL)configureSocketAndReturnError:(NSError **)errPtr
{
// Call the delegate method for further configuration.
if([theDelegate respondsToSelector:@selector(onSocketWillConnect:)])
{
if([theDelegate onSocketWillConnect:self] == NO)
{
if (errPtr) *errPtr = [self getAbortError];
return NO;
}
}
return YES;
}
- (BOOL)connectSocketToAddress:(NSData *)remoteAddr error:(NSError **)errPtr
{
// Start connecting to the given address in the background
// The MyCFSocketCallback method will be called when the connection succeeds or fails
if(theSocket4)
{
CFSocketError err = CFSocketConnectToAddress(theSocket4, (CFDataRef)remoteAddr, -1);
if(err != kCFSocketSuccess)
{
if (errPtr) *errPtr = [self getSocketError];
return NO;
}
}
else if(theSocket6)
{
CFSocketError err = CFSocketConnectToAddress(theSocket6, (CFDataRef)remoteAddr, -1);
if(err != kCFSocketSuccess)
{
if (errPtr) *errPtr = [self getSocketError];
return NO;
}
}
return YES;
}
/**
* Attempt to make the new socket.
* If an error occurs, ignore this event.
**/
- (void)doAcceptFromSocket:(CFSocketRef)parentSocket withNewNativeSocket:(CFSocketNativeHandle)newNativeSocket
{
if(newNativeSocket)
{
// New socket inherits same delegate and run loop modes.
// Note: We use [self class] to support subclassing AsyncSocket.
AsyncSocket *newSocket = [[[[self class] alloc] initWithDelegate:theDelegate] autorelease];
[newSocket setRunLoopModes:theRunLoopModes];
if(![newSocket createStreamsFromNative:newNativeSocket error:nil])
goto Failed;
if (parentSocket == theSocket4)
newSocket->theNativeSocket4 = newNativeSocket;
else
newSocket->theNativeSocket6 = newNativeSocket;
if ([theDelegate respondsToSelector:@selector(onSocket:didAcceptNewSocket:)])
[theDelegate onSocket:self didAcceptNewSocket:newSocket];
newSocket->theFlags |= kDidStartDelegate;
NSRunLoop *runLoop = nil;
if ([theDelegate respondsToSelector:@selector(onSocket:wantsRunLoopForNewSocket:)])
{
runLoop = [theDelegate onSocket:self wantsRunLoopForNewSocket:newSocket];
}
if(![newSocket attachStreamsToRunLoop:runLoop error:nil]) goto Failed;
if(![newSocket configureStreamsAndReturnError:nil]) goto Failed;
if(![newSocket openStreamsAndReturnError:nil]) goto Failed;
return;
Failed:
[newSocket close];
}
}
/**
* This method is called as a result of connectToAddress:withTimeout:error:.
* At this point we have an open CFSocket from which we need to create our read and write stream.
**/
- (void)doSocketOpen:(CFSocketRef)sock withCFSocketError:(CFSocketError)socketError
{
NSParameterAssert ((sock == theSocket4) || (sock == theSocket6));
if(socketError == kCFSocketTimeout || socketError == kCFSocketError)
{
[self closeWithError:[self getSocketError]];
return;
}
// Get the underlying native (BSD) socket
CFSocketNativeHandle nativeSocket = CFSocketGetNative(sock);
// Store a reference to it
if (sock == theSocket4)
theNativeSocket4 = nativeSocket;
else
theNativeSocket6 = nativeSocket;
// Setup the CFSocket so that invalidating it will not close the underlying native socket
CFSocketSetSocketFlags(sock, 0);
// Invalidate and release the CFSocket - All we need from here on out is the nativeSocket.
// Note: If we don't invalidate the CFSocket (leaving the native socket open)
// then theReadStream and theWriteStream won't function properly.
// Specifically, their callbacks won't work, with the exception of kCFStreamEventOpenCompleted.
//
// This is likely due to the mixture of the CFSocketCreateWithNative method,
// along with the CFStreamCreatePairWithSocket method.
// The documentation for CFSocketCreateWithNative states:
//
// If a CFSocket object already exists for sock,
// the function returns the pre-existing object instead of creating a new object;
// the context, callout, and callBackTypes parameters are ignored in this case.
//
// So the CFStreamCreateWithNative method invokes the CFSocketCreateWithNative method,
// thinking that is creating a new underlying CFSocket for it's own purposes.
// When it does this, it uses the context/callout/callbackTypes parameters to setup everything appropriately.
// However, if a CFSocket already exists for the native socket,
// then it is returned (as per the documentation), which in turn screws up the CFStreams.
CFSocketInvalidate(sock);
CFRelease(sock);
theSocket4 = NULL;
theSocket6 = NULL;
NSError *err;
BOOL pass = YES;
if(pass && ![self createStreamsFromNative:nativeSocket error:&err]) pass = NO;
if(pass && ![self attachStreamsToRunLoop:nil error:&err]) pass = NO;
if(pass && ![self openStreamsAndReturnError:&err]) pass = NO;
if(!pass)
{
[self closeWithError:err];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Stream Implementation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Creates the CFReadStream and CFWriteStream from the given native socket.
* The CFSocket may be extracted from either stream after the streams have been opened.
*
* Note: The given native socket must already be connected!
**/
- (BOOL)createStreamsFromNative:(CFSocketNativeHandle)native error:(NSError **)errPtr
{
// Create the socket & streams.
CFStreamCreatePairWithSocket(kCFAllocatorDefault, native, &theReadStream, &theWriteStream);
if (theReadStream == NULL || theWriteStream == NULL)
{
NSError *err = [self getStreamError];
NSLog(@"AsyncSocket %p couldn't create streams from accepted socket: %@", self, err);
if (errPtr) *errPtr = err;
return NO;
}
// Ensure the CF & BSD socket is closed when the streams are closed.
CFReadStreamSetProperty(theReadStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(theWriteStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
return YES;
}
/**
* Creates the CFReadStream and CFWriteStream from the given hostname and port number.
* The CFSocket may be extracted from either stream after the streams have been opened.
**/
- (BOOL)createStreamsToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr
{
// Create the socket & streams.
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)hostname, port, &theReadStream, &theWriteStream);
if (theReadStream == NULL || theWriteStream == NULL)
{
if (errPtr) *errPtr = [self getStreamError];
return NO;
}
// Ensure the CF & BSD socket is closed when the streams are closed.
CFReadStreamSetProperty(theReadStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(theWriteStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
return YES;
}
- (BOOL)attachStreamsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr
{
// Get the CFRunLoop to which the socket should be attached.
theRunLoop = (runLoop == nil) ? CFRunLoopGetCurrent() : [runLoop getCFRunLoop];
// Setup read stream callbacks
CFOptionFlags readStreamEvents = kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred |
kCFStreamEventEndEncountered |
kCFStreamEventOpenCompleted;
if (!CFReadStreamSetClient(theReadStream,
readStreamEvents,
(CFReadStreamClientCallBack)&MyCFReadStreamCallback,
(CFStreamClientContext *)(&theContext)))
{
NSError *err = [self getStreamError];
NSLog (@"AsyncSocket %p couldn't attach read stream to run-loop,", self);
NSLog (@"Error: %@", err);
if (errPtr) *errPtr = err;
return NO;
}
// Setup write stream callbacks
CFOptionFlags writeStreamEvents = kCFStreamEventCanAcceptBytes |
kCFStreamEventErrorOccurred |
kCFStreamEventEndEncountered |
kCFStreamEventOpenCompleted;
if (!CFWriteStreamSetClient (theWriteStream,
writeStreamEvents,
(CFWriteStreamClientCallBack)&MyCFWriteStreamCallback,
(CFStreamClientContext *)(&theContext)))
{
NSError *err = [self getStreamError];
NSLog (@"AsyncSocket %p couldn't attach write stream to run-loop,", self);
NSLog (@"Error: %@", err);
if (errPtr) *errPtr = err;
return NO;
}
// Add read and write streams to run loop
for (NSString *runLoopMode in theRunLoopModes)
{
CFReadStreamScheduleWithRunLoop(theReadStream, theRunLoop, (CFStringRef)runLoopMode);
CFWriteStreamScheduleWithRunLoop(theWriteStream, theRunLoop, (CFStringRef)runLoopMode);
}
return YES;
}
/**
* Allows the delegate method to configure the CFReadStream and/or CFWriteStream as desired before we connect.
*
* If being called from a connect method,
* the CFSocket and CFNativeSocket will not be available until after the connection is opened.
**/
- (BOOL)configureStreamsAndReturnError:(NSError **)errPtr
{
// Call the delegate method for further configuration.
if([theDelegate respondsToSelector:@selector(onSocketWillConnect:)])
{
if([theDelegate onSocketWillConnect:self] == NO)
{
if (errPtr) *errPtr = [self getAbortError];
return NO;
}
}
return YES;
}
- (BOOL)openStreamsAndReturnError:(NSError **)errPtr
{
BOOL pass = YES;
if(pass && !CFReadStreamOpen(theReadStream))
{
NSLog (@"AsyncSocket %p couldn't open read stream,", self);
pass = NO;
}
if(pass && !CFWriteStreamOpen(theWriteStream))
{
NSLog (@"AsyncSocket %p couldn't open write stream,", self);
pass = NO;
}
if(!pass)
{
if (errPtr) *errPtr = [self getStreamError];
}
return pass;
}
/**
* Called when read or write streams open.
* When the socket is connected and both streams are open, consider the AsyncSocket instance to be ready.
**/
- (void)doStreamOpen
{
if ((theFlags & kDidCompleteOpenForRead) && (theFlags & kDidCompleteOpenForWrite))
{
NSError *err = nil;
// Get the socket
if (![self setSocketFromStreamsAndReturnError: &err])
{
NSLog (@"AsyncSocket %p couldn't get socket from streams, %@. Disconnecting.", self, err);
[self closeWithError:err];
return;
}
// Stop the connection attempt timeout timer
[self endConnectTimeout];
if ([theDelegate respondsToSelector:@selector(onSocket:didConnectToHost:port:)])
{
[theDelegate onSocket:self didConnectToHost:[self connectedHost] port:[self connectedPort]];
}
// Immediately deal with any already-queued requests.
[self maybeDequeueRead];
[self maybeDequeueWrite];
}
}
- (BOOL)setSocketFromStreamsAndReturnError:(NSError **)errPtr
{
// Get the CFSocketNativeHandle from theReadStream
CFSocketNativeHandle native;
CFDataRef nativeProp = CFReadStreamCopyProperty(theReadStream, kCFStreamPropertySocketNativeHandle);
if(nativeProp == NULL)
{
if (errPtr) *errPtr = [self getStreamError];
return NO;
}
CFIndex nativePropLen = CFDataGetLength(nativeProp);
CFIndex nativeLen = (CFIndex)sizeof(native);
CFIndex len = MIN(nativePropLen, nativeLen);
CFDataGetBytes(nativeProp, CFRangeMake(0, len), (UInt8 *)&native);
CFRelease(nativeProp);
CFSocketRef theSocket = CFSocketCreateWithNative(kCFAllocatorDefault, native, 0, NULL, NULL);
if(theSocket == NULL)
{
if (errPtr) *errPtr = [self getSocketError];
return NO;
}
// Determine whether the connection was IPv4 or IPv6.
// We may already know if this was an accepted socket,
// or if the connectToAddress method was used.
// In either of the above two cases, the native socket variable would already be set.
if (theNativeSocket4 > 0)
{
theSocket4 = theSocket;
return YES;
}
if (theNativeSocket6 > 0)
{
theSocket6 = theSocket;
return YES;
}
CFDataRef peeraddr = CFSocketCopyPeerAddress(theSocket);
if(peeraddr == NULL)
{
NSLog(@"AsyncSocket couldn't determine IP version of socket");
CFRelease(theSocket);
if (errPtr) *errPtr = [self getSocketError];
return NO;
}
struct sockaddr *sa = (struct sockaddr *)CFDataGetBytePtr(peeraddr);
if(sa->sa_family == AF_INET)
{
theSocket4 = theSocket;
theNativeSocket4 = native;
}
else
{
theSocket6 = theSocket;
theNativeSocket6 = native;
}
CFRelease(peeraddr);
return YES;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Disconnect Implementation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sends error message and disconnects
- (void)closeWithError:(NSError *)err
{
theFlags |= kClosingWithError;
if (theFlags & kDidStartDelegate)
{
// Try to salvage what data we can.
[self recoverUnreadData];
// Let the delegate know, so it can try to recover if it likes.
if ([theDelegate respondsToSelector:@selector(onSocket:willDisconnectWithError:)])
{
[theDelegate onSocket:self willDisconnectWithError:err];
}
}
[self close];
}
// Prepare partially read data for recovery.
- (void)recoverUnreadData
{
if(theCurrentRead != nil)
{
// We never finished the current read.
// Check to see if it's a normal read packet (not AsyncSpecialPacket) and if it had read anything yet.
if(([theCurrentRead isKindOfClass:[AsyncReadPacket class]]) && (theCurrentRead->bytesDone > 0))
{
// We need to move its data into the front of the partial read buffer.
void *buffer = [theCurrentRead->buffer mutableBytes] + theCurrentRead->startOffset;
[partialReadBuffer replaceBytesInRange:NSMakeRange(0, 0)
withBytes:buffer
length:theCurrentRead->bytesDone];
}
}
[self emptyQueues];
}
- (void)emptyQueues
{
if (theCurrentRead != nil) [self endCurrentRead];
if (theCurrentWrite != nil) [self endCurrentWrite];
[theReadQueue removeAllObjects];
[theWriteQueue removeAllObjects];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(maybeDequeueRead) object:nil];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(maybeDequeueWrite) object:nil];
theFlags &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
}
/**
* Disconnects. This is called for both error and clean disconnections.
**/
- (void)close
{
// Empty queues
[self emptyQueues];
// Clear partialReadBuffer (pre-buffer and also unreadData buffer in case of error)
[partialReadBuffer replaceBytesInRange:NSMakeRange(0, [partialReadBuffer length]) withBytes:NULL length:0];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(disconnect) object:nil];
// Stop the connection attempt timeout timer
if (theConnectTimer != nil)
{
[self endConnectTimeout];
}
// Close streams.
if (theReadStream != NULL)
{
[self runLoopUnscheduleReadStream];
CFReadStreamClose(theReadStream);
CFRelease(theReadStream);
theReadStream = NULL;
}
if (theWriteStream != NULL)
{
[self runLoopUnscheduleWriteStream];
CFWriteStreamClose(theWriteStream);
CFRelease(theWriteStream);
theWriteStream = NULL;
}
// Close sockets.
if (theSocket4 != NULL)
{
CFSocketInvalidate (theSocket4);
CFRelease (theSocket4);
theSocket4 = NULL;
}
if (theSocket6 != NULL)
{
CFSocketInvalidate (theSocket6);
CFRelease (theSocket6);
theSocket6 = NULL;
}
// Closing the streams or sockets resulted in closing the underlying native socket
theNativeSocket4 = 0;
theNativeSocket6 = 0;
// Remove run loop sources
if (theSource4 != NULL)
{
[self runLoopRemoveSource:theSource4];
CFRelease (theSource4);
theSource4 = NULL;
}
if (theSource6 != NULL)
{
[self runLoopRemoveSource:theSource6];
CFRelease (theSource6);
theSource6 = NULL;
}
theRunLoop = NULL;
// If the client has passed the connect/accept method, then the connection has at least begun.
// Notify delegate that it is now ending.
BOOL shouldCallDelegate = (theFlags & kDidStartDelegate);
// Clear all flags (except the pre-buffering flag, which should remain as is)
theFlags &= kEnablePreBuffering;
if (shouldCallDelegate)
{
if ([theDelegate respondsToSelector: @selector(onSocketDidDisconnect:)])
{
[theDelegate onSocketDidDisconnect:self];
}
}
// Do not access any instance variables after calling onSocketDidDisconnect.
// This gives the delegate freedom to release us without returning here and crashing.
}
/**
* Disconnects immediately. Any pending reads or writes are dropped.
**/
- (void)disconnect
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
[self close];
}
/**
* Diconnects after all pending reads have completed.
**/
- (void)disconnectAfterReading
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theFlags |= (kForbidReadsWrites | kDisconnectAfterReads);
[self maybeScheduleDisconnect];
}
/**
* Disconnects after all pending writes have completed.
**/
- (void)disconnectAfterWriting
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theFlags |= (kForbidReadsWrites | kDisconnectAfterWrites);
[self maybeScheduleDisconnect];
}
/**
* Disconnects after all pending reads and writes have completed.
**/
- (void)disconnectAfterReadingAndWriting
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theFlags |= (kForbidReadsWrites | kDisconnectAfterReads | kDisconnectAfterWrites);
[self maybeScheduleDisconnect];
}
/**
* Schedules a call to disconnect if possible.
* That is, if all writes have completed, and we're set to disconnect after writing,
* or if all reads have completed, and we're set to disconnect after reading.
**/
- (void)maybeScheduleDisconnect
{
BOOL shouldDisconnect = NO;
if(theFlags & kDisconnectAfterReads)
{
if(([theReadQueue count] == 0) && (theCurrentRead == nil))
{
if(theFlags & kDisconnectAfterWrites)
{
if(([theWriteQueue count] == 0) && (theCurrentWrite == nil))
{
shouldDisconnect = YES;
}
}
else
{
shouldDisconnect = YES;
}
}
}
else if(theFlags & kDisconnectAfterWrites)
{
if(([theWriteQueue count] == 0) && (theCurrentWrite == nil))
{
shouldDisconnect = YES;
}
}
if(shouldDisconnect)
{
[self performSelector:@selector(disconnect) withObject:nil afterDelay:0 inModes:theRunLoopModes];
}
}
/**
* In the event of an error, this method may be called during onSocket:willDisconnectWithError: to read
* any data that's left on the socket.
**/
- (NSData *)unreadData
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
// Ensure this method will only return data in the event of an error
if (!(theFlags & kClosingWithError)) return nil;
if (theReadStream == NULL) return nil;
NSUInteger totalBytesRead = [partialReadBuffer length];
BOOL error = NO;
while (!error && CFReadStreamHasBytesAvailable(theReadStream))
{
if (totalBytesRead == [partialReadBuffer length])
{
[partialReadBuffer increaseLengthBy:READALL_CHUNKSIZE];
}
// Number of bytes to read is space left in packet buffer.
NSUInteger bytesToRead = [partialReadBuffer length] - totalBytesRead;
// Read data into packet buffer
UInt8 *packetbuf = (UInt8 *)( [partialReadBuffer mutableBytes] + totalBytesRead );
CFIndex result = CFReadStreamRead(theReadStream, packetbuf, bytesToRead);
// Check results
if (result < 0)
{
error = YES;
}
else
{
CFIndex bytesRead = result;
totalBytesRead += bytesRead;
}
}
[partialReadBuffer setLength:totalBytesRead];
return partialReadBuffer;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Errors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns a standard error object for the current errno value.
* Errno is used for low-level BSD socket errors.
**/
- (NSError *)getErrnoError
{
NSString *errorMsg = [NSString stringWithUTF8String:strerror(errno)];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo];
}
/**
* Returns a standard error message for a CFSocket error.
* Unfortunately, CFSocket offers no feedback on its errors.
**/
- (NSError *)getSocketError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"AsyncSocketCFSocketError",
@"AsyncSocket", [NSBundle mainBundle],
@"General CFSocket error", nil);
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketCFSocketError userInfo:info];
}
- (NSError *)getStreamError
{
CFStreamError err;
if (theReadStream != NULL)
{
err = CFReadStreamGetError (theReadStream);
if (err.error != 0) return [self errorFromCFStreamError: err];
}
if (theWriteStream != NULL)
{
err = CFWriteStreamGetError (theWriteStream);
if (err.error != 0) return [self errorFromCFStreamError: err];
}
return nil;
}
/**
* Returns a standard AsyncSocket abort error.
**/
- (NSError *)getAbortError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"AsyncSocketCanceledError",
@"AsyncSocket", [NSBundle mainBundle],
@"Connection canceled", nil);
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketCanceledError userInfo:info];
}
/**
* Returns a standard AsyncSocket connect timeout error.
**/
- (NSError *)getConnectTimeoutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"AsyncSocketConnectTimeoutError",
@"AsyncSocket", [NSBundle mainBundle],
@"Attempt to connect to host timed out", nil);
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketConnectTimeoutError userInfo:info];
}
/**
* Returns a standard AsyncSocket maxed out error.
**/
- (NSError *)getReadMaxedOutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"AsyncSocketReadMaxedOutError",
@"AsyncSocket", [NSBundle mainBundle],
@"Read operation reached set maximum length", nil);
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketReadMaxedOutError userInfo:info];
}
/**
* Returns a standard AsyncSocket read timeout error.
**/
- (NSError *)getReadTimeoutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"AsyncSocketReadTimeoutError",
@"AsyncSocket", [NSBundle mainBundle],
@"Read operation timed out", nil);
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketReadTimeoutError userInfo:info];
}
/**
* Returns a standard AsyncSocket write timeout error.
**/
- (NSError *)getWriteTimeoutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"AsyncSocketWriteTimeoutError",
@"AsyncSocket", [NSBundle mainBundle],
@"Write operation timed out", nil);
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:AsyncSocketErrorDomain code:AsyncSocketWriteTimeoutError userInfo:info];
}
- (NSError *)errorFromCFStreamError:(CFStreamError)err
{
if (err.domain == 0 && err.error == 0) return nil;
// Can't use switch; these constants aren't int literals.
NSString *domain = @"CFStreamError (unlisted domain)";
NSString *message = nil;
if(err.domain == kCFStreamErrorDomainPOSIX) {
domain = NSPOSIXErrorDomain;
}
else if(err.domain == kCFStreamErrorDomainMacOSStatus) {
domain = NSOSStatusErrorDomain;
}
else if(err.domain == kCFStreamErrorDomainMach) {
domain = NSMachErrorDomain;
}
else if(err.domain == kCFStreamErrorDomainNetDB)
{
domain = @"kCFStreamErrorDomainNetDB";
message = [NSString stringWithCString:gai_strerror(err.error) encoding:NSASCIIStringEncoding];
}
else if(err.domain == kCFStreamErrorDomainNetServices) {
domain = @"kCFStreamErrorDomainNetServices";
}
else if(err.domain == kCFStreamErrorDomainSOCKS) {
domain = @"kCFStreamErrorDomainSOCKS";
}
else if(err.domain == kCFStreamErrorDomainSystemConfiguration) {
domain = @"kCFStreamErrorDomainSystemConfiguration";
}
else if(err.domain == kCFStreamErrorDomainSSL) {
domain = @"kCFStreamErrorDomainSSL";
}
NSDictionary *info = nil;
if(message != nil)
{
info = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
}
return [NSError errorWithDomain:domain code:err.error userInfo:info];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Diagnostics
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)isDisconnected
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if (theNativeSocket4 > 0) return NO;
if (theNativeSocket6 > 0) return NO;
if (theSocket4) return NO;
if (theSocket6) return NO;
if (theReadStream) return NO;
if (theWriteStream) return NO;
return YES;
}
- (BOOL)isConnected
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return [self areStreamsConnected];
}
- (NSString *)connectedHost
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if(theSocket4)
return [self connectedHostFromCFSocket4:theSocket4];
if(theSocket6)
return [self connectedHostFromCFSocket6:theSocket6];
if(theNativeSocket4 > 0)
return [self connectedHostFromNativeSocket4:theNativeSocket4];
if(theNativeSocket6 > 0)
return [self connectedHostFromNativeSocket6:theNativeSocket6];
return nil;
}
- (UInt16)connectedPort
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if(theSocket4)
return [self connectedPortFromCFSocket4:theSocket4];
if(theSocket6)
return [self connectedPortFromCFSocket6:theSocket6];
if(theNativeSocket4 > 0)
return [self connectedPortFromNativeSocket4:theNativeSocket4];
if(theNativeSocket6 > 0)
return [self connectedPortFromNativeSocket6:theNativeSocket6];
return 0;
}
- (NSString *)localHost
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if(theSocket4)
return [self localHostFromCFSocket4:theSocket4];
if(theSocket6)
return [self localHostFromCFSocket6:theSocket6];
if(theNativeSocket4 > 0)
return [self localHostFromNativeSocket4:theNativeSocket4];
if(theNativeSocket6 > 0)
return [self localHostFromNativeSocket6:theNativeSocket6];
return nil;
}
- (UInt16)localPort
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if(theSocket4)
return [self localPortFromCFSocket4:theSocket4];
if(theSocket6)
return [self localPortFromCFSocket6:theSocket6];
if(theNativeSocket4 > 0)
return [self localPortFromNativeSocket4:theNativeSocket4];
if(theNativeSocket6 > 0)
return [self localPortFromNativeSocket6:theNativeSocket6];
return 0;
}
- (NSString *)connectedHost4
{
if(theSocket4)
return [self connectedHostFromCFSocket4:theSocket4];
if(theNativeSocket4 > 0)
return [self connectedHostFromNativeSocket4:theNativeSocket4];
return nil;
}
- (NSString *)connectedHost6
{
if(theSocket6)
return [self connectedHostFromCFSocket6:theSocket6];
if(theNativeSocket6 > 0)
return [self connectedHostFromNativeSocket6:theNativeSocket6];
return nil;
}
- (UInt16)connectedPort4
{
if(theSocket4)
return [self connectedPortFromCFSocket4:theSocket4];
if(theNativeSocket4 > 0)
return [self connectedPortFromNativeSocket4:theNativeSocket4];
return 0;
}
- (UInt16)connectedPort6
{
if(theSocket6)
return [self connectedPortFromCFSocket6:theSocket6];
if(theNativeSocket6 > 0)
return [self connectedPortFromNativeSocket6:theNativeSocket6];
return 0;
}
- (NSString *)localHost4
{
if(theSocket4)
return [self localHostFromCFSocket4:theSocket4];
if(theNativeSocket4 > 0)
return [self localHostFromNativeSocket4:theNativeSocket4];
return nil;
}
- (NSString *)localHost6
{
if(theSocket6)
return [self localHostFromCFSocket6:theSocket6];
if(theNativeSocket6 > 0)
return [self localHostFromNativeSocket6:theNativeSocket6];
return nil;
}
- (UInt16)localPort4
{
if(theSocket4)
return [self localPortFromCFSocket4:theSocket4];
if(theNativeSocket4 > 0)
return [self localPortFromNativeSocket4:theNativeSocket4];
return 0;
}
- (UInt16)localPort6
{
if(theSocket6)
return [self localPortFromCFSocket6:theSocket6];
if(theNativeSocket6 > 0)
return [self localPortFromNativeSocket6:theNativeSocket6];
return 0;
}
- (NSString *)connectedHostFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getpeername(theNativeSocket, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return nil;
}
return [self hostFromAddress4:&sockaddr4];
}
- (NSString *)connectedHostFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getpeername(theNativeSocket, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return nil;
}
return [self hostFromAddress6:&sockaddr6];
}
- (NSString *)connectedHostFromCFSocket4:(CFSocketRef)theSocket
{
CFDataRef peeraddr;
NSString *peerstr = nil;
if((peeraddr = CFSocketCopyPeerAddress(theSocket)))
{
struct sockaddr_in *pSockAddr = (struct sockaddr_in *)CFDataGetBytePtr(peeraddr);
peerstr = [self hostFromAddress4:pSockAddr];
CFRelease (peeraddr);
}
return peerstr;
}
- (NSString *)connectedHostFromCFSocket6:(CFSocketRef)theSocket
{
CFDataRef peeraddr;
NSString *peerstr = nil;
if((peeraddr = CFSocketCopyPeerAddress(theSocket)))
{
struct sockaddr_in6 *pSockAddr = (struct sockaddr_in6 *)CFDataGetBytePtr(peeraddr);
peerstr = [self hostFromAddress6:pSockAddr];
CFRelease (peeraddr);
}
return peerstr;
}
- (UInt16)connectedPortFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getpeername(theNativeSocket, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return 0;
}
return [self portFromAddress4:&sockaddr4];
}
- (UInt16)connectedPortFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getpeername(theNativeSocket, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return 0;
}
return [self portFromAddress6:&sockaddr6];
}
- (UInt16)connectedPortFromCFSocket4:(CFSocketRef)theSocket
{
CFDataRef peeraddr;
UInt16 peerport = 0;
if((peeraddr = CFSocketCopyPeerAddress(theSocket)))
{
struct sockaddr_in *pSockAddr = (struct sockaddr_in *)CFDataGetBytePtr(peeraddr);
peerport = [self portFromAddress4:pSockAddr];
CFRelease (peeraddr);
}
return peerport;
}
- (UInt16)connectedPortFromCFSocket6:(CFSocketRef)theSocket
{
CFDataRef peeraddr;
UInt16 peerport = 0;
if((peeraddr = CFSocketCopyPeerAddress(theSocket)))
{
struct sockaddr_in6 *pSockAddr = (struct sockaddr_in6 *)CFDataGetBytePtr(peeraddr);
peerport = [self portFromAddress6:pSockAddr];
CFRelease (peeraddr);
}
return peerport;
}
- (NSString *)localHostFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getsockname(theNativeSocket, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return nil;
}
return [self hostFromAddress4:&sockaddr4];
}
- (NSString *)localHostFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getsockname(theNativeSocket, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return nil;
}
return [self hostFromAddress6:&sockaddr6];
}
- (NSString *)localHostFromCFSocket4:(CFSocketRef)theSocket
{
CFDataRef selfaddr;
NSString *selfstr = nil;
if((selfaddr = CFSocketCopyAddress(theSocket)))
{
struct sockaddr_in *pSockAddr = (struct sockaddr_in *)CFDataGetBytePtr(selfaddr);
selfstr = [self hostFromAddress4:pSockAddr];
CFRelease (selfaddr);
}
return selfstr;
}
- (NSString *)localHostFromCFSocket6:(CFSocketRef)theSocket
{
CFDataRef selfaddr;
NSString *selfstr = nil;
if((selfaddr = CFSocketCopyAddress(theSocket)))
{
struct sockaddr_in6 *pSockAddr = (struct sockaddr_in6 *)CFDataGetBytePtr(selfaddr);
selfstr = [self hostFromAddress6:pSockAddr];
CFRelease (selfaddr);
}
return selfstr;
}
- (UInt16)localPortFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if(getsockname(theNativeSocket, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return 0;
}
return [self portFromAddress4:&sockaddr4];
}
- (UInt16)localPortFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if(getsockname(theNativeSocket, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return 0;
}
return [self portFromAddress6:&sockaddr6];
}
- (UInt16)localPortFromCFSocket4:(CFSocketRef)theSocket
{
CFDataRef selfaddr;
UInt16 selfport = 0;
if ((selfaddr = CFSocketCopyAddress(theSocket)))
{
struct sockaddr_in *pSockAddr = (struct sockaddr_in *)CFDataGetBytePtr(selfaddr);
selfport = [self portFromAddress4:pSockAddr];
CFRelease (selfaddr);
}
return selfport;
}
- (UInt16)localPortFromCFSocket6:(CFSocketRef)theSocket
{
CFDataRef selfaddr;
UInt16 selfport = 0;
if ((selfaddr = CFSocketCopyAddress(theSocket)))
{
struct sockaddr_in6 *pSockAddr = (struct sockaddr_in6 *)CFDataGetBytePtr(selfaddr);
selfport = [self portFromAddress6:pSockAddr];
CFRelease (selfaddr);
}
return selfport;
}
- (NSString *)hostFromAddress4:(struct sockaddr_in *)pSockaddr4
{
char addrBuf[INET_ADDRSTRLEN];
if(inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
{
[NSException raise:NSInternalInconsistencyException format:@"Cannot convert IPv4 address to string."];
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
- (NSString *)hostFromAddress6:(struct sockaddr_in6 *)pSockaddr6
{
char addrBuf[INET6_ADDRSTRLEN];
if(inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
{
[NSException raise:NSInternalInconsistencyException format:@"Cannot convert IPv6 address to string."];
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
- (UInt16)portFromAddress4:(struct sockaddr_in *)pSockaddr4
{
return ntohs(pSockaddr4->sin_port);
}
- (UInt16)portFromAddress6:(struct sockaddr_in6 *)pSockaddr6
{
return ntohs(pSockaddr6->sin6_port);
}
- (NSData *)connectedAddress
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
// Extract address from CFSocket
CFSocketRef theSocket;
if (theSocket4)
theSocket = theSocket4;
else
theSocket = theSocket6;
if (theSocket)
{
CFDataRef peeraddr = CFSocketCopyPeerAddress(theSocket);
if (peeraddr == NULL) return nil;
return [(NSData *)NSMakeCollectable(peeraddr) autorelease];
}
// Extract address from CFSocketNativeHandle
socklen_t sockaddrlen;
CFSocketNativeHandle theNativeSocket = 0;
if (theNativeSocket4 > 0)
{
theNativeSocket = theNativeSocket4;
sockaddrlen = sizeof(struct sockaddr_in);
}
else
{
theNativeSocket = theNativeSocket6;
sockaddrlen = sizeof(struct sockaddr_in6);
}
NSData *result = nil;
void *sockaddr = malloc(sockaddrlen);
if(getpeername(theNativeSocket, (struct sockaddr *)sockaddr, &sockaddrlen) >= 0)
{
result = [NSData dataWithBytesNoCopy:sockaddr length:sockaddrlen freeWhenDone:YES];
}
else
{
free(sockaddr);
}
return result;
}
- (NSData *)localAddress
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
// Extract address from CFSocket
CFSocketRef theSocket;
if (theSocket4)
theSocket = theSocket4;
else
theSocket = theSocket6;
if (theSocket)
{
CFDataRef selfaddr = CFSocketCopyAddress(theSocket);
if (selfaddr == NULL) return nil;
return [(NSData *)NSMakeCollectable(selfaddr) autorelease];
}
// Extract address from CFSocketNativeHandle
socklen_t sockaddrlen;
CFSocketNativeHandle theNativeSocket = 0;
if (theNativeSocket4 > 0)
{
theNativeSocket = theNativeSocket4;
sockaddrlen = sizeof(struct sockaddr_in);
}
else
{
theNativeSocket = theNativeSocket6;
sockaddrlen = sizeof(struct sockaddr_in6);
}
NSData *result = nil;
void *sockaddr = malloc(sockaddrlen);
if(getsockname(theNativeSocket, (struct sockaddr *)sockaddr, &sockaddrlen) >= 0)
{
result = [NSData dataWithBytesNoCopy:sockaddr length:sockaddrlen freeWhenDone:YES];
}
else
{
free(sockaddr);
}
return result;
}
- (BOOL)isIPv4
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return (theNativeSocket4 > 0 || theSocket4 != NULL);
}
- (BOOL)isIPv6
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return (theNativeSocket6 > 0 || theSocket6 != NULL);
}
- (BOOL)areStreamsConnected
{
CFStreamStatus s;
if (theReadStream != NULL)
{
s = CFReadStreamGetStatus(theReadStream);
if ( !(s == kCFStreamStatusOpen || s == kCFStreamStatusReading || s == kCFStreamStatusError) )
return NO;
}
else return NO;
if (theWriteStream != NULL)
{
s = CFWriteStreamGetStatus(theWriteStream);
if ( !(s == kCFStreamStatusOpen || s == kCFStreamStatusWriting || s == kCFStreamStatusError) )
return NO;
}
else return NO;
return YES;
}
- (NSString *)description
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
static const char *statstr[] = {"not open","opening","open","reading","writing","at end","closed","has error"};
CFStreamStatus rs = (theReadStream != NULL) ? CFReadStreamGetStatus(theReadStream) : 0;
CFStreamStatus ws = (theWriteStream != NULL) ? CFWriteStreamGetStatus(theWriteStream) : 0;
NSString *peerstr, *selfstr;
BOOL is4 = [self isIPv4];
BOOL is6 = [self isIPv6];
if (is4 || is6)
{
if (is4 && is6)
{
peerstr = [NSString stringWithFormat: @"%@/%@ %u",
[self connectedHost4],
[self connectedHost6],
[self connectedPort]];
}
else if (is4)
{
peerstr = [NSString stringWithFormat: @"%@ %u",
[self connectedHost4],
[self connectedPort4]];
}
else
{
peerstr = [NSString stringWithFormat: @"%@ %u",
[self connectedHost6],
[self connectedPort6]];
}
}
else peerstr = @"nowhere";
if (is4 || is6)
{
if (is4 && is6)
{
selfstr = [NSString stringWithFormat: @"%@/%@ %u",
[self localHost4],
[self localHost6],
[self localPort]];
}
else if (is4)
{
selfstr = [NSString stringWithFormat: @"%@ %u",
[self localHost4],
[self localPort4]];
}
else
{
selfstr = [NSString stringWithFormat: @"%@ %u",
[self localHost6],
[self localPort6]];
}
}
else selfstr = @"nowhere";
NSMutableString *ms = [[NSMutableString alloc] initWithCapacity:150];
[ms appendString:[NSString stringWithFormat:@"<AsyncSocket %p", self]];
[ms appendString:[NSString stringWithFormat:@" local %@ remote %@ ", selfstr, peerstr]];
unsigned readQueueCount = (unsigned)[theReadQueue count];
unsigned writeQueueCount = (unsigned)[theWriteQueue count];
[ms appendString:[NSString stringWithFormat:@"has queued %u reads %u writes, ", readQueueCount, writeQueueCount]];
if (theCurrentRead == nil)
[ms appendString: @"no current read, "];
else
{
int percentDone;
if (theCurrentRead->readLength > 0)
percentDone = (float)theCurrentRead->bytesDone / (float)theCurrentRead->readLength * 100.0F;
else
percentDone = 100.0F;
[ms appendString: [NSString stringWithFormat:@"currently read %u bytes (%d%% done), ",
(unsigned int)[theCurrentRead->buffer length],
theCurrentRead->bytesDone ? percentDone : 0]];
}
if (theCurrentWrite == nil)
[ms appendString: @"no current write, "];
else
{
int percentDone = (float)theCurrentWrite->bytesDone / (float)[theCurrentWrite->buffer length] * 100.0F;
[ms appendString: [NSString stringWithFormat:@"currently written %u (%d%%), ",
(unsigned int)[theCurrentWrite->buffer length],
theCurrentWrite->bytesDone ? percentDone : 0]];
}
[ms appendString:[NSString stringWithFormat:@"read stream %p %s, ", theReadStream, statstr[rs]]];
[ms appendString:[NSString stringWithFormat:@"write stream %p %s", theWriteStream, statstr[ws]]];
if(theFlags & kDisconnectAfterReads)
{
if(theFlags & kDisconnectAfterWrites)
[ms appendString: @", will disconnect after reads & writes"];
else
[ms appendString: @", will disconnect after reads"];
}
else if(theFlags & kDisconnectAfterWrites)
{
[ms appendString: @", will disconnect after writes"];
}
if (![self isConnected]) [ms appendString: @", not connected"];
[ms appendString:@">"];
return [ms autorelease];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Reading
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag
{
[self readDataWithTimeout:timeout buffer:nil bufferOffset:0 maxLength:0 tag:tag];
}
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag
{
[self readDataWithTimeout:timeout buffer:buffer bufferOffset:offset maxLength:0 tag:tag];
}
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if (offset > [buffer length]) return;
if (theFlags & kForbidReadsWrites) return;
AsyncReadPacket *packet = [[AsyncReadPacket alloc] initWithData:buffer
startOffset:offset
maxLength:length
timeout:timeout
readLength:0
terminator:nil
tag:tag];
[theReadQueue addObject:packet];
[self scheduleDequeueRead];
[packet release];
}
- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
[self readDataToLength:length withTimeout:timeout buffer:nil bufferOffset:0 tag:tag];
}
- (void)readDataToLength:(NSUInteger)length
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if (length == 0) return;
if (offset > [buffer length]) return;
if (theFlags & kForbidReadsWrites) return;
AsyncReadPacket *packet = [[AsyncReadPacket alloc] initWithData:buffer
startOffset:offset
maxLength:0
timeout:timeout
readLength:length
terminator:nil
tag:tag];
[theReadQueue addObject:packet];
[self scheduleDequeueRead];
[packet release];
}
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
[self readDataToData:data withTimeout:timeout buffer:nil bufferOffset:0 maxLength:0 tag:tag];
}
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag
{
[self readDataToData:data withTimeout:timeout buffer:buffer bufferOffset:offset maxLength:0 tag:tag];
}
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag
{
[self readDataToData:data withTimeout:timeout buffer:nil bufferOffset:0 maxLength:length tag:tag];
}
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if (data == nil || [data length] == 0) return;
if (offset > [buffer length]) return;
if (length > 0 && length < [data length]) return;
if (theFlags & kForbidReadsWrites) return;
AsyncReadPacket *packet = [[AsyncReadPacket alloc] initWithData:buffer
startOffset:offset
maxLength:length
timeout:timeout
readLength:0
terminator:data
tag:tag];
[theReadQueue addObject:packet];
[self scheduleDequeueRead];
[packet release];
}
/**
* Puts a maybeDequeueRead on the run loop.
* An assumption here is that selectors will be performed consecutively within their priority.
**/
- (void)scheduleDequeueRead
{
if((theFlags & kDequeueReadScheduled) == 0)
{
theFlags |= kDequeueReadScheduled;
[self performSelector:@selector(maybeDequeueRead) withObject:nil afterDelay:0 inModes:theRunLoopModes];
}
}
/**
* This method starts a new read, if needed.
* It is called when a user requests a read,
* or when a stream opens that may have requested reads sitting in the queue, etc.
**/
- (void)maybeDequeueRead
{
// Unset the flag indicating a call to this method is scheduled
theFlags &= ~kDequeueReadScheduled;
// If we're not currently processing a read AND we have an available read stream
if((theCurrentRead == nil) && (theReadStream != NULL))
{
if([theReadQueue count] > 0)
{
// Dequeue the next object in the write queue
theCurrentRead = [[theReadQueue objectAtIndex:0] retain];
[theReadQueue removeObjectAtIndex:0];
if([theCurrentRead isKindOfClass:[AsyncSpecialPacket class]])
{
// Attempt to start TLS
theFlags |= kStartingReadTLS;
// This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set
[self maybeStartTLS];
}
else
{
// Start time-out timer
if(theCurrentRead->timeout >= 0.0)
{
theReadTimer = [NSTimer timerWithTimeInterval:theCurrentRead->timeout
target:self
selector:@selector(doReadTimeout:)
userInfo:nil
repeats:NO];
[self runLoopAddTimer:theReadTimer];
}
// Immediately read, if possible
[self doBytesAvailable];
}
}
else if(theFlags & kDisconnectAfterReads)
{
if(theFlags & kDisconnectAfterWrites)
{
if(([theWriteQueue count] == 0) && (theCurrentWrite == nil))
{
[self disconnect];
}
}
else
{
[self disconnect];
}
}
}
}
/**
* Call this method in doBytesAvailable instead of CFReadStreamHasBytesAvailable().
* This method supports pre-buffering properly as well as the kSocketHasBytesAvailable flag.
**/
- (BOOL)hasBytesAvailable
{
if ((theFlags & kSocketHasBytesAvailable) || ([partialReadBuffer length] > 0))
{
return YES;
}
else
{
return CFReadStreamHasBytesAvailable(theReadStream);
}
}
/**
* Call this method in doBytesAvailable instead of CFReadStreamRead().
* This method support pre-buffering properly.
**/
- (CFIndex)readIntoBuffer:(void *)buffer maxLength:(NSUInteger)length
{
if([partialReadBuffer length] > 0)
{
// Determine the maximum amount of data to read
NSUInteger bytesToRead = MIN(length, [partialReadBuffer length]);
// Copy the bytes from the partial read buffer
memcpy(buffer, [partialReadBuffer bytes], (size_t)bytesToRead);
// Remove the copied bytes from the partial read buffer
[partialReadBuffer replaceBytesInRange:NSMakeRange(0, bytesToRead) withBytes:NULL length:0];
return (CFIndex)bytesToRead;
}
else
{
// Unset the "has-bytes-available" flag
theFlags &= ~kSocketHasBytesAvailable;
return CFReadStreamRead(theReadStream, (UInt8 *)buffer, length);
}
}
/**
* This method is called when a new read is taken from the read queue or when new data becomes available on the stream.
**/
- (void)doBytesAvailable
{
// If data is available on the stream, but there is no read request, then we don't need to process the data yet.
// Also, if there is a read request but no read stream setup, we can't process any data yet.
if((theCurrentRead == nil) || (theReadStream == NULL))
{
return;
}
// Note: This method is not called if theCurrentRead is an AsyncSpecialPacket (startTLS packet)
NSUInteger totalBytesRead = 0;
BOOL done = NO;
BOOL socketError = NO;
BOOL maxoutError = NO;
while(!done && !socketError && !maxoutError && [self hasBytesAvailable])
{
BOOL didPreBuffer = NO;
BOOL didReadFromPreBuffer = NO;
// There are 3 types of read packets:
//
// 1) Read all available data.
// 2) Read a specific length of data.
// 3) Read up to a particular terminator.
NSUInteger bytesToRead;
if (theCurrentRead->term != nil)
{
// Read type #3 - read up to a terminator
//
// If pre-buffering is enabled we'll read a chunk and search for the terminator.
// If the terminator is found, overflow data will be placed in the partialReadBuffer for the next read.
//
// If pre-buffering is disabled we'll be forced to read only a few bytes.
// Just enough to ensure we don't go past our term or over our max limit.
//
// If we already have data pre-buffered, we can read directly from it.
if ([partialReadBuffer length] > 0)
{
didReadFromPreBuffer = YES;
bytesToRead = [theCurrentRead readLengthForTermWithPreBuffer:partialReadBuffer found:&done];
}
else
{
if (theFlags & kEnablePreBuffering)
{
didPreBuffer = YES;
bytesToRead = [theCurrentRead prebufferReadLengthForTerm];
}
else
{
bytesToRead = [theCurrentRead readLengthForTerm];
}
}
}
else
{
// Read type #1 or #2
bytesToRead = [theCurrentRead readLengthForNonTerm];
}
// Make sure we have enough room in the buffer for our read
NSUInteger buffSize = [theCurrentRead->buffer length];
NSUInteger buffSpace = buffSize - theCurrentRead->startOffset - theCurrentRead->bytesDone;
if (bytesToRead > buffSpace)
{
NSUInteger buffInc = bytesToRead - buffSpace;
[theCurrentRead->buffer increaseLengthBy:buffInc];
}
// Read data into packet buffer
void *buffer = [theCurrentRead->buffer mutableBytes] + theCurrentRead->startOffset;
void *subBuffer = buffer + theCurrentRead->bytesDone;
CFIndex result = [self readIntoBuffer:subBuffer maxLength:bytesToRead];
// Check results
if (result < 0)
{
socketError = YES;
}
else
{
CFIndex bytesRead = result;
// Update total amount read for the current read
theCurrentRead->bytesDone += bytesRead;
// Update total amount read in this method invocation
totalBytesRead += bytesRead;
// Is packet done?
if (theCurrentRead->readLength > 0)
{
// Read type #2 - read a specific length of data
done = (theCurrentRead->bytesDone == theCurrentRead->readLength);
}
else if (theCurrentRead->term != nil)
{
// Read type #3 - read up to a terminator
if (didPreBuffer)
{
// Search for the terminating sequence within the big chunk we just read.
NSInteger overflow = [theCurrentRead searchForTermAfterPreBuffering:result];
if (overflow > 0)
{
// Copy excess data into partialReadBuffer
void *overflowBuffer = buffer + theCurrentRead->bytesDone - overflow;
[partialReadBuffer appendBytes:overflowBuffer length:overflow];
// Update the bytesDone variable.
theCurrentRead->bytesDone -= overflow;
// Note: The completeCurrentRead method will trim the buffer for us.
}
done = (overflow >= 0);
}
else if (didReadFromPreBuffer)
{
// Our 'done' variable was updated via the readLengthForTermWithPreBuffer:found: method
}
else
{
// Search for the terminating sequence at the end of the buffer
NSUInteger termlen = [theCurrentRead->term length];
if(theCurrentRead->bytesDone >= termlen)
{
void *bufferEnd = buffer + (theCurrentRead->bytesDone - termlen);
const void *seq = [theCurrentRead->term bytes];
done = (memcmp (bufferEnd, seq, termlen) == 0);
}
}
if(!done && theCurrentRead->maxLength > 0)
{
// We're not done and there's a set maxLength.
// Have we reached that maxLength yet?
if(theCurrentRead->bytesDone >= theCurrentRead->maxLength)
{
maxoutError = YES;
}
}
}
else
{
// Read type #1 - read all available data
//
// We're done when:
// - we reach maxLength (if there is a max)
// - all readable is read (see below)
if (theCurrentRead->maxLength > 0)
{
done = (theCurrentRead->bytesDone >= theCurrentRead->maxLength);
}
}
}
}
if (theCurrentRead->readLength <= 0 && theCurrentRead->term == nil)
{
// Read type #1 - read all available data
if (theCurrentRead->bytesDone > 0)
{
// Ran out of bytes, so the "read-all-available-data" type packet is done
done = YES;
}
}
if (done)
{
[self completeCurrentRead];
if (!socketError) [self scheduleDequeueRead];
}
else if (totalBytesRead > 0)
{
// We're not done with the readToLength or readToData yet, but we have read in some bytes
if ([theDelegate respondsToSelector:@selector(onSocket:didReadPartialDataOfLength:tag:)])
{
[theDelegate onSocket:self didReadPartialDataOfLength:totalBytesRead tag:theCurrentRead->tag];
}
}
if(socketError)
{
CFStreamError err = CFReadStreamGetError(theReadStream);
[self closeWithError:[self errorFromCFStreamError:err]];
return;
}
if(maxoutError)
{
[self closeWithError:[self getReadMaxedOutError]];
return;
}
}
// Ends current read and calls delegate.
- (void)completeCurrentRead
{
NSAssert(theCurrentRead, @"Trying to complete current read when there is no current read.");
NSData *result;
if (theCurrentRead->bufferOwner)
{
// We created the buffer on behalf of the user.
// Trim our buffer to be the proper size.
[theCurrentRead->buffer setLength:theCurrentRead->bytesDone];
result = theCurrentRead->buffer;
}
else
{
// We did NOT create the buffer.
// The buffer is owned by the caller.
// Only trim the buffer if we had to increase its size.
if ([theCurrentRead->buffer length] > theCurrentRead->originalBufferLength)
{
NSUInteger readSize = theCurrentRead->startOffset + theCurrentRead->bytesDone;
NSUInteger origSize = theCurrentRead->originalBufferLength;
NSUInteger buffSize = MAX(readSize, origSize);
[theCurrentRead->buffer setLength:buffSize];
}
void *buffer = [theCurrentRead->buffer mutableBytes] + theCurrentRead->startOffset;
result = [NSData dataWithBytesNoCopy:buffer length:theCurrentRead->bytesDone freeWhenDone:NO];
}
if([theDelegate respondsToSelector:@selector(onSocket:didReadData:withTag:)])
{
[theDelegate onSocket:self didReadData:result withTag:theCurrentRead->tag];
}
// Caller may have disconnected in the above delegate method
if (theCurrentRead != nil)
{
[self endCurrentRead];
}
}
// Ends current read.
- (void)endCurrentRead
{
NSAssert(theCurrentRead, @"Trying to end current read when there is no current read.");
[theReadTimer invalidate];
theReadTimer = nil;
[theCurrentRead release];
theCurrentRead = nil;
}
- (void)doReadTimeout:(NSTimer *)timer
{
#pragma unused(timer)
NSTimeInterval timeoutExtension = 0.0;
if([theDelegate respondsToSelector:@selector(onSocket:shouldTimeoutReadWithTag:elapsed:bytesDone:)])
{
timeoutExtension = [theDelegate onSocket:self shouldTimeoutReadWithTag:theCurrentRead->tag
elapsed:theCurrentRead->timeout
bytesDone:theCurrentRead->bytesDone];
}
if(timeoutExtension > 0.0)
{
theCurrentRead->timeout += timeoutExtension;
theReadTimer = [NSTimer timerWithTimeInterval:timeoutExtension
target:self
selector:@selector(doReadTimeout:)
userInfo:nil
repeats:NO];
[self runLoopAddTimer:theReadTimer];
}
else
{
// Do not call endCurrentRead here.
// We must allow the delegate access to any partial read in the unreadData method.
[self closeWithError:[self getReadTimeoutError]];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Writing
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if (data == nil || [data length] == 0) return;
if (theFlags & kForbidReadsWrites) return;
AsyncWritePacket *packet = [[AsyncWritePacket alloc] initWithData:data timeout:timeout tag:tag];
[theWriteQueue addObject:packet];
[self scheduleDequeueWrite];
[packet release];
}
- (void)scheduleDequeueWrite
{
if((theFlags & kDequeueWriteScheduled) == 0)
{
theFlags |= kDequeueWriteScheduled;
[self performSelector:@selector(maybeDequeueWrite) withObject:nil afterDelay:0 inModes:theRunLoopModes];
}
}
/**
* Conditionally starts a new write.
*
* IF there is not another write in process
* AND there is a write queued
* AND we have a write stream available
*
* This method also handles auto-disconnect post read/write completion.
**/
- (void)maybeDequeueWrite
{
// Unset the flag indicating a call to this method is scheduled
theFlags &= ~kDequeueWriteScheduled;
// If we're not currently processing a write AND we have an available write stream
if((theCurrentWrite == nil) && (theWriteStream != NULL))
{
if([theWriteQueue count] > 0)
{
// Dequeue the next object in the write queue
theCurrentWrite = [[theWriteQueue objectAtIndex:0] retain];
[theWriteQueue removeObjectAtIndex:0];
if([theCurrentWrite isKindOfClass:[AsyncSpecialPacket class]])
{
// Attempt to start TLS
theFlags |= kStartingWriteTLS;
// This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set
[self maybeStartTLS];
}
else
{
// Start time-out timer
if(theCurrentWrite->timeout >= 0.0)
{
theWriteTimer = [NSTimer timerWithTimeInterval:theCurrentWrite->timeout
target:self
selector:@selector(doWriteTimeout:)
userInfo:nil
repeats:NO];
[self runLoopAddTimer:theWriteTimer];
}
// Immediately write, if possible
[self doSendBytes];
}
}
else if(theFlags & kDisconnectAfterWrites)
{
if(theFlags & kDisconnectAfterReads)
{
if(([theReadQueue count] == 0) && (theCurrentRead == nil))
{
[self disconnect];
}
}
else
{
[self disconnect];
}
}
}
}
/**
* Call this method in doSendBytes instead of CFWriteStreamCanAcceptBytes().
* This method supports the kSocketCanAcceptBytes flag.
**/
- (BOOL)canAcceptBytes
{
if (theFlags & kSocketCanAcceptBytes)
{
return YES;
}
else
{
return CFWriteStreamCanAcceptBytes(theWriteStream);
}
}
- (void)doSendBytes
{
if ((theCurrentWrite == nil) || (theWriteStream == NULL))
{
return;
}
// Note: This method is not called if theCurrentWrite is an AsyncSpecialPacket (startTLS packet)
NSUInteger totalBytesWritten = 0;
BOOL done = NO;
BOOL error = NO;
while (!done && !error && [self canAcceptBytes])
{
// Figure out what to write
NSUInteger bytesRemaining = [theCurrentWrite->buffer length] - theCurrentWrite->bytesDone;
NSUInteger bytesToWrite = (bytesRemaining < WRITE_CHUNKSIZE) ? bytesRemaining : WRITE_CHUNKSIZE;
UInt8 *writestart = (UInt8 *)([theCurrentWrite->buffer bytes] + theCurrentWrite->bytesDone);
// Write
CFIndex result = CFWriteStreamWrite(theWriteStream, writestart, bytesToWrite);
// Unset the "can accept bytes" flag
theFlags &= ~kSocketCanAcceptBytes;
// Check results
if (result < 0)
{
error = YES;
}
else
{
CFIndex bytesWritten = result;
// Update total amount read for the current write
theCurrentWrite->bytesDone += bytesWritten;
// Update total amount written in this method invocation
totalBytesWritten += bytesWritten;
// Is packet done?
done = ([theCurrentWrite->buffer length] == theCurrentWrite->bytesDone);
}
}
if(done)
{
[self completeCurrentWrite];
[self scheduleDequeueWrite];
}
else if(error)
{
CFStreamError err = CFWriteStreamGetError(theWriteStream);
[self closeWithError:[self errorFromCFStreamError:err]];
return;
}
else if (totalBytesWritten > 0)
{
// We're not done with the entire write, but we have written some bytes
if ([theDelegate respondsToSelector:@selector(onSocket:didWritePartialDataOfLength:tag:)])
{
[theDelegate onSocket:self didWritePartialDataOfLength:totalBytesWritten tag:theCurrentWrite->tag];
}
}
}
// Ends current write and calls delegate.
- (void)completeCurrentWrite
{
NSAssert(theCurrentWrite, @"Trying to complete current write when there is no current write.");
if ([theDelegate respondsToSelector:@selector(onSocket:didWriteDataWithTag:)])
{
[theDelegate onSocket:self didWriteDataWithTag:theCurrentWrite->tag];
}
if (theCurrentWrite != nil) [self endCurrentWrite]; // Caller may have disconnected.
}
// Ends current write.
- (void)endCurrentWrite
{
NSAssert(theCurrentWrite, @"Trying to complete current write when there is no current write.");
[theWriteTimer invalidate];
theWriteTimer = nil;
[theCurrentWrite release];
theCurrentWrite = nil;
}
- (void)doWriteTimeout:(NSTimer *)timer
{
#pragma unused(timer)
NSTimeInterval timeoutExtension = 0.0;
if([theDelegate respondsToSelector:@selector(onSocket:shouldTimeoutWriteWithTag:elapsed:bytesDone:)])
{
timeoutExtension = [theDelegate onSocket:self shouldTimeoutWriteWithTag:theCurrentWrite->tag
elapsed:theCurrentWrite->timeout
bytesDone:theCurrentWrite->bytesDone];
}
if(timeoutExtension > 0.0)
{
theCurrentWrite->timeout += timeoutExtension;
theWriteTimer = [NSTimer timerWithTimeInterval:timeoutExtension
target:self
selector:@selector(doWriteTimeout:)
userInfo:nil
repeats:NO];
[self runLoopAddTimer:theWriteTimer];
}
else
{
[self closeWithError:[self getWriteTimeoutError]];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Security
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)startTLS:(NSDictionary *)tlsSettings
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if(tlsSettings == nil)
{
// Passing nil/NULL to CFReadStreamSetProperty will appear to work the same as passing an empty dictionary,
// but causes problems if we later try to fetch the remote host's certificate.
//
// To be exact, it causes the following to return NULL instead of the normal result:
// CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates)
//
// So we use an empty dictionary instead, which works perfectly.
tlsSettings = [NSDictionary dictionary];
}
AsyncSpecialPacket *packet = [[AsyncSpecialPacket alloc] initWithTLSSettings:tlsSettings];
[theReadQueue addObject:packet];
[self scheduleDequeueRead];
[theWriteQueue addObject:packet];
[self scheduleDequeueWrite];
[packet release];
}
- (void)maybeStartTLS
{
// We can't start TLS until:
// - All queued reads prior to the user calling StartTLS are complete
// - All queued writes prior to the user calling StartTLS are complete
//
// We'll know these conditions are met when both kStartingReadTLS and kStartingWriteTLS are set
if((theFlags & kStartingReadTLS) && (theFlags & kStartingWriteTLS))
{
AsyncSpecialPacket *tlsPacket = (AsyncSpecialPacket *)theCurrentRead;
BOOL didStartOnReadStream = CFReadStreamSetProperty(theReadStream, kCFStreamPropertySSLSettings,
(CFDictionaryRef)tlsPacket->tlsSettings);
BOOL didStartOnWriteStream = CFWriteStreamSetProperty(theWriteStream, kCFStreamPropertySSLSettings,
(CFDictionaryRef)tlsPacket->tlsSettings);
if(!didStartOnReadStream || !didStartOnWriteStream)
{
[self closeWithError:[self getSocketError]];
}
}
}
- (void)onTLSHandshakeSuccessful
{
if((theFlags & kStartingReadTLS) && (theFlags & kStartingWriteTLS))
{
theFlags &= ~kStartingReadTLS;
theFlags &= ~kStartingWriteTLS;
if([theDelegate respondsToSelector:@selector(onSocketDidSecure:)])
{
[theDelegate onSocketDidSecure:self];
}
[self endCurrentRead];
[self endCurrentWrite];
[self scheduleDequeueRead];
[self scheduleDequeueWrite];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark CF Callbacks
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)doCFSocketCallback:(CFSocketCallBackType)type
forSocket:(CFSocketRef)sock
withAddress:(NSData *)address
withData:(const void *)pData
{
#pragma unused(address)
NSParameterAssert ((sock == theSocket4) || (sock == theSocket6));
switch (type)
{
case kCFSocketConnectCallBack:
// The data argument is either NULL or a pointer to an SInt32 error code, if the connect failed.
if(pData)
[self doSocketOpen:sock withCFSocketError:kCFSocketError];
else
[self doSocketOpen:sock withCFSocketError:kCFSocketSuccess];
break;
case kCFSocketAcceptCallBack:
[self doAcceptFromSocket:sock withNewNativeSocket:*((CFSocketNativeHandle *)pData)];
break;
default:
NSLog(@"AsyncSocket %p received unexpected CFSocketCallBackType %i", self, (int)type);
break;
}
}
- (void)doCFReadStreamCallback:(CFStreamEventType)type forStream:(CFReadStreamRef)stream
{
#pragma unused(stream)
NSParameterAssert(theReadStream != NULL);
CFStreamError err;
switch (type)
{
case kCFStreamEventOpenCompleted:
theFlags |= kDidCompleteOpenForRead;
[self doStreamOpen];
break;
case kCFStreamEventHasBytesAvailable:
if(theFlags & kStartingReadTLS) {
[self onTLSHandshakeSuccessful];
}
else {
theFlags |= kSocketHasBytesAvailable;
[self doBytesAvailable];
}
break;
case kCFStreamEventErrorOccurred:
case kCFStreamEventEndEncountered:
err = CFReadStreamGetError (theReadStream);
[self closeWithError: [self errorFromCFStreamError:err]];
break;
default:
NSLog(@"AsyncSocket %p received unexpected CFReadStream callback, CFStreamEventType %i", self, (int)type);
}
}
- (void)doCFWriteStreamCallback:(CFStreamEventType)type forStream:(CFWriteStreamRef)stream
{
#pragma unused(stream)
NSParameterAssert(theWriteStream != NULL);
CFStreamError err;
switch (type)
{
case kCFStreamEventOpenCompleted:
theFlags |= kDidCompleteOpenForWrite;
[self doStreamOpen];
break;
case kCFStreamEventCanAcceptBytes:
if(theFlags & kStartingWriteTLS) {
[self onTLSHandshakeSuccessful];
}
else {
theFlags |= kSocketCanAcceptBytes;
[self doSendBytes];
}
break;
case kCFStreamEventErrorOccurred:
case kCFStreamEventEndEncountered:
err = CFWriteStreamGetError (theWriteStream);
[self closeWithError: [self errorFromCFStreamError:err]];
break;
default:
NSLog(@"AsyncSocket %p received unexpected CFWriteStream callback, CFStreamEventType %i", self, (int)type);
}
}
/**
* This is the callback we setup for CFSocket.
* This method does nothing but forward the call to it's Objective-C counterpart
**/
static void MyCFSocketCallback (CFSocketRef sref, CFSocketCallBackType type, CFDataRef address, const void *pData, void *pInfo)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AsyncSocket *theSocket = [[(AsyncSocket *)pInfo retain] autorelease];
[theSocket doCFSocketCallback:type forSocket:sref withAddress:(NSData *)address withData:pData];
[pool release];
}
/**
* This is the callback we setup for CFReadStream.
* This method does nothing but forward the call to it's Objective-C counterpart
**/
static void MyCFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type, void *pInfo)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AsyncSocket *theSocket = [[(AsyncSocket *)pInfo retain] autorelease];
[theSocket doCFReadStreamCallback:type forStream:stream];
[pool release];
}
/**
* This is the callback we setup for CFWriteStream.
* This method does nothing but forward the call to it's Objective-C counterpart
**/
static void MyCFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType type, void *pInfo)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AsyncSocket *theSocket = [[(AsyncSocket *)pInfo retain] autorelease];
[theSocket doCFWriteStreamCallback:type forStream:stream];
[pool release];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Class Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Return line separators.
+ (NSData *)CRLFData
{
return [NSData dataWithBytes:"\x0D\x0A" length:2];
}
+ (NSData *)CRData
{
return [NSData dataWithBytes:"\x0D" length:1];
}
+ (NSData *)LFData
{
return [NSData dataWithBytes:"\x0A" length:1];
}
+ (NSData *)ZeroData
{
return [NSData dataWithBytes:"" length:1];
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/AsyncSocket.m
|
Objective-C
|
oos
| 124,597
|
<html>
<body>
<h1>Welcome to the CocoaAsyncSocket project!</h1>
<p>
A wealth of documentation can be found on the Google Code homepage:</br>
<a href="http://code.google.com/p/cocoaasyncsocket/">http://code.google.com/p/cocoaasyncsocket/</a>
</p>
<p>
If you are new to networking, it is recommended you start by reading the Intro page:<br/>
<a href="http://code.google.com/p/cocoaasyncsocket/wiki/Intro">http://code.google.com/p/cocoaasyncsocket/wiki/Intro</a>
</p>
<p>
If you are a seasoned networking professional, with 10+ years of experience writing low-level socket code,
and detailed knowledge of the underlying BSD networking stack, then you can skip the CommonPitfalls page.<br/>
Otherwise, it should be considered mandatory reading:<br/>
<a href="http://code.google.com/p/cocoaasyncsocket/wiki/CommonPitfalls">http://code.google.com/p/cocoaasyncsocket/wiki/CommonPitfalls</a>
</p>
<h4>
A little bit of investment in your knowledge and understanding of networking fundamentals can go a long way.<br/>
And it can save you a LOT of time and frustration in the long run.
</h4>
<p>
The API reference page can be found here:</br/>
<a href="http://code.google.com/p/cocoaasyncsocket/wiki/Reference_AsyncSocket">http://code.google.com/p/cocoaasyncsocket/wiki/Reference_AsyncSocket</a>
</p>
<p>
In addition to this, the headers are generally well documented.
</p>
<p>
If you have any questions you are welcome to post to the CocoaAsyncSocket mailing list:<br/>
<a href="http://groups.google.com/group/cocoaasyncsocket">http://groups.google.com/group/cocoaasyncsocket</a><br/>
<br/>
The list is archived, and available for browsing online.<br/>
You may be able to instantly find the answer you're looking for with a quick search.<br/>
</p>
<h3>We hope the CocoaAsyncSocket project can provide you with powerful and easy to use networking libraries.</h3>
</body>
</html>
|
zzymoon-cocoaasyncsocket
|
RunLoop/Documentation.html
|
HTML
|
oos
| 1,877
|
//
// AsyncUdpSocket.h
//
// This class is in the public domain.
// Originally created by Robbie Hanson on Wed Oct 01 2008.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import <Foundation/Foundation.h>
@class AsyncSendPacket;
@class AsyncReceivePacket;
extern NSString *const AsyncUdpSocketException;
extern NSString *const AsyncUdpSocketErrorDomain;
enum AsyncUdpSocketError
{
AsyncUdpSocketCFSocketError = kCFSocketError, // From CFSocketError enum
AsyncUdpSocketNoError = 0, // Never used
AsyncUdpSocketBadParameter, // Used if given a bad parameter (such as an improper address)
AsyncUdpSocketIPv4Unavailable, // Used if you bind/connect using IPv6 only
AsyncUdpSocketIPv6Unavailable, // Used if you bind/connect using IPv4 only (or iPhone)
AsyncUdpSocketSendTimeoutError,
AsyncUdpSocketReceiveTimeoutError
};
typedef enum AsyncUdpSocketError AsyncUdpSocketError;
@interface AsyncUdpSocket : NSObject
{
CFSocketRef theSocket4; // IPv4 socket
CFSocketRef theSocket6; // IPv6 socket
CFRunLoopSourceRef theSource4; // For theSocket4
CFRunLoopSourceRef theSource6; // For theSocket6
CFRunLoopRef theRunLoop;
CFSocketContext theContext;
NSArray *theRunLoopModes;
NSMutableArray *theSendQueue;
AsyncSendPacket *theCurrentSend;
NSTimer *theSendTimer;
NSMutableArray *theReceiveQueue;
AsyncReceivePacket *theCurrentReceive;
NSTimer *theReceiveTimer;
id theDelegate;
UInt16 theFlags;
long theUserData;
NSString *cachedLocalHost;
UInt16 cachedLocalPort;
NSString *cachedConnectedHost;
UInt16 cachedConnectedPort;
UInt32 maxReceiveBufferSize;
}
/**
* Creates new instances of AsyncUdpSocket.
**/
- (id)init;
- (id)initWithDelegate:(id)delegate;
- (id)initWithDelegate:(id)delegate userData:(long)userData;
/**
* Creates new instances of AsyncUdpSocket that support only IPv4 or IPv6.
* The other init methods will support both, unless specifically binded or connected to one protocol.
* If you know you'll only be using one protocol, these init methods may be a bit more efficient.
**/
- (id)initIPv4;
- (id)initIPv6;
- (id)delegate;
- (void)setDelegate:(id)delegate;
- (long)userData;
- (void)setUserData:(long)userData;
/**
* Returns the local address info for the socket.
*
* Note: Address info may not be available until after the socket has been bind'ed,
* or until after data has been sent.
**/
- (NSString *)localHost;
- (UInt16)localPort;
/**
* Returns the remote address info for the socket.
*
* Note: Since UDP is connectionless by design, connected address info
* will not be available unless the socket is explicitly connected to a remote host/port
**/
- (NSString *)connectedHost;
- (UInt16)connectedPort;
/**
* Returns whether or not this socket has been connected to a single host.
* By design, UDP is a connectionless protocol, and connecting is not needed.
* If connected, the socket will only be able to send/receive data to/from the connected host.
**/
- (BOOL)isConnected;
/**
* Returns whether or not this socket has been closed.
* The only way a socket can be closed is if you explicitly call one of the close methods.
**/
- (BOOL)isClosed;
/**
* Returns whether or not this socket supports IPv4.
* By default this will be true, unless the socket is specifically initialized as IPv6 only,
* or is binded or connected to an IPv6 address.
**/
- (BOOL)isIPv4;
/**
* Returns whether or not this socket supports IPv6.
* By default this will be true, unless the socket is specifically initialized as IPv4 only,
* or is binded or connected to an IPv4 address.
*
* This method will also return false on platforms that do not support IPv6.
* Note: The iPhone does not currently support IPv6.
**/
- (BOOL)isIPv6;
/**
* Returns the mtu of the socket.
* If unknown, returns zero.
*
* Sending data larger than this may result in an error.
* This is an advanced topic, and one should understand the wide range of mtu's on networks and the internet.
* Therefore this method is only for reference and may be of little use in many situations.
**/
- (unsigned int)maximumTransmissionUnit;
/**
* Binds the UDP socket to the given port and optional address.
* Binding should be done for server sockets that receive data prior to sending it.
* Client sockets can skip binding,
* as the OS will automatically assign the socket an available port when it starts sending data.
*
* You cannot bind a socket after its been connected.
* You can only bind a socket once.
* You can still connect a socket (if desired) after binding.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)bindToPort:(UInt16)port error:(NSError **)errPtr;
- (BOOL)bindToAddress:(NSString *)localAddr port:(UInt16)port error:(NSError **)errPtr;
/**
* Connects the UDP socket to the given host and port.
* By design, UDP is a connectionless protocol, and connecting is not needed.
*
* Choosing to connect to a specific host/port has the following effect:
* - You will only be able to send data to the connected host/port.
* - You will only be able to receive data from the connected host/port.
* - You will receive ICMP messages that come from the connected host/port, such as "connection refused".
*
* Connecting a UDP socket does not result in any communication on the socket.
* It simply changes the internal state of the socket.
*
* You cannot bind a socket after its been connected.
* You can only connect a socket once.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)connectToHost:(NSString *)host onPort:(UInt16)port error:(NSError **)errPtr;
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
/**
* Join multicast group
*
* Group should be an IP address (eg @"225.228.0.1")
**/
- (BOOL)joinMulticastGroup:(NSString *)group error:(NSError **)errPtr;
- (BOOL)joinMulticastGroup:(NSString *)group withAddress:(NSString *)interface error:(NSError **)errPtr;
/**
* By default, the underlying socket in the OS will not allow you to send broadcast messages.
* In order to send broadcast messages, you need to enable this functionality in the socket.
*
* A broadcast is a UDP message to addresses like "192.168.255.255" or "255.255.255.255" that is
* delivered to every host on the network.
* The reason this is generally disabled by default is to prevent
* accidental broadcast messages from flooding the network.
**/
- (BOOL)enableBroadcast:(BOOL)flag error:(NSError **)errPtr;
/**
* Asynchronously sends the given data, with the given timeout and tag.
*
* This method may only be used with a connected socket.
*
* If data is nil or zero-length, this method does nothing and immediately returns NO.
* If the socket is not connected, this method does nothing and immediately returns NO.
**/
- (BOOL)sendData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Asynchronously sends the given data, with the given timeout and tag, to the given host and port.
*
* This method cannot be used with a connected socket.
*
* If data is nil or zero-length, this method does nothing and immediately returns NO.
* If the socket is connected, this method does nothing and immediately returns NO.
* If unable to resolve host to a valid IPv4 or IPv6 address, this method returns NO.
**/
- (BOOL)sendData:(NSData *)data toHost:(NSString *)host port:(UInt16)port withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Asynchronously sends the given data, with the given timeout and tag, to the given address.
*
* This method cannot be used with a connected socket.
*
* If data is nil or zero-length, this method does nothing and immediately returns NO.
* If the socket is connected, this method does nothing and immediately returns NO.
**/
- (BOOL)sendData:(NSData *)data toAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Asynchronously receives a single datagram packet.
*
* If the receive succeeds, the onUdpSocket:didReceiveData:fromHost:port:tag delegate method will be called.
* Otherwise, a timeout will occur, and the onUdpSocket:didNotReceiveDataWithTag: delegate method will be called.
**/
- (void)receiveWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Closes the socket immediately. Any pending send or receive operations are dropped.
**/
- (void)close;
/**
* Closes after all pending send operations have completed.
* After calling this, the sendData: and receive: methods will do nothing.
* In other words, you won't be able to add any more send or receive operations to the queue.
* The socket will close even if there are still pending receive operations.
**/
- (void)closeAfterSending;
/**
* Closes after all pending receive operations have completed.
* After calling this, the sendData: and receive: methods will do nothing.
* In other words, you won't be able to add any more send or receive operations to the queue.
* The socket will close even if there are still pending send operations.
**/
- (void)closeAfterReceiving;
/**
* Closes after all pending send and receive operations have completed.
* After calling this, the sendData: and receive: methods will do nothing.
* In other words, you won't be able to add any more send or receive operations to the queue.
**/
- (void)closeAfterSendingAndReceiving;
/**
* Gets/Sets the maximum size of the buffer that will be allocated for receive operations.
* The default size is 9216 bytes.
*
* The theoretical maximum size of any IPv4 UDP packet is UINT16_MAX = 65535.
* The theoretical maximum size of any IPv6 UDP packet is UINT32_MAX = 4294967295.
*
* In practice, however, the size of UDP packets will be much smaller.
* Indeed most protocols will send and receive packets of only a few bytes,
* or will set a limit on the size of packets to prevent fragmentation in the IP layer.
*
* If you set the buffer size too small, the sockets API in the OS will silently discard
* any extra data, and you will not be notified of the error.
**/
- (UInt32)maxReceiveBufferSize;
- (void)setMaxReceiveBufferSize:(UInt32)max;
/**
* When you create an AsyncUdpSocket, it is added to the runloop of the current thread.
* So it is easiest to simply create the socket on the thread you intend to use it.
*
* If, however, you need to move the socket to a separate thread at a later time, this
* method may be used to accomplish the task.
*
* This method must be called from the thread/runloop the socket is currently running on.
*
* Note: After calling this method, all further method calls to this object should be done from the given runloop.
* Also, all delegate calls will be sent on the given runloop.
**/
- (BOOL)moveToRunLoop:(NSRunLoop *)runLoop;
/**
* Allows you to configure which run loop modes the socket uses.
* The default set of run loop modes is NSDefaultRunLoopMode.
*
* If you'd like your socket to continue operation during other modes, you may want to add modes such as
* NSModalPanelRunLoopMode or NSEventTrackingRunLoopMode. Or you may simply want to use NSRunLoopCommonModes.
*
* Note: NSRunLoopCommonModes is defined in 10.5. For previous versions one can use kCFRunLoopCommonModes.
**/
- (BOOL)setRunLoopModes:(NSArray *)runLoopModes;
/**
* Returns the current run loop modes the AsyncSocket instance is operating in.
* The default set of run loop modes is NSDefaultRunLoopMode.
**/
- (NSArray *)runLoopModes;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@protocol AsyncUdpSocketDelegate
@optional
/**
* Called when the datagram with the given tag has been sent.
**/
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag;
/**
* Called if an error occurs while trying to send a datagram.
* This could be due to a timeout, or something more serious such as the data being too large to fit in a sigle packet.
**/
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error;
/**
* Called when the socket has received the requested datagram.
*
* Due to the nature of UDP, you may occasionally receive undesired packets.
* These may be rogue UDP packets from unknown hosts,
* or they may be delayed packets arriving after retransmissions have already occurred.
* It's important these packets are properly ignored, while not interfering with the flow of your implementation.
* As an aid, this delegate method has a boolean return value.
* If you ever need to ignore a received packet, simply return NO,
* and AsyncUdpSocket will continue as if the packet never arrived.
* That is, the original receive request will still be queued, and will still timeout as usual if a timeout was set.
* For example, say you requested to receive data, and you set a timeout of 500 milliseconds, using a tag of 15.
* If rogue data arrives after 250 milliseconds, this delegate method would be invoked, and you could simply return NO.
* If the expected data then arrives within the next 250 milliseconds,
* this delegate method will be invoked, with a tag of 15, just as if the rogue data never appeared.
*
* Under normal circumstances, you simply return YES from this method.
**/
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port;
/**
* Called if an error occurs while trying to receive a requested datagram.
* This is generally due to a timeout, but could potentially be something else if some kind of OS error occurred.
**/
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error;
/**
* Called when the socket is closed.
* A socket is only closed if you explicitly call one of the close methods.
**/
- (void)onUdpSocketDidClose:(AsyncUdpSocket *)sock;
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/AsyncUdpSocket.h
|
Objective-C
|
oos
| 14,306
|
#import <Cocoa/Cocoa.h>
@class AsyncSocket;
@interface AppController : NSObject
{
AsyncSocket *listenSocket;
NSMutableArray *connectedSockets;
BOOL isRunning;
IBOutlet id logView;
IBOutlet id portField;
IBOutlet id startStopButton;
}
- (IBAction)startStop:(id)sender;
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/EchoServer/AppController.h
|
Objective-C
|
oos
| 294
|
#import "AppController.h"
#import "AsyncSocket.h"
#define WELCOME_MSG 0
#define ECHO_MSG 1
#define WARNING_MSG 2
#define READ_TIMEOUT 15.0
#define READ_TIMEOUT_EXTENSION 10.0
#define FORMAT(format, ...) [NSString stringWithFormat:(format), ##__VA_ARGS__]
@interface AppController (PrivateAPI)
- (void)logError:(NSString *)msg;
- (void)logInfo:(NSString *)msg;
- (void)logMessage:(NSString *)msg;
@end
@implementation AppController
- (id)init
{
if((self = [super init]))
{
listenSocket = [[AsyncSocket alloc] initWithDelegate:self];
connectedSockets = [[NSMutableArray alloc] initWithCapacity:1];
isRunning = NO;
}
return self;
}
- (void)awakeFromNib
{
[logView setString:@""];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(@"Ready");
// Advanced options - enable the socket to contine operations even during modal dialogs, and menu browsing
[listenSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
- (void)scrollToBottom
{
NSScrollView *scrollView = [logView enclosingScrollView];
NSPoint newScrollOrigin;
if ([[scrollView documentView] isFlipped])
newScrollOrigin = NSMakePoint(0.0F, NSMaxY([[scrollView documentView] frame]));
else
newScrollOrigin = NSMakePoint(0.0F, 0.0F);
[[scrollView documentView] scrollPoint:newScrollOrigin];
}
- (void)logError:(NSString *)msg
{
NSString *paragraph = [NSString stringWithFormat:@"%@\n", msg];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:1];
[attributes setObject:[NSColor redColor] forKey:NSForegroundColorAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[logView textStorage] appendAttributedString:as];
[self scrollToBottom];
}
- (void)logInfo:(NSString *)msg
{
NSString *paragraph = [NSString stringWithFormat:@"%@\n", msg];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:1];
[attributes setObject:[NSColor purpleColor] forKey:NSForegroundColorAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[logView textStorage] appendAttributedString:as];
[self scrollToBottom];
}
- (void)logMessage:(NSString *)msg
{
NSString *paragraph = [NSString stringWithFormat:@"%@\n", msg];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:1];
[attributes setObject:[NSColor blackColor] forKey:NSForegroundColorAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[logView textStorage] appendAttributedString:as];
[self scrollToBottom];
}
- (IBAction)startStop:(id)sender
{
if(!isRunning)
{
int port = [portField intValue];
if(port < 0 || port > 65535)
{
port = 0;
}
NSError *error = nil;
if(![listenSocket acceptOnPort:port error:&error])
{
[self logError:FORMAT(@"Error starting server: %@", error)];
return;
}
[self logInfo:FORMAT(@"Echo server started on port %hu", [listenSocket localPort])];
isRunning = YES;
[portField setEnabled:NO];
[startStopButton setTitle:@"Stop"];
}
else
{
// Stop accepting connections
[listenSocket disconnect];
// Stop any client connections
NSUInteger i;
for(i = 0; i < [connectedSockets count]; i++)
{
// Call disconnect on the socket,
// which will invoke the onSocketDidDisconnect: method,
// which will remove the socket from the list.
[[connectedSockets objectAtIndex:i] disconnect];
}
[self logInfo:@"Stopped Echo server"];
isRunning = false;
[portField setEnabled:YES];
[startStopButton setTitle:@"Start"];
}
}
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
[connectedSockets addObject:newSocket];
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
[self logInfo:FORMAT(@"Accepted client %@:%hu", host, port)];
NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:welcomeData withTimeout:-1 tag:WELCOME_MSG];
[sock readDataToData:[AsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
if(tag == ECHO_MSG)
{
[sock readDataToData:[AsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
NSString *msg = [[[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding] autorelease];
if(msg)
{
[self logMessage:msg];
}
else
{
[self logError:@"Error converting received data into UTF-8 String"];
}
// Even if we were unable to write the incoming data to the log,
// we're still going to echo it back to the client.
[sock writeData:data withTimeout:-1 tag:ECHO_MSG];
}
/**
* This method is called if a read has timed out.
* It allows us to optionally extend the timeout.
* We use this method to issue a warning to the user prior to disconnecting them.
**/
- (NSTimeInterval)onSocket:(AsyncSocket *)sock
shouldTimeoutReadWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length
{
if(elapsed <= READ_TIMEOUT)
{
NSString *warningMsg = @"Are you still there?\r\n";
NSData *warningData = [warningMsg dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:warningData withTimeout:-1 tag:WARNING_MSG];
return READ_TIMEOUT_EXTENSION;
}
return 0.0;
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
[self logInfo:FORMAT(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort])];
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
[connectedSockets removeObject:sock];
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/EchoServer/AppController.m
|
Objective-C
|
oos
| 6,007
|
//
// main.m
// EchoServer
//
// Created by Robbie Hanson on 7/10/08.
// Copyright __MyCompanyName__ 2008. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/EchoServer/main.m
|
Objective-C
|
oos
| 257
|
#import <UIKit/UIKit.h>
@class InterfaceTestViewController;
@class AsyncSocket;
@interface InterfaceTestAppDelegate : NSObject <UIApplicationDelegate>
{
CFHostRef host;
AsyncSocket *asyncSocket;
UIWindow *window;
InterfaceTestViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet InterfaceTestViewController *viewController;
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/InterfaceTest/Classes/InterfaceTestAppDelegate.h
|
Objective-C
|
oos
| 418
|
//
// InterfaceTestViewController.h
// InterfaceTest
//
// Created by Robbie Hanson on 10/15/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface InterfaceTestViewController : UIViewController {
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/InterfaceTest/Classes/InterfaceTestViewController.h
|
Objective-C
|
oos
| 258
|
//
// InterfaceTestViewController.m
// InterfaceTest
//
// Created by Robbie Hanson on 10/15/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "InterfaceTestViewController.h"
@implementation InterfaceTestViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/InterfaceTest/Classes/InterfaceTestViewController.m
|
Objective-C
|
oos
| 1,491
|
#import "InterfaceTestAppDelegate.h"
#import "InterfaceTestViewController.h"
#import "AsyncSocket.h"
#import <arpa/inet.h>
#import <net/if.h>
#import <ifaddrs.h>
@implementation InterfaceTestAppDelegate
@synthesize window;
@synthesize viewController;
- (void)listInterfaces
{
NSLog(@"listInterfaces");
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
if ((getifaddrs(&addrs) == 0))
{
cursor = addrs;
while (cursor != NULL)
{
NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
NSLog(@"%@", name);
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
}
- (NSData *)wifiAddress
{
// On iPhone, WiFi is always "en0"
NSData *result = nil;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
if ((getifaddrs(&addrs) == 0))
{
cursor = addrs;
while (cursor != NULL)
{
NSLog(@"cursor->ifa_name = %s", cursor->ifa_name);
if (strcmp(cursor->ifa_name, "en0") == 0)
{
if (cursor->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *)cursor->ifa_addr;
NSLog(@"cursor->ifa_addr = %s", inet_ntoa(addr->sin_addr));
result = [NSData dataWithBytes:addr length:sizeof(struct sockaddr_in)];
cursor = NULL;
}
else
{
cursor = cursor->ifa_next;
}
}
else
{
cursor = cursor->ifa_next;
}
}
freeifaddrs(addrs);
}
return result;
}
- (NSData *)cellAddress
{
// On iPhone, 3G is "pdp_ipX", where X is usually 0, but may possibly be 0-3 (i'm guessing...)
NSData *result = nil;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
if ((getifaddrs(&addrs) == 0))
{
cursor = addrs;
while (cursor != NULL)
{
NSLog(@"cursor->ifa_name = %s", cursor->ifa_name);
if (strncmp(cursor->ifa_name, "pdp_ip", 6) == 0)
{
if (cursor->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *)cursor->ifa_addr;
NSLog(@"cursor->ifa_addr = %s", inet_ntoa(addr->sin_addr));
result = [NSData dataWithBytes:addr length:sizeof(struct sockaddr_in)];
cursor = NULL;
}
else
{
cursor = cursor->ifa_next;
}
}
else
{
cursor = cursor->ifa_next;
}
}
freeifaddrs(addrs);
}
return result;
}
- (void)dnsResolveDidFinish
{
NSLog(@"dnsResolveDidFinish");
Boolean hasBeenResolved;
CFArrayRef addrs = CFHostGetAddressing(host, &hasBeenResolved);
if (!hasBeenResolved)
{
NSLog(@"Failed to resolve!");
return;
}
CFIndex count = CFArrayGetCount(addrs);
if (count == 0)
{
NSLog(@"Found 0 addresses!");
return;
}
struct sockaddr_in remoteAddr;
NSData *remoteAddrData = nil;
BOOL found = NO;
CFIndex i;
for (i = 0; i < count && !found; i++)
{
CFDataRef addr = CFArrayGetValueAtIndex(addrs, i);
struct sockaddr *saddr = (struct sockaddr *)CFDataGetBytePtr(addr);
if (saddr->sa_family == AF_INET)
{
struct sockaddr_in *saddr4 = (struct sockaddr_in *)saddr;
NSLog(@"Found IPv4 version: %s", inet_ntoa(saddr4->sin_addr));
memcpy(&remoteAddr, saddr, sizeof(remoteAddr));
remoteAddr.sin_port = htons(80);
remoteAddrData = [NSData dataWithBytes:&remoteAddr length:sizeof(remoteAddr)];
found = YES;
}
}
if (found == NO)
{
NSLog(@"Found no suitable addresses!");
return;
}
NSData *interfaceAddrData = [self wifiAddress];
// NSData *interfaceAddrData = [self cellAddress];
if (interfaceAddrData == nil)
{
NSLog(@"Requested interface not available");
return;
}
NSLog(@"Connecting...");
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
NSError *err = nil;
if (![asyncSocket connectToAddress:remoteAddrData viaInterfaceAddress:interfaceAddrData withTimeout:-1 error:&err])
{
NSLog(@"Error connecting: %@", err);
}
}
static void DNSResolveCallBack(CFHostRef theHost, CFHostInfoType typeInfo, const CFStreamError *error, void *info)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
InterfaceTestAppDelegate *instance = (InterfaceTestAppDelegate *)info;
[instance dnsResolveDidFinish];
[pool release];
}
- (void)startDNSResolve
{
NSLog(@"startDNSResolve");
NSLog(@"Resolving google.com...");
host = CFHostCreateWithName(kCFAllocatorDefault, CFSTR("google.com"));
if (host == NULL)
{
NSLog(@"wtf 1");
return;
}
Boolean result;
CFHostClientContext context;
context.version = 0;
context.info = self;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
result = CFHostSetClient(host, &DNSResolveCallBack, &context);
if (!result)
{
NSLog(@"wtf 2");
return;
}
CFHostScheduleWithRunLoop(host, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFStreamError error;
bzero(&error, sizeof(error));
result = CFHostStartInfoResolution(host, kCFHostAddresses, &error);
if (!result)
{
NSLog(@"Failed to start DNS resolve");
NSLog(@"error: domain(%i) code(%i)", (int)(error.domain), (int)(error.error));
}
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)remoteHost port:(UInt16)remotePort
{
NSLog(@"Socket is connected!");
NSLog(@"Remote Address: %@:%hu", remoteHost, remotePort);
NSString *localHost = [sock localHost];
UInt16 localPort = [sock localPort];
NSLog(@"Local Address: %@:%hu", localHost, localPort);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"application:didFinishLaunchingWithOptions:");
[self listInterfaces];
[self startDNSResolve];
// Add the view controller's view to the window and display.
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[viewController release];
[window release];
[super dealloc];
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/InterfaceTest/Classes/InterfaceTestAppDelegate.m
|
Objective-C
|
oos
| 5,802
|
//
// main.m
// InterfaceTest
//
// Created by Robbie Hanson on 10/15/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/InterfaceTest/main.m
|
Objective-C
|
oos
| 369
|
//
// X509Certificate.m
//
// This class is in the public domain.
// Originally created by Robbie Hanson on Mon Jan 26 2009.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
// This class is largely derived from Apple's sample code project: SSLSample.
// This class does not extract every bit of available information, just the most common fields.
#import "X509Certificate.h"
#import "AsyncSocket.h"
#import <Security/Security.h>
#define UTC_TIME_STRLEN 13
#define GENERALIZED_TIME_STRLEN 15
@implementation X509Certificate
// Standard app-level memory functions required by CDSA
static void * appMalloc (uint32 size, void *allocRef)
{
return malloc(size);
}
static void * appCalloc(uint32 num, uint32 size, void *allocRef)
{
return calloc(num, size);
}
static void * appRealloc (void *ptr, uint32 size, void *allocRef)
{
return realloc(ptr, size);
}
static void appFree (void *mem_ptr, void *allocRef)
{
free(mem_ptr);
}
static const CSSM_API_MEMORY_FUNCS memFuncs = {
(CSSM_MALLOC)appMalloc,
(CSSM_FREE)appFree,
(CSSM_REALLOC)appRealloc,
(CSSM_CALLOC)appCalloc,
NULL
};
static const CSSM_VERSION vers = {2, 0};
static const CSSM_GUID testGuid = { 0xFADE, 0, 0, { 1,2,3,4,5,6,7,0 }};
static BOOL CSSMStartup()
{
CSSM_RETURN crtn;
CSSM_PVC_MODE pvcPolicy = CSSM_PVC_NONE;
crtn = CSSM_Init (&vers,
CSSM_PRIVILEGE_SCOPE_NONE,
&testGuid,
CSSM_KEY_HIERARCHY_NONE,
&pvcPolicy,
NULL /* reserved */);
if(crtn != CSSM_OK)
{
cssmPerror("CSSM_Init", crtn);
return NO;
}
else
{
return YES;
}
}
static CSSM_CL_HANDLE CLStartup()
{
CSSM_CL_HANDLE clHandle;
CSSM_RETURN crtn;
if(CSSMStartup() == NO)
{
return 0;
}
crtn = CSSM_ModuleLoad(&gGuidAppleX509CL,
CSSM_KEY_HIERARCHY_NONE,
NULL, // eventHandler
NULL); // AppNotifyCallbackCtx
if(crtn != CSSM_OK)
{
cssmPerror("CSSM_ModuleLoad", crtn);
return 0;
}
crtn = CSSM_ModuleAttach (&gGuidAppleX509CL,
&vers,
&memFuncs, // memFuncs
0, // SubserviceID
CSSM_SERVICE_CL, // SubserviceFlags - Where is this used?
0, // AttachFlags
CSSM_KEY_HIERARCHY_NONE,
NULL, // FunctionTable
0, // NumFuncTable
NULL, // reserved
&clHandle);
if(crtn != CSSM_OK)
{
cssmPerror("CSSM_ModuleAttach", crtn);
return 0;
}
return clHandle;
}
static void CLShutdown(CSSM_CL_HANDLE clHandle)
{
CSSM_RETURN crtn;
crtn = CSSM_ModuleDetach(clHandle);
if(crtn != CSSM_OK)
{
cssmPerror("CSSM_ModuleDetach", crtn);
}
crtn = CSSM_ModuleUnload(&gGuidAppleX509CL, NULL, NULL);
if(crtn != CSSM_OK)
{
cssmPerror("CSSM_ModuleUnload", crtn);
}
}
static BOOL CompareCSSMData(const CSSM_DATA *d1, const CSSM_DATA *d2)
{
if(d1 == NULL || d2 == NULL)
{
return NO;
}
if(d1->Length != d2->Length)
{
return NO;
}
return memcmp(d1->Data, d2->Data, d1->Length) == 0;
}
static BOOL CompareOids(const CSSM_OID *oid1, const CSSM_OID *oid2)
{
if(oid1 == NULL || oid2 == NULL)
{
return NO;
}
if(oid1->Length != oid2->Length)
{
return NO;
}
return memcmp(oid1->Data, oid2->Data, oid1->Length) == 0;
}
static NSString* KeyForOid(const CSSM_OID *oid)
{
if(CompareOids(oid, &CSSMOID_CountryName))
{
return X509_COUNTRY;
}
if(CompareOids(oid, &CSSMOID_OrganizationName))
{
return X509_ORGANIZATION;
}
if(CompareOids(oid, &CSSMOID_LocalityName))
{
return X509_LOCALITY;
}
if(CompareOids(oid, &CSSMOID_OrganizationalUnitName))
{
return X509_ORANIZATIONAL_UNIT;
}
if(CompareOids(oid, &CSSMOID_CommonName))
{
return X509_COMMON_NAME;
}
if(CompareOids(oid, &CSSMOID_Surname))
{
return X509_SURNAME;
}
if(CompareOids(oid, &CSSMOID_Title))
{
return X509_TITLE;
}
if(CompareOids(oid, &CSSMOID_StateProvinceName))
{
return X509_STATE_PROVINCE;
}
if(CompareOids(oid, &CSSMOID_CollectiveStateProvinceName))
{
return X509_COLLECTIVE_STATE_PROVINCE;
}
if(CompareOids(oid, &CSSMOID_EmailAddress))
{
return X509_EMAIL_ADDRESS;
}
if(CompareOids(oid, &CSSMOID_StreetAddress))
{
return X509_STREET_ADDRESS;
}
if(CompareOids(oid, &CSSMOID_PostalCode))
{
return X509_POSTAL_CODE;
}
// Not every possible Oid is checked for.
// Feel free to add any you may need.
// They are listed in the Security Framework's aoisattr.h file.
return nil;
}
static NSString* DataToString(const CSSM_DATA *data, const CSSM_BER_TAG *type)
{
NSStringEncoding encoding;
switch (*type)
{
case BER_TAG_PRINTABLE_STRING :
case BER_TAG_TELETEX_STRING :
encoding = NSISOLatin1StringEncoding;
break;
case BER_TAG_PKIX_BMP_STRING :
case BER_TAG_PKIX_UNIVERSAL_STRING :
case BER_TAG_PKIX_UTF8_STRING :
encoding = NSUTF8StringEncoding;
break;
default :
return nil;
}
NSString *result = [[NSString alloc] initWithBytes:data->Data
length:data->Length
encoding:encoding];
return [result autorelease];
}
static NSDate* TimeToDate(const char *str, unsigned len)
{
BOOL isUTC;
unsigned i;
long year, month, day, hour, minute, second;
// Check for null or empty strings
if(str == NULL || len == 0)
{
return nil;
}
// Ignore NULL termination
if(str[len - 1] == '\0')
{
len--;
}
// Check for proper string length
if(len == UTC_TIME_STRLEN)
{
// 2-digit year, not Y2K compliant
isUTC = YES;
}
else if(len == GENERALIZED_TIME_STRLEN)
{
// 4-digit year
isUTC = NO;
}
else
{
// Unknown format
return nil;
}
// Check that all characters except last are digits
for(i = 0; i < (len - 1); i++)
{
if(!(isdigit(str[i])))
{
return nil;
}
}
// Check last character is a 'Z'
if(str[len - 1] != 'Z' )
{
return nil;
}
// Start parsing
i = 0;
char tmp[5];
// Year
if(isUTC)
{
tmp[0] = str[i++];
tmp[1] = str[i++];
tmp[2] = '\0';
year = strtol(tmp, NULL, 10);
// 2-digit year:
// 0 <= year < 50 : assume century 21
// 50 <= year < 70 : illegal per PKIX
// 70 < year <= 99 : assume century 20
if(year < 50)
{
year += 2000;
}
else if(year < 70)
{
return nil;
}
else
{
year += 1900;
}
}
else
{
tmp[0] = str[i++];
tmp[1] = str[i++];
tmp[2] = str[i++];
tmp[3] = str[i++];
tmp[4] = '\0';
year = strtol(tmp, NULL, 10);
}
// Month
tmp[0] = str[i++];
tmp[1] = str[i++];
tmp[2] = '\0';
month = strtol(tmp, NULL, 10);
// Months are represented in format from 1 to 12
if(month > 12 || month <= 0)
{
return nil;
}
// Day
tmp[0] = str[i++];
tmp[1] = str[i++];
tmp[2] = '\0';
day = strtol(tmp, NULL, 10);
// Days are represented in format from 1 to 31
if(day > 31 || day <= 0)
{
return nil;
}
// Hour
tmp[0] = str[i++];
tmp[1] = str[i++];
tmp[2] = '\0';
hour = strtol(tmp, NULL, 10);
// Hours are represented in format from 0 to 23
if(hour > 23 || hour < 0)
{
return nil;
}
// Minute
tmp[0] = str[i++];
tmp[1] = str[i++];
tmp[2] = '\0';
minute = strtol(tmp, NULL, 10);
// Minutes are represented in format from 0 to 59
if(minute > 59 || minute < 0)
{
return nil;
}
// Second
tmp[0] = str[i++];
tmp[1] = str[i++];
tmp[2] = '\0';
second = strtol(tmp, NULL, 10);
// Seconds are represented in format from 0 to 59
if(second > 59 || second < 0)
{
return nil;
}
CFGregorianDate gDate = { year, month, day, hour, minute, second };
CFAbsoluteTime aTime = CFGregorianDateGetAbsoluteTime(gDate, NULL);
return [NSDate dateWithTimeIntervalSinceReferenceDate:aTime];
}
static NSData* RawToData(const CSSM_DATA *data)
{
if(data == NULL)
{
return nil;
}
return [NSData dataWithBytes:data->Data length:data->Length];
}
static NSDictionary* X509NameToDictionary(const CSSM_X509_NAME *x509Name)
{
if(x509Name == NULL)
{
return nil;
}
NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:6];
NSMutableArray *others = [NSMutableArray arrayWithCapacity:6];
UInt32 i, j;
for(i = 0; i < x509Name->numberOfRDNs; i++)
{
const CSSM_X509_RDN *name = &x509Name->RelativeDistinguishedName[i];
for(j = 0; j < name->numberOfPairs; j++)
{
const CSSM_X509_TYPE_VALUE_PAIR *pair = &name->AttributeTypeAndValue[j];
NSString *value = DataToString(&pair->value, &pair->valueType);
if(value)
{
NSString *key = KeyForOid(&pair->type);
if(key)
[result setObject:value forKey:key];
else
[others addObject:value];
}
}
}
if([others count] > 0)
{
[result setObject:others forKey:X509_OTHERS];
}
return result;
}
static void AddCSSMField(const CSSM_FIELD *field, NSMutableDictionary *dict)
{
const CSSM_DATA *fieldData = &field->FieldValue;
const CSSM_OID *fieldOid = &field->FieldOid;
if(CompareOids(fieldOid, &CSSMOID_X509V1SerialNumber))
{
NSData *data = RawToData(fieldData);
if(data)
{
[dict setObject:data forKey:X509_SERIAL_NUMBER];
}
}
else if(CompareOids(fieldOid, &CSSMOID_X509V1IssuerNameCStruct))
{
CSSM_X509_NAME_PTR issuer = (CSSM_X509_NAME_PTR)fieldData->Data;
if(issuer && fieldData->Length == sizeof(CSSM_X509_NAME))
{
NSDictionary *issuerDict = X509NameToDictionary(issuer);
if(issuerDict)
{
[dict setObject:issuerDict forKey:X509_ISSUER];
}
}
}
else if(CompareOids(fieldOid, &CSSMOID_X509V1SubjectNameCStruct))
{
CSSM_X509_NAME_PTR subject = (CSSM_X509_NAME_PTR)fieldData->Data;
if(subject && fieldData->Length == sizeof(CSSM_X509_NAME))
{
NSDictionary *subjectDict = X509NameToDictionary(subject);
if(subjectDict)
{
[dict setObject:subjectDict forKey:X509_SUBJECT];
}
}
}
else if(CompareOids(fieldOid, &CSSMOID_X509V1ValidityNotBefore))
{
CSSM_X509_TIME_PTR time = (CSSM_X509_TIME_PTR)fieldData->Data;
if(time && fieldData->Length == sizeof(CSSM_X509_TIME))
{
NSDate *date = TimeToDate((const char *)time->time.Data, time->time.Length);
if(date)
{
[dict setObject:date forKey:X509_NOT_VALID_BEFORE];
}
}
}
else if(CompareOids(fieldOid, &CSSMOID_X509V1ValidityNotAfter))
{
CSSM_X509_TIME_PTR time = (CSSM_X509_TIME_PTR)fieldData->Data;
if(time && fieldData->Length == sizeof(CSSM_X509_TIME))
{
NSDate *date = TimeToDate((const char *)time->time.Data, time->time.Length);
if(date)
{
[dict setObject:date forKey:X509_NOT_VALID_AFTER];
}
}
}
else if(CompareOids(fieldOid, &CSSMOID_X509V1SubjectPublicKeyCStruct))
{
CSSM_X509_SUBJECT_PUBLIC_KEY_INFO_PTR pubKeyInfo = (CSSM_X509_SUBJECT_PUBLIC_KEY_INFO_PTR)fieldData->Data;
if(pubKeyInfo && fieldData->Length == sizeof(CSSM_X509_SUBJECT_PUBLIC_KEY_INFO))
{
NSData *data = RawToData(&pubKeyInfo->subjectPublicKey);
if(data)
{
[dict setObject:data forKey:X509_PUBLIC_KEY];
}
}
}
}
+ (NSDictionary *)extractCertDictFromAsyncSocket:(AsyncSocket *)socket
{
if(socket == nil)
{
return nil;
}
return [self extractCertDictFromReadStream:[socket getCFReadStream]];
}
+ (NSDictionary *)extractCertDictFromReadStream:(CFReadStreamRef)readStream
{
if(readStream == NULL)
{
return nil;
}
NSDictionary *result = nil;
CFArrayRef certs = CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates);
if(certs && CFArrayGetCount(certs) > 0)
{
// The first cert in the chain is the subject cert
SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(certs, 0);
result = [self extractCertDictFromCert:cert];
}
if(certs) CFRelease(certs);
return result;
}
+ (NSDictionary *)extractCertDictFromIdentity:(SecIdentityRef)identity
{
if(identity == NULL)
{
return nil;
}
NSDictionary *result = nil;
SecCertificateRef cert = NULL;
OSStatus err = SecIdentityCopyCertificate(identity, &cert);
if(err)
{
cssmPerror("SecIdentityCopyCertificate", err);
return nil;
}
else
{
result = [self extractCertDictFromCert:cert];
}
if(cert) CFRelease(cert);
return result;
}
+ (NSDictionary *)extractCertDictFromCert:(SecCertificateRef)cert
{
CSSM_CL_HANDLE clHandle = CLStartup();
if(clHandle == 0)
{
return nil;
}
NSMutableDictionary *result = nil;
CSSM_DATA certData;
if(SecCertificateGetData(cert, &certData) == noErr)
{
uint32 i;
uint32 numFields;
CSSM_FIELD_PTR fieldPtr;
CSSM_RETURN crtn = CSSM_CL_CertGetAllFields(clHandle, &certData, &numFields, &fieldPtr);
if(crtn == CSSM_OK)
{
result = [NSMutableDictionary dictionaryWithCapacity:6];
for(i = 0; i < numFields; i++)
{
AddCSSMField(&fieldPtr[i], result);
}
CSSM_CL_FreeFields(clHandle, numFields, &fieldPtr);
}
}
CLShutdown(clHandle);
return result;
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/CertTest/X509Certificate.m
|
Objective-C
|
oos
| 12,902
|
#import <Cocoa/Cocoa.h>
@class AsyncSocket;
@interface AppController : NSObject
{
AsyncSocket *asyncSocket;
}
- (IBAction)printCert:(id)sender;
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/CertTest/AppController.h
|
Objective-C
|
oos
| 152
|
//
// X509Certificate.h
//
// This class is in the public domain.
// Originally created by Robbie Hanson on Mon Jan 26 2009.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
// This class is largely derived from Apple's sample code project: SSLSample.
// This class does not extract every bit of available information, just the most common fields.
#import <Foundation/Foundation.h>
@class AsyncSocket;
// Top Level Keys
#define X509_ISSUER @"Issuer"
#define X509_SUBJECT @"Subject"
#define X509_NOT_VALID_BEFORE @"NotValidBefore"
#define X509_NOT_VALID_AFTER @"NotValidAfter"
#define X509_PUBLIC_KEY @"PublicKey"
#define X509_SERIAL_NUMBER @"SerialNumber"
// Keys For Issuer/Subject Dictionaries
#define X509_COUNTRY @"Country"
#define X509_ORGANIZATION @"Organization"
#define X509_LOCALITY @"Locality"
#define X509_ORANIZATIONAL_UNIT @"OrganizationalUnit"
#define X509_COMMON_NAME @"CommonName"
#define X509_SURNAME @"Surname"
#define X509_TITLE @"Title"
#define X509_STATE_PROVINCE @"StateProvince"
#define X509_COLLECTIVE_STATE_PROVINCE @"CollectiveStateProvince"
#define X509_EMAIL_ADDRESS @"EmailAddress"
#define X509_STREET_ADDRESS @"StreetAddress"
#define X509_POSTAL_CODE @"PostalCode"
#define X509_OTHERS @"Others"
@interface X509Certificate : NSObject
+ (NSDictionary *)extractCertDictFromAsyncSocket:(AsyncSocket *)socket;
+ (NSDictionary *)extractCertDictFromReadStream:(CFReadStreamRef)readStream;
+ (NSDictionary *)extractCertDictFromIdentity:(SecIdentityRef)identity;
+ (NSDictionary *)extractCertDictFromCert:(SecCertificateRef)cert;
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/CertTest/X509Certificate.h
|
Objective-C
|
oos
| 1,931
|
#import "AppController.h"
#import "AsyncSocket.h"
#import "X509Certificate.h"
@implementation AppController
- (id)init
{
if(self = [super init])
{
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
}
return self;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(@"Ready");
NSError *err = nil;
if(![asyncSocket connectToHost:@"www.paypal.com" onPort:443 error:&err])
{
NSLog(@"Error: %@", err);
}
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"onSocket:%p didConnectToHost:%@ port:%hu", sock, host, port);
// Configure SSL/TLS settings
NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];
// If you simply want to ensure that the remote host's certificate is valid,
// then you can use an empty dictionary.
// If you know the name of the remote host, then you should specify the name here.
//
// NOTE:
// You should understand the security implications if you do not specify the peer name.
// Please see the documentation for the startTLS method in AsyncSocket.h for a full discussion.
[settings setObject:@"www.paypal.com"
forKey:(NSString *)kCFStreamSSLPeerName];
// To connect to a test server, with a self-signed certificate, use settings similar to this:
// // Allow expired certificates
// [settings setObject:[NSNumber numberWithBool:YES]
// forKey:(NSString *)kCFStreamSSLAllowsExpiredCertificates];
//
// // Allow self-signed certificates
// [settings setObject:[NSNumber numberWithBool:YES]
// forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
//
// // In fact, don't even validate the certificate chain
// [settings setObject:[NSNumber numberWithBool:NO]
// forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
[sock startTLS:settings];
// You can also pass nil to the startTLS method, which is the same as passing an empty dictionary.
// Again, you should understand the security implications of doing so.
// Please see the documentation for the startTLS method in AsyncSocket.h for a full discussion.
}
- (void)onSocketDidSecure:(AsyncSocket *)sock
{
NSLog(@"onSocketDidSecure:%p", sock);
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"onSocket:%p willDisconnectWithError:%@", sock, err);
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"onSocketDidDisconnect:%p", sock);
}
- (IBAction)printCert:(id)sender
{
NSDictionary *cert = [X509Certificate extractCertDictFromAsyncSocket:asyncSocket];
NSLog(@"X509 Certificate: \n%@", cert);
}
@end
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/CertTest/AppController.m
|
Objective-C
|
oos
| 2,649
|
//
// main.m
// CertTest
//
// Created by Robbie Hanson on 1/26/09.
// Copyright Deusty Designs, LLC. 2009. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
zzymoon-cocoaasyncsocket
|
RunLoop/Xcode/CertTest/main.m
|
Objective-C
|
oos
| 258
|
//
// GCDAsyncSocket.m
//
// This class is in the public domain.
// Originally created by Robbie Hanson in Q4 2010.
// Updated and maintained by Deusty LLC and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import "GCDAsyncSocket.h"
#if TARGET_OS_IPHONE
#import <CFNetwork/CFNetwork.h>
#endif
#import <arpa/inet.h>
#import <fcntl.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <netinet/in.h>
#import <net/if.h>
#import <sys/socket.h>
#import <sys/types.h>
#import <sys/ioctl.h>
#import <sys/poll.h>
#import <sys/uio.h>
#import <unistd.h>
#if 0
// Logging Enabled - See log level below
// Logging uses the CocoaLumberjack framework (which is also GCD based).
// http://code.google.com/p/cocoalumberjack/
//
// It allows us to do a lot of logging without significantly slowing down the code.
#import "DDLog.h"
#define LogAsync YES
#define LogContext 65535
#define LogObjc(flg, frmt, ...) LOG_OBJC_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
#define LogC(flg, frmt, ...) LOG_C_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
#define LogError(frmt, ...) LogObjc(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogWarn(frmt, ...) LogObjc(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogInfo(frmt, ...) LogObjc(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogVerbose(frmt, ...) LogObjc(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCError(frmt, ...) LogC(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCWarn(frmt, ...) LogC(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCInfo(frmt, ...) LogC(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCVerbose(frmt, ...) LogC(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogTrace() LogObjc(LOG_FLAG_VERBOSE, @"%@: %@", THIS_FILE, THIS_METHOD)
#define LogCTrace() LogC(LOG_FLAG_VERBOSE, @"%@: %s", THIS_FILE, __FUNCTION__)
// Log levels : off, error, warn, info, verbose
static const int logLevel = LOG_LEVEL_VERBOSE;
#else
// Logging Disabled
#define LogError(frmt, ...) {}
#define LogWarn(frmt, ...) {}
#define LogInfo(frmt, ...) {}
#define LogVerbose(frmt, ...) {}
#define LogCError(frmt, ...) {}
#define LogCWarn(frmt, ...) {}
#define LogCInfo(frmt, ...) {}
#define LogCVerbose(frmt, ...) {}
#define LogTrace() {}
#define LogCTrace(frmt, ...) {}
#endif
/**
* Seeing a return statements within an inner block
* can sometimes be mistaken for a return point of the enclosing method.
* This makes inline blocks a bit easier to read.
**/
#define return_from_block return
/**
* A socket file descriptor is really just an integer.
* It represents the index of the socket within the kernel.
* This makes invalid file descriptor comparisons easier to read.
**/
#define SOCKET_NULL -1
NSString *const GCDAsyncSocketException = @"GCDAsyncSocketException";
NSString *const GCDAsyncSocketErrorDomain = @"GCDAsyncSocketErrorDomain";
#if !TARGET_OS_IPHONE
NSString *const GCDAsyncSocketSSLCipherSuites = @"GCDAsyncSocketSSLCipherSuites";
NSString *const GCDAsyncSocketSSLDiffieHellmanParameters = @"GCDAsyncSocketSSLDiffieHellmanParameters";
#endif
enum GCDAsyncSocketFlags
{
kSocketStarted = 1 << 0, // If set, socket has been started (accepting/connecting)
kConnected = 1 << 1, // If set, the socket is connected
kForbidReadsWrites = 1 << 2, // If set, no new reads or writes are allowed
kReadsPaused = 1 << 3, // If set, reads are paused due to possible timeout
kWritesPaused = 1 << 4, // If set, writes are paused due to possible timeout
kDisconnectAfterReads = 1 << 5, // If set, disconnect after no more reads are queued
kDisconnectAfterWrites = 1 << 6, // If set, disconnect after no more writes are queued
kSocketCanAcceptBytes = 1 << 7, // If set, we know socket can accept bytes. If unset, it's unknown.
kReadSourceSuspended = 1 << 8, // If set, the read source is suspended
kWriteSourceSuspended = 1 << 9, // If set, the write source is suspended
kQueuedTLS = 1 << 10, // If set, we've queued an upgrade to TLS
kStartingReadTLS = 1 << 11, // If set, we're waiting for TLS negotiation to complete
kStartingWriteTLS = 1 << 12, // If set, we're waiting for TLS negotiation to complete
kSocketSecure = 1 << 13, // If set, socket is using secure communication via SSL/TLS
kSocketHasReadEOF = 1 << 14, // If set, we have read EOF from socket
kReadStreamClosed = 1 << 15, // If set, we've read EOF plus prebuffer has been drained
#if TARGET_OS_IPHONE
kAddedStreamListener = 1 << 16, // If set, CFStreams have been added to listener thread
kSecureSocketHasBytesAvailable = 1 << 17, // If set, CFReadStream has notified us of bytes available
#endif
};
enum GCDAsyncSocketConfig
{
kIPv4Disabled = 1 << 0, // If set, IPv4 is disabled
kIPv6Disabled = 1 << 1, // If set, IPv6 is disabled
kPreferIPv6 = 1 << 2, // If set, IPv6 is preferred over IPv4
kAllowHalfDuplexConnection = 1 << 3, // If set, the socket will stay open even if the read stream closes
};
#if TARGET_OS_IPHONE
static NSThread *listenerThread; // Used for CFStreams
#endif
@interface GCDAsyncSocket (Private)
// Accepting
- (BOOL)doAccept:(int)socketFD;
// Connecting
- (void)startConnectTimeout:(NSTimeInterval)timeout;
- (void)endConnectTimeout;
- (void)doConnectTimeout;
- (void)lookup:(int)aConnectIndex host:(NSString *)host port:(uint16_t)port;
- (void)lookup:(int)aConnectIndex didSucceedWithAddress4:(NSData *)address4 address6:(NSData *)address6;
- (void)lookup:(int)aConnectIndex didFail:(NSError *)error;
- (BOOL)connectWithAddress4:(NSData *)address4 address6:(NSData *)address6 error:(NSError **)errPtr;
- (void)didConnect:(int)aConnectIndex;
- (void)didNotConnect:(int)aConnectIndex error:(NSError *)error;
// Disconnect
- (void)closeWithError:(NSError *)error;
- (void)close;
- (void)maybeClose;
// Errors
- (NSError *)badConfigError:(NSString *)msg;
- (NSError *)badParamError:(NSString *)msg;
- (NSError *)gaiError:(int)gai_error;
- (NSError *)errnoError;
- (NSError *)errnoErrorWithReason:(NSString *)reason;
- (NSError *)connectTimeoutError;
- (NSError *)otherError:(NSString *)msg;
// Diagnostics
- (NSString *)connectedHost4;
- (NSString *)connectedHost6;
- (uint16_t)connectedPort4;
- (uint16_t)connectedPort6;
- (NSString *)localHost4;
- (NSString *)localHost6;
- (uint16_t)localPort4;
- (uint16_t)localPort6;
- (NSString *)connectedHostFromSocket4:(int)socketFD;
- (NSString *)connectedHostFromSocket6:(int)socketFD;
- (uint16_t)connectedPortFromSocket4:(int)socketFD;
- (uint16_t)connectedPortFromSocket6:(int)socketFD;
- (NSString *)localHostFromSocket4:(int)socketFD;
- (NSString *)localHostFromSocket6:(int)socketFD;
- (uint16_t)localPortFromSocket4:(int)socketFD;
- (uint16_t)localPortFromSocket6:(int)socketFD;
// Utilities
- (void)getInterfaceAddress4:(NSMutableData **)addr4Ptr
address6:(NSMutableData **)addr6Ptr
fromDescription:(NSString *)interfaceDescription
port:(uint16_t)port;
- (void)setupReadAndWriteSourcesForNewlyConnectedSocket:(int)socketFD;
- (void)suspendReadSource;
- (void)resumeReadSource;
- (void)suspendWriteSource;
- (void)resumeWriteSource;
// Reading
- (void)maybeDequeueRead;
- (void)flushSSLBuffers;
- (void)doReadData;
- (void)doReadEOF;
- (void)completeCurrentRead;
- (void)endCurrentRead;
- (void)setupReadTimerWithTimeout:(NSTimeInterval)timeout;
- (void)doReadTimeout;
- (void)doReadTimeoutWithExtension:(NSTimeInterval)timeoutExtension;
// Writing
- (void)maybeDequeueWrite;
- (void)doWriteData;
- (void)completeCurrentWrite;
- (void)endCurrentWrite;
- (void)setupWriteTimerWithTimeout:(NSTimeInterval)timeout;
- (void)doWriteTimeout;
- (void)doWriteTimeoutWithExtension:(NSTimeInterval)timeoutExtension;
// Security
- (void)maybeStartTLS;
#if !TARGET_OS_IPHONE
- (void)continueSSLHandshake;
#endif
// CFStream
#if TARGET_OS_IPHONE
+ (void)startListenerThreadIfNeeded;
- (BOOL)createReadAndWriteStream;
- (BOOL)registerForStreamCallbacksIncludingReadWrite:(BOOL)includeReadWrite;
- (BOOL)addStreamsToRunLoop;
- (BOOL)openStreams;
- (void)removeStreamsFromRunLoop;
#endif
// Class Methods
+ (NSString *)hostFromAddress4:(const struct sockaddr_in *)pSockaddr4;
+ (NSString *)hostFromAddress6:(const struct sockaddr_in6 *)pSockaddr6;
+ (uint16_t)portFromAddress4:(const struct sockaddr_in *)pSockaddr4;
+ (uint16_t)portFromAddress6:(const struct sockaddr_in6 *)pSockaddr6;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The GCDAsyncReadPacket encompasses the instructions for any given read.
* The content of a read packet allows the code to determine if we're:
* - reading to a certain length
* - reading to a certain separator
* - or simply reading the first chunk of available data
**/
@interface GCDAsyncReadPacket : NSObject
{
@public
NSMutableData *buffer;
NSUInteger startOffset;
NSUInteger bytesDone;
NSUInteger maxLength;
NSTimeInterval timeout;
NSUInteger readLength;
NSData *term;
BOOL bufferOwner;
NSUInteger originalBufferLength;
long tag;
}
- (id)initWithData:(NSMutableData *)d
startOffset:(NSUInteger)s
maxLength:(NSUInteger)m
timeout:(NSTimeInterval)t
readLength:(NSUInteger)l
terminator:(NSData *)e
tag:(long)i;
- (void)ensureCapacityForAdditionalDataOfLength:(NSUInteger)bytesToRead;
- (NSUInteger)optimalReadLengthWithDefault:(NSUInteger)defaultValue shouldPreBuffer:(BOOL *)shouldPreBufferPtr;
- (NSUInteger)readLengthForNonTermWithHint:(NSUInteger)bytesAvailable;
- (NSUInteger)readLengthForTermWithHint:(NSUInteger)bytesAvailable shouldPreBuffer:(BOOL *)shouldPreBufferPtr;
- (NSUInteger)readLengthForTermWithPreBuffer:(NSData *)preBuffer found:(BOOL *)foundPtr;
- (NSInteger)searchForTermAfterPreBuffering:(ssize_t)numBytes;
@end
@implementation GCDAsyncReadPacket
- (id)initWithData:(NSMutableData *)d
startOffset:(NSUInteger)s
maxLength:(NSUInteger)m
timeout:(NSTimeInterval)t
readLength:(NSUInteger)l
terminator:(NSData *)e
tag:(long)i
{
if((self = [super init]))
{
bytesDone = 0;
maxLength = m;
timeout = t;
readLength = l;
term = [e copy];
tag = i;
if (d)
{
buffer = [d retain];
startOffset = s;
bufferOwner = NO;
originalBufferLength = [d length];
}
else
{
if (readLength > 0)
buffer = [[NSMutableData alloc] initWithLength:readLength];
else
buffer = [[NSMutableData alloc] initWithLength:0];
startOffset = 0;
bufferOwner = YES;
originalBufferLength = 0;
}
}
return self;
}
/**
* Increases the length of the buffer (if needed) to ensure a read of the given size will fit.
**/
- (void)ensureCapacityForAdditionalDataOfLength:(NSUInteger)bytesToRead
{
NSUInteger buffSize = [buffer length];
NSUInteger buffUsed = startOffset + bytesDone;
NSUInteger buffSpace = buffSize - buffUsed;
if (bytesToRead > buffSpace)
{
NSUInteger buffInc = bytesToRead - buffSpace;
[buffer increaseLengthBy:buffInc];
}
}
/**
* This method is used when we do NOT know how much data is available to be read from the socket.
* This method returns the default value unless it exceeds the specified readLength or maxLength.
*
* Furthermore, the shouldPreBuffer decision is based upon the packet type,
* and whether the returned value would fit in the current buffer without requiring a resize of the buffer.
**/
- (NSUInteger)optimalReadLengthWithDefault:(NSUInteger)defaultValue shouldPreBuffer:(BOOL *)shouldPreBufferPtr
{
NSUInteger result;
if (readLength > 0)
{
// Read a specific length of data
result = MIN(defaultValue, (readLength - bytesDone));
// There is no need to prebuffer since we know exactly how much data we need to read.
// Even if the buffer isn't currently big enough to fit this amount of data,
// it would have to be resized eventually anyway.
if (shouldPreBufferPtr)
*shouldPreBufferPtr = NO;
}
else
{
// Either reading until we find a specified terminator,
// or we're simply reading all available data.
//
// In other words, one of:
//
// - readDataToData packet
// - readDataWithTimeout packet
if (maxLength > 0)
result = MIN(defaultValue, (maxLength - bytesDone));
else
result = defaultValue;
// Since we don't know the size of the read in advance,
// the shouldPreBuffer decision is based upon whether the returned value would fit
// in the current buffer without requiring a resize of the buffer.
//
// This is because, in all likelyhood, the amount read from the socket will be less than the default value.
// Thus we should avoid over-allocating the read buffer when we can simply use the pre-buffer instead.
if (shouldPreBufferPtr)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffUsed = startOffset + bytesDone;
NSUInteger buffSpace = buffSize - buffUsed;
if (buffSpace >= result)
*shouldPreBufferPtr = NO;
else
*shouldPreBufferPtr = YES;
}
}
return result;
}
/**
* For read packets without a set terminator, returns the amount of data
* that can be read without exceeding the readLength or maxLength.
*
* The given parameter indicates the number of bytes estimated to be available on the socket,
* which is taken into consideration during the calculation.
*
* The given hint MUST be greater than zero.
**/
- (NSUInteger)readLengthForNonTermWithHint:(NSUInteger)bytesAvailable
{
NSAssert(term == nil, @"This method does not apply to term reads");
NSAssert(bytesAvailable > 0, @"Invalid parameter: bytesAvailable");
if (readLength > 0)
{
// Read a specific length of data
return MIN(bytesAvailable, (readLength - bytesDone));
// No need to avoid resizing the buffer.
// If the user provided their own buffer,
// and told us to read a certain length of data that exceeds the size of the buffer,
// then it is clear that our code will resize the buffer during the read operation.
//
// This method does not actually do any resizing.
// The resizing will happen elsewhere if needed.
}
else
{
// Read all available data
NSUInteger result = bytesAvailable;
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
// No need to avoid resizing the buffer.
// If the user provided their own buffer,
// and told us to read all available data without giving us a maxLength,
// then it is clear that our code might resize the buffer during the read operation.
//
// This method does not actually do any resizing.
// The resizing will happen elsewhere if needed.
return result;
}
}
/**
* For read packets with a set terminator, returns the amount of data
* that can be read without exceeding the maxLength.
*
* The given parameter indicates the number of bytes estimated to be available on the socket,
* which is taken into consideration during the calculation.
*
* To optimize memory allocations, mem copies, and mem moves
* the shouldPreBuffer boolean value will indicate if the data should be read into a prebuffer first,
* or if the data can be read directly into the read packet's buffer.
**/
- (NSUInteger)readLengthForTermWithHint:(NSUInteger)bytesAvailable shouldPreBuffer:(BOOL *)shouldPreBufferPtr
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSAssert(bytesAvailable > 0, @"Invalid parameter: bytesAvailable");
NSUInteger result = bytesAvailable;
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
// Should the data be read into the read packet's buffer, or into a pre-buffer first?
//
// One would imagine the preferred option is the faster one.
// So which one is faster?
//
// Reading directly into the packet's buffer requires:
// 1. Possibly resizing packet buffer (malloc/realloc)
// 2. Filling buffer (read)
// 3. Searching for term (memcmp)
// 4. Possibly copying overflow into prebuffer (malloc/realloc, memcpy)
//
// Reading into prebuffer first:
// 1. Possibly resizing prebuffer (malloc/realloc)
// 2. Filling buffer (read)
// 3. Searching for term (memcmp)
// 4. Copying underflow into packet buffer (malloc/realloc, memcpy)
// 5. Removing underflow from prebuffer (memmove)
//
// Comparing the performance of the two we can see that reading
// data into the prebuffer first is slower due to the extra memove.
//
// However:
// The implementation of NSMutableData is open source via core foundation's CFMutableData.
// Decreasing the length of a mutable data object doesn't cause a realloc.
// In other words, the capacity of a mutable data object can grow, but doesn't shrink.
//
// This means the prebuffer will rarely need a realloc.
// The packet buffer, on the other hand, may often need a realloc.
// This is especially true if we are the buffer owner.
// Furthermore, if we are constantly realloc'ing the packet buffer,
// and then moving the overflow into the prebuffer,
// then we're consistently over-allocating memory for each term read.
// And now we get into a bit of a tradeoff between speed and memory utilization.
//
// The end result is that the two perform very similarly.
// And we can answer the original question very simply by another means.
//
// If we can read all the data directly into the packet's buffer without resizing it first,
// then we do so. Otherwise we use the prebuffer.
if (shouldPreBufferPtr)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffUsed = startOffset + bytesDone;
if ((buffSize - buffUsed) >= result)
*shouldPreBufferPtr = NO;
else
*shouldPreBufferPtr = YES;
}
return result;
}
/**
* For read packets with a set terminator,
* returns the amount of data that can be read from the given preBuffer,
* without going over a terminator or the maxLength.
*
* It is assumed the terminator has not already been read.
**/
- (NSUInteger)readLengthForTermWithPreBuffer:(NSData *)preBuffer found:(BOOL *)foundPtr
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSAssert([preBuffer length] > 0, @"Invoked with empty pre buffer!");
// We know that the terminator, as a whole, doesn't exist in our own buffer.
// But it is possible that a portion of it exists in our buffer.
// So we're going to look for the terminator starting with a portion of our own buffer.
//
// Example:
//
// term length = 3 bytes
// bytesDone = 5 bytes
// preBuffer length = 5 bytes
//
// If we append the preBuffer to our buffer,
// it would look like this:
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------------------
//
// So we start our search here:
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// -------^-^-^---------
//
// And move forwards...
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------^-^-^-------
//
// Until we find the terminator or reach the end.
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------------^-^-^-
BOOL found = NO;
NSUInteger termLength = [term length];
NSUInteger preBufferLength = [preBuffer length];
if ((bytesDone + preBufferLength) < termLength)
{
// Not enough data for a full term sequence yet
return preBufferLength;
}
NSUInteger maxPreBufferLength;
if (maxLength > 0) {
maxPreBufferLength = MIN(preBufferLength, (maxLength - bytesDone));
// Note: maxLength >= termLength
}
else {
maxPreBufferLength = preBufferLength;
}
uint8_t seq[termLength];
const void *termBuf = [term bytes];
NSUInteger bufLen = MIN(bytesDone, (termLength - 1));
uint8_t *buf = (uint8_t *)[buffer mutableBytes] + startOffset + bytesDone - bufLen;
NSUInteger preLen = termLength - bufLen;
const uint8_t *pre = [preBuffer bytes];
NSUInteger loopCount = bufLen + maxPreBufferLength - termLength + 1; // Plus one. See example above.
NSUInteger result = preBufferLength;
NSUInteger i;
for (i = 0; i < loopCount; i++)
{
if (bufLen > 0)
{
// Combining bytes from buffer and preBuffer
memcpy(seq, buf, bufLen);
memcpy(seq + bufLen, pre, preLen);
if (memcmp(seq, termBuf, termLength) == 0)
{
result = preLen;
found = YES;
break;
}
buf++;
bufLen--;
preLen++;
}
else
{
// Comparing directly from preBuffer
if (memcmp(pre, termBuf, termLength) == 0)
{
NSUInteger preOffset = pre - (const uint8_t *)[preBuffer bytes]; // pointer arithmetic
result = preOffset + termLength;
found = YES;
break;
}
pre++;
}
}
// There is no need to avoid resizing the buffer in this particular situation.
if (foundPtr) *foundPtr = found;
return result;
}
/**
* For read packets with a set terminator, scans the packet buffer for the term.
* It is assumed the terminator had not been fully read prior to the new bytes.
*
* If the term is found, the number of excess bytes after the term are returned.
* If the term is not found, this method will return -1.
*
* Note: A return value of zero means the term was found at the very end.
*
* Prerequisites:
* The given number of bytes have been added to the end of our buffer.
* Our bytesDone variable has NOT been changed due to the prebuffered bytes.
**/
- (NSInteger)searchForTermAfterPreBuffering:(ssize_t)numBytes
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
// The implementation of this method is very similar to the above method.
// See the above method for a discussion of the algorithm used here.
uint8_t *buff = [buffer mutableBytes];
NSUInteger buffLength = bytesDone + numBytes;
const void *termBuff = [term bytes];
NSUInteger termLength = [term length];
// Note: We are dealing with unsigned integers,
// so make sure the math doesn't go below zero.
NSUInteger i = ((buffLength - numBytes) >= termLength) ? (buffLength - numBytes - termLength + 1) : 0;
while (i + termLength <= buffLength)
{
uint8_t *subBuffer = buff + startOffset + i;
if (memcmp(subBuffer, termBuff, termLength) == 0)
{
return buffLength - (i + termLength);
}
i++;
}
return -1;
}
- (void)dealloc
{
[buffer release];
[term release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The GCDAsyncWritePacket encompasses the instructions for any given write.
**/
@interface GCDAsyncWritePacket : NSObject
{
@public
NSData *buffer;
NSUInteger bytesDone;
long tag;
NSTimeInterval timeout;
}
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation GCDAsyncWritePacket
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
{
if((self = [super init]))
{
buffer = [d retain];
bytesDone = 0;
timeout = t;
tag = i;
}
return self;
}
- (void)dealloc
{
[buffer release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The GCDAsyncSpecialPacket encompasses special instructions for interruptions in the read/write queues.
* This class my be altered to support more than just TLS in the future.
**/
@interface GCDAsyncSpecialPacket : NSObject
{
@public
NSDictionary *tlsSettings;
}
- (id)initWithTLSSettings:(NSDictionary *)settings;
@end
@implementation GCDAsyncSpecialPacket
- (id)initWithTLSSettings:(NSDictionary *)settings
{
if((self = [super init]))
{
tlsSettings = [settings copy];
}
return self;
}
- (void)dealloc
{
[tlsSettings release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation GCDAsyncSocket
- (id)init
{
return [self initWithDelegate:nil delegateQueue:NULL socketQueue:NULL];
}
- (id)initWithSocketQueue:(dispatch_queue_t)sq
{
return [self initWithDelegate:nil delegateQueue:NULL socketQueue:sq];
}
- (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq
{
return [self initWithDelegate:aDelegate delegateQueue:dq socketQueue:NULL];
}
- (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq
{
if((self = [super init]))
{
delegate = aDelegate;
if (dq)
{
dispatch_retain(dq);
delegateQueue = dq;
}
socket4FD = SOCKET_NULL;
socket6FD = SOCKET_NULL;
connectIndex = 0;
if (sq)
{
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
dispatch_retain(sq);
socketQueue = sq;
}
else
{
socketQueue = dispatch_queue_create("GCDAsyncSocket", NULL);
}
readQueue = [[NSMutableArray alloc] initWithCapacity:5];
currentRead = nil;
writeQueue = [[NSMutableArray alloc] initWithCapacity:5];
currentWrite = nil;
partialReadBuffer = [[NSMutableData alloc] init];
}
return self;
}
- (void)dealloc
{
LogInfo(@"%@ - %@ (start)", THIS_METHOD, self);
if (dispatch_get_current_queue() == socketQueue)
{
[self closeWithError:nil];
}
else
{
dispatch_sync(socketQueue, ^{
[self closeWithError:nil];
});
}
delegate = nil;
if (delegateQueue)
dispatch_release(delegateQueue);
delegateQueue = NULL;
dispatch_release(socketQueue);
socketQueue = NULL;
[readQueue release];
[writeQueue release];
[partialReadBuffer release];
#if !TARGET_OS_IPHONE
[sslReadBuffer release];
#endif
[userData release];
LogInfo(@"%@ - %@ (finish)", THIS_METHOD, self);
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (id)delegate
{
if (dispatch_get_current_queue() == socketQueue)
{
return delegate;
}
else
{
__block id result;
dispatch_sync(socketQueue, ^{
result = delegate;
});
return result;
}
}
- (void)setDelegate:(id)newDelegate synchronously:(BOOL)synchronously
{
dispatch_block_t block = ^{
delegate = newDelegate;
};
if (dispatch_get_current_queue() == socketQueue) {
block();
}
else {
if (synchronously)
dispatch_sync(socketQueue, block);
else
dispatch_async(socketQueue, block);
}
}
- (void)setDelegate:(id)newDelegate
{
[self setDelegate:newDelegate synchronously:NO];
}
- (void)synchronouslySetDelegate:(id)newDelegate
{
[self setDelegate:newDelegate synchronously:YES];
}
- (dispatch_queue_t)delegateQueue
{
if (dispatch_get_current_queue() == socketQueue)
{
return delegateQueue;
}
else
{
__block dispatch_queue_t result;
dispatch_sync(socketQueue, ^{
result = delegateQueue;
});
return result;
}
}
- (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
{
dispatch_block_t block = ^{
if (delegateQueue)
dispatch_release(delegateQueue);
if (newDelegateQueue)
dispatch_retain(newDelegateQueue);
delegateQueue = newDelegateQueue;
};
if (dispatch_get_current_queue() == socketQueue) {
block();
}
else {
if (synchronously)
dispatch_sync(socketQueue, block);
else
dispatch_async(socketQueue, block);
}
}
- (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegateQueue:newDelegateQueue synchronously:NO];
}
- (void)synchronouslySetDelegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegateQueue:newDelegateQueue synchronously:YES];
}
- (void)getDelegate:(id *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr
{
if (dispatch_get_current_queue() == socketQueue)
{
if (delegatePtr) *delegatePtr = delegate;
if (delegateQueuePtr) *delegateQueuePtr = delegateQueue;
}
else
{
__block id dPtr = NULL;
__block dispatch_queue_t dqPtr = NULL;
dispatch_sync(socketQueue, ^{
dPtr = delegate;
dqPtr = delegateQueue;
});
if (delegatePtr) *delegatePtr = dPtr;
if (delegateQueuePtr) *delegateQueuePtr = dqPtr;
}
}
- (void)setDelegate:(id)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
{
dispatch_block_t block = ^{
delegate = newDelegate;
if (delegateQueue)
dispatch_release(delegateQueue);
if (newDelegateQueue)
dispatch_retain(newDelegateQueue);
delegateQueue = newDelegateQueue;
};
if (dispatch_get_current_queue() == socketQueue) {
block();
}
else {
if (synchronously)
dispatch_sync(socketQueue, block);
else
dispatch_async(socketQueue, block);
}
}
- (void)setDelegate:(id)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:NO];
}
- (void)synchronouslySetDelegate:(id)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:YES];
}
- (BOOL)autoDisconnectOnClosedReadStream
{
// Note: YES means kAllowHalfDuplexConnection is OFF
if (dispatch_get_current_queue() == socketQueue)
{
return ((config & kAllowHalfDuplexConnection) == 0);
}
else
{
__block BOOL result;
dispatch_sync(socketQueue, ^{
result = ((config & kAllowHalfDuplexConnection) == 0);
});
return result;
}
}
- (void)setAutoDisconnectOnClosedReadStream:(BOOL)flag
{
// Note: YES means kAllowHalfDuplexConnection is OFF
dispatch_block_t block = ^{
if (flag)
config &= ~kAllowHalfDuplexConnection;
else
config |= kAllowHalfDuplexConnection;
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_async(socketQueue, block);
}
- (BOOL)isIPv4Enabled
{
// Note: YES means kIPv4Disabled is OFF
if (dispatch_get_current_queue() == socketQueue)
{
return ((config & kIPv4Disabled) == 0);
}
else
{
__block BOOL result;
dispatch_sync(socketQueue, ^{
result = ((config & kIPv4Disabled) == 0);
});
return result;
}
}
- (void)setIPv4Enabled:(BOOL)flag
{
// Note: YES means kIPv4Disabled is OFF
dispatch_block_t block = ^{
if (flag)
config &= ~kIPv4Disabled;
else
config |= kIPv4Disabled;
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_async(socketQueue, block);
}
- (BOOL)isIPv6Enabled
{
// Note: YES means kIPv6Disabled is OFF
if (dispatch_get_current_queue() == socketQueue)
{
return ((config & kIPv6Disabled) == 0);
}
else
{
__block BOOL result;
dispatch_sync(socketQueue, ^{
result = ((config & kIPv6Disabled) == 0);
});
return result;
}
}
- (void)setIPv6Enabled:(BOOL)flag
{
// Note: YES means kIPv6Disabled is OFF
dispatch_block_t block = ^{
if (flag)
config &= ~kIPv6Disabled;
else
config |= kIPv6Disabled;
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_async(socketQueue, block);
}
- (BOOL)isIPv4PreferredOverIPv6
{
// Note: YES means kPreferIPv6 is OFF
if (dispatch_get_current_queue() == socketQueue)
{
return ((config & kPreferIPv6) == 0);
}
else
{
__block BOOL result;
dispatch_sync(socketQueue, ^{
result = ((config & kPreferIPv6) == 0);
});
return result;
}
}
- (void)setPreferIPv4OverIPv6:(BOOL)flag
{
// Note: YES means kPreferIPv6 is OFF
dispatch_block_t block = ^{
if (flag)
config &= ~kPreferIPv6;
else
config |= kPreferIPv6;
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_async(socketQueue, block);
}
- (id)userData
{
__block id result;
dispatch_block_t block = ^{
result = [userData retain];
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
return [result autorelease];
}
- (void)setUserData:(id)arbitraryUserData
{
dispatch_block_t block = ^{
if (userData != arbitraryUserData)
{
[userData release];
userData = [arbitraryUserData retain];
}
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_async(socketQueue, block);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accepting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr
{
return [self acceptOnInterface:nil port:port error:errPtr];
}
- (BOOL)acceptOnInterface:(NSString *)interface port:(uint16_t)port error:(NSError **)errPtr
{
LogTrace();
__block BOOL result = NO;
__block NSError *err = nil;
// CreateSocket Block
// This block will be invoked within the dispatch block below.
int(^createSocket)(int, NSData*) = ^int (int domain, NSData *interfaceAddr) {
int socketFD = socket(domain, SOCK_STREAM, 0);
if (socketFD == SOCKET_NULL)
{
NSString *reason = @"Error in socket() function";
err = [[self errnoErrorWithReason:reason] retain];
return SOCKET_NULL;
}
int status;
// Set socket options
status = fcntl(socketFD, F_SETFL, O_NONBLOCK);
if (status == -1)
{
NSString *reason = @"Error enabling non-blocking IO on socket (fcntl)";
err = [[self errnoErrorWithReason:reason] retain];
close(socketFD);
return SOCKET_NULL;
}
int reuseOn = 1;
status = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
if (status == -1)
{
NSString *reason = @"Error enabling address reuse (setsockopt)";
err = [[self errnoErrorWithReason:reason] retain];
close(socketFD);
return SOCKET_NULL;
}
// Bind socket
status = bind(socketFD, (const struct sockaddr *)[interfaceAddr bytes], (socklen_t)[interfaceAddr length]);
if (status == -1)
{
NSString *reason = @"Error in bind() function";
err = [[self errnoErrorWithReason:reason] retain];
close(socketFD);
return SOCKET_NULL;
}
// Listen
status = listen(socketFD, 1024);
if (status == -1)
{
NSString *reason = @"Error in listen() function";
err = [[self errnoErrorWithReason:reason] retain];
close(socketFD);
return SOCKET_NULL;
}
return socketFD;
};
// Create dispatch block and run on socketQueue
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (delegate == nil) // Must have delegate set
{
NSString *msg = @"Attempting to accept without a delegate. Set a delegate first.";
err = [[self badConfigError:msg] retain];
[pool drain];
return_from_block;
}
if (delegateQueue == NULL) // Must have delegate queue set
{
NSString *msg = @"Attempting to accept without a delegate queue. Set a delegate queue first.";
err = [[self badConfigError:msg] retain];
[pool drain];
return_from_block;
}
BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled
{
NSString *msg = @"Both IPv4 and IPv6 have been disabled. Must enable at least one protocol first.";
err = [[self badConfigError:msg] retain];
[pool drain];
return_from_block;
}
if (![self isDisconnected]) // Must be disconnected
{
NSString *msg = @"Attempting to accept while connected or accepting connections. Disconnect first.";
err = [[self badConfigError:msg] retain];
[pool drain];
return_from_block;
}
// Clear queues (spurious read/write requests post disconnect)
[readQueue removeAllObjects];
[writeQueue removeAllObjects];
// Resolve interface from description
NSMutableData *interface4 = nil;
NSMutableData *interface6 = nil;
[self getInterfaceAddress4:&interface4 address6:&interface6 fromDescription:interface port:port];
if ((interface4 == nil) && (interface6 == nil))
{
NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address.";
err = [[self badParamError:msg] retain];
[pool drain];
return_from_block;
}
if (isIPv4Disabled && (interface6 == nil))
{
NSString *msg = @"IPv4 has been disabled and specified interface doesn't support IPv6.";
err = [[self badParamError:msg] retain];
[pool drain];
return_from_block;
}
if (isIPv6Disabled && (interface4 == nil))
{
NSString *msg = @"IPv6 has been disabled and specified interface doesn't support IPv4.";
err = [[self badParamError:msg] retain];
[pool drain];
return_from_block;
}
BOOL enableIPv4 = !isIPv4Disabled && (interface4 != nil);
BOOL enableIPv6 = !isIPv6Disabled && (interface6 != nil);
// Create sockets, configure, bind, and listen
if (enableIPv4)
{
LogVerbose(@"Creating IPv4 socket");
socket4FD = createSocket(AF_INET, interface4);
if (socket4FD == SOCKET_NULL)
{
[pool drain];
return_from_block;
}
}
if (enableIPv6)
{
LogVerbose(@"Creating IPv6 socket");
if (enableIPv4 && (port == 0))
{
// No specific port was specified, so we allowed the OS to pick an available port for us.
// Now we need to make sure the IPv6 socket listens on the same port as the IPv4 socket.
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)[interface6 mutableBytes];
addr6->sin6_port = htons([self localPort4]);
}
socket6FD = createSocket(AF_INET6, interface6);
if (socket6FD == SOCKET_NULL)
{
if (socket4FD != SOCKET_NULL)
{
close(socket4FD);
}
[pool drain];
return_from_block;
}
}
// Create accept sources
if (enableIPv4)
{
accept4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socket4FD, 0, socketQueue);
int socketFD = socket4FD;
dispatch_source_t acceptSource = accept4Source;
dispatch_source_set_event_handler(accept4Source, ^{
NSAutoreleasePool *eventPool = [[NSAutoreleasePool alloc] init];
LogVerbose(@"event4Block");
unsigned long i = 0;
unsigned long numPendingConnections = dispatch_source_get_data(acceptSource);
LogVerbose(@"numPendingConnections: %lu", numPendingConnections);
while ([self doAccept:socketFD] && (++i < numPendingConnections));
[eventPool drain];
});
dispatch_source_set_cancel_handler(accept4Source, ^{
LogVerbose(@"dispatch_release(accept4Source)");
dispatch_release(acceptSource);
LogVerbose(@"close(socket4FD)");
close(socketFD);
});
LogVerbose(@"dispatch_resume(accept4Source)");
dispatch_resume(accept4Source);
}
if (enableIPv6)
{
accept6Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socket6FD, 0, socketQueue);
int socketFD = socket6FD;
dispatch_source_t acceptSource = accept6Source;
dispatch_source_set_event_handler(accept6Source, ^{
NSAutoreleasePool *eventPool = [[NSAutoreleasePool alloc] init];
LogVerbose(@"event6Block");
unsigned long i = 0;
unsigned long numPendingConnections = dispatch_source_get_data(acceptSource);
LogVerbose(@"numPendingConnections: %lu", numPendingConnections);
while ([self doAccept:socketFD] && (++i < numPendingConnections));
[eventPool drain];
});
dispatch_source_set_cancel_handler(accept6Source, ^{
LogVerbose(@"dispatch_release(accept6Source)");
dispatch_release(acceptSource);
LogVerbose(@"close(socket6FD)");
close(socketFD);
});
LogVerbose(@"dispatch_resume(accept6Source)");
dispatch_resume(accept6Source);
}
flags |= kSocketStarted;
result = YES;
[pool drain];
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
if (result == NO)
{
LogInfo(@"Error in accept: %@", err);
if (errPtr)
*errPtr = [err autorelease];
else
[err release];
}
return result;
}
- (BOOL)doAccept:(int)parentSocketFD
{
LogTrace();
BOOL isIPv4;
int childSocketFD;
NSData *childSocketAddress;
if (parentSocketFD == socket4FD)
{
isIPv4 = YES;
struct sockaddr_in addr;
socklen_t addrLen = sizeof(addr);
childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen);
if (childSocketFD == -1)
{
LogWarn(@"Accept failed with error: %@", [self errnoError]);
return NO;
}
childSocketAddress = [NSData dataWithBytes:&addr length:addrLen];
}
else // if (parentSocketFD == socket6FD)
{
isIPv4 = NO;
struct sockaddr_in6 addr;
socklen_t addrLen = sizeof(addr);
childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen);
if (childSocketFD == -1)
{
LogWarn(@"Accept failed with error: %@", [self errnoError]);
return NO;
}
childSocketAddress = [NSData dataWithBytes:&addr length:addrLen];
}
// Enable non-blocking IO on the socket
int result = fcntl(childSocketFD, F_SETFL, O_NONBLOCK);
if (result == -1)
{
LogWarn(@"Error enabling non-blocking IO on accepted socket (fcntl)");
return NO;
}
// Prevent SIGPIPE signals
int nosigpipe = 1;
setsockopt(childSocketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
// Notify delegate
if (delegateQueue)
{
id theDelegate = delegate;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *delegatePool = [[NSAutoreleasePool alloc] init];
// Query delegate for custom socket queue
dispatch_queue_t childSocketQueue = NULL;
if ([theDelegate respondsToSelector:@selector(newSocketQueueForConnectionFromAddress:onSocket:)])
{
childSocketQueue = [theDelegate newSocketQueueForConnectionFromAddress:childSocketAddress
onSocket:self];
}
// Create GCDAsyncSocket instance for accepted socket
GCDAsyncSocket *acceptedSocket = [[GCDAsyncSocket alloc] initWithDelegate:delegate
delegateQueue:delegateQueue
socketQueue:childSocketQueue];
if (isIPv4)
acceptedSocket->socket4FD = childSocketFD;
else
acceptedSocket->socket6FD = childSocketFD;
acceptedSocket->flags = (kSocketStarted | kConnected);
// Setup read and write sources for accepted socket
dispatch_async(acceptedSocket->socketQueue, ^{
NSAutoreleasePool *socketPool = [[NSAutoreleasePool alloc] init];
[acceptedSocket setupReadAndWriteSourcesForNewlyConnectedSocket:childSocketFD];
[socketPool drain];
});
// Notify delegate
if ([theDelegate respondsToSelector:@selector(socket:didAcceptNewSocket:)])
{
[theDelegate socket:self didAcceptNewSocket:acceptedSocket];
}
// Release the socket queue returned from the delegate (it was retained by acceptedSocket)
if (childSocketQueue)
dispatch_release(childSocketQueue);
// Release the accepted socket (it should have been retained by the delegate)
[acceptedSocket release];
[delegatePool drain];
});
}
return YES;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connecting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* This method runs through the various checks required prior to a connection attempt.
* It is shared between the connectToHost and connectToAddress methods.
*
**/
- (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr
{
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
if (delegate == nil) // Must have delegate set
{
if (errPtr)
{
NSString *msg = @"Attempting to connect without a delegate. Set a delegate first.";
*errPtr = [self badConfigError:msg];
}
return NO;
}
if (delegateQueue == NULL) // Must have delegate queue set
{
if (errPtr)
{
NSString *msg = @"Attempting to connect without a delegate queue. Set a delegate queue first.";
*errPtr = [self badConfigError:msg];
}
return NO;
}
if (![self isDisconnected]) // Must be disconnected
{
if (errPtr)
{
NSString *msg = @"Attempting to connect while connected or accepting connections. Disconnect first.";
*errPtr = [self badConfigError:msg];
}
return NO;
}
BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled
{
if (errPtr)
{
NSString *msg = @"Both IPv4 and IPv6 have been disabled. Must enable at least one protocol first.";
*errPtr = [self badConfigError:msg];
}
return NO;
}
if (interface)
{
NSMutableData *interface4 = nil;
NSMutableData *interface6 = nil;
[self getInterfaceAddress4:&interface4 address6:&interface6 fromDescription:interface port:0];
if ((interface4 == nil) && (interface6 == nil))
{
if (errPtr)
{
NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address.";
*errPtr = [self badParamError:msg];
}
return NO;
}
if (isIPv4Disabled && (interface6 == nil))
{
if (errPtr)
{
NSString *msg = @"IPv4 has been disabled and specified interface doesn't support IPv6.";
*errPtr = [self badParamError:msg];
}
return NO;
}
if (isIPv6Disabled && (interface4 == nil))
{
if (errPtr)
{
NSString *msg = @"IPv6 has been disabled and specified interface doesn't support IPv4.";
*errPtr = [self badParamError:msg];
}
return NO;
}
connectInterface4 = [interface4 retain];
connectInterface6 = [interface6 retain];
}
// Clear queues (spurious read/write requests post disconnect)
[readQueue removeAllObjects];
[writeQueue removeAllObjects];
return YES;
}
- (BOOL)connectToHost:(NSString*)host onPort:(uint16_t)port error:(NSError **)errPtr
{
return [self connectToHost:host onPort:port withTimeout:-1 error:errPtr];
}
- (BOOL)connectToHost:(NSString *)host
onPort:(uint16_t)port
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr
{
return [self connectToHost:host onPort:port viaInterface:nil withTimeout:timeout error:errPtr];
}
- (BOOL)connectToHost:(NSString *)host
onPort:(uint16_t)port
viaInterface:(NSString *)interface
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr
{
LogTrace();
__block BOOL result = NO;
__block NSError *err = nil;
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Check for problems with host parameter
if (host == nil)
{
NSString *msg = @"Invalid host parameter (nil). Should be a domain name or IP address string.";
err = [[self badParamError:msg] retain];
[pool drain];
return_from_block;
}
// Run through standard pre-connect checks
if (![self preConnectWithInterface:interface error:&err])
{
[err retain];
[pool drain];
return_from_block;
}
// We've made it past all the checks.
// It's time to start the connection process.
flags |= kSocketStarted;
LogVerbose(@"Dispatching DNS lookup...");
// It's possible that the given host parameter is actually a NSMutableString.
// So we want to copy it now, within this block that will be executed synchronously.
// This way the asynchronous lookup block below doesn't have to worry about it changing.
int aConnectIndex = connectIndex;
NSString *hostCpy = [[host copy] autorelease];
dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalConcurrentQueue, ^{
NSAutoreleasePool *lookupPool = [[NSAutoreleasePool alloc] init];
[self lookup:aConnectIndex host:hostCpy port:port];
[lookupPool drain];
});
[self startConnectTimeout:timeout];
result = YES;
[pool drain];
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
if (result == NO)
{
if (errPtr)
*errPtr = [err autorelease];
else
[err release];
}
return result;
}
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr
{
return [self connectToAddress:remoteAddr viaInterface:nil withTimeout:-1 error:errPtr];
}
- (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr
{
return [self connectToAddress:remoteAddr viaInterface:nil withTimeout:timeout error:errPtr];
}
- (BOOL)connectToAddress:(NSData *)remoteAddr
viaInterface:(NSString *)interface
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr
{
LogTrace();
__block BOOL result = NO;
__block NSError *err = nil;
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Check for problems with remoteAddr parameter
NSData *address4 = nil;
NSData *address6 = nil;
if ([remoteAddr length] >= sizeof(struct sockaddr))
{
const struct sockaddr *sockaddr = (const struct sockaddr *)[remoteAddr bytes];
if (sockaddr->sa_family == AF_INET)
{
if ([remoteAddr length] == sizeof(struct sockaddr_in))
{
address4 = remoteAddr;
}
}
else if (sockaddr->sa_family == AF_INET6)
{
if ([remoteAddr length] == sizeof(struct sockaddr_in6))
{
address6 = remoteAddr;
}
}
}
if ((address4 == nil) && (address6 == nil))
{
NSString *msg = @"A valid IPv4 or IPv6 address was not given";
err = [[self badParamError:msg] retain];
[pool drain];
return_from_block;
}
BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
if (isIPv4Disabled && (address4 != nil))
{
NSString *msg = @"IPv4 has been disabled and an IPv4 address was passed.";
err = [[self badParamError:msg] retain];
[pool drain];
return_from_block;
}
if (isIPv6Disabled && (address6 != nil))
{
NSString *msg = @"IPv6 has been disabled and an IPv6 address was passed.";
err = [[self badParamError:msg] retain];
[pool drain];
return_from_block;
}
// Run through standard pre-connect checks
if (![self preConnectWithInterface:interface error:&err])
{
[err retain];
[pool drain];
return_from_block;
}
// We've made it past all the checks.
// It's time to start the connection process.
if (![self connectWithAddress4:address4 address6:address6 error:&err])
{
[err retain];
[pool drain];
return_from_block;
}
flags |= kSocketStarted;
[self startConnectTimeout:timeout];
result = YES;
[pool drain];
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
if (result == NO)
{
if (errPtr)
*errPtr = [err autorelease];
else
[err release];
}
return result;
}
- (void)lookup:(int)aConnectIndex host:(NSString *)host port:(uint16_t)port
{
LogTrace();
// This method is executed on a global concurrent queue.
// It posts the results back to the socket queue.
// The lookupIndex is used to ignore the results if the connect operation was cancelled or timed out.
NSError *error = nil;
NSData *address4 = nil;
NSData *address6 = nil;
if ([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"])
{
// Use LOOPBACK address
struct sockaddr_in nativeAddr;
nativeAddr.sin_len = sizeof(struct sockaddr_in);
nativeAddr.sin_family = AF_INET;
nativeAddr.sin_port = htons(port);
nativeAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
memset(&(nativeAddr.sin_zero), 0, sizeof(nativeAddr.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_loopback;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures
address4 = [NSData dataWithBytes:&nativeAddr length:sizeof(nativeAddr)];
address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
}
else
{
NSString *portStr = [NSString stringWithFormat:@"%hu", port];
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
int gai_error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
if (gai_error)
{
error = [self gaiError:gai_error];
}
else
{
for(res = res0; res; res = res->ai_next)
{
if ((address4 == nil) && (res->ai_family == AF_INET))
{
// Found IPv4 address
// Wrap the native address structure
address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
else if ((address6 == nil) && (res->ai_family == AF_INET6))
{
// Found IPv6 address
// Wrap the native address structure
address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
}
freeaddrinfo(res0);
if ((address4 == nil) && (address6 == nil))
{
error = [self gaiError:EAI_FAIL];
}
}
}
if (error)
{
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self lookup:aConnectIndex didFail:error];
[pool drain];
});
}
else
{
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self lookup:aConnectIndex didSucceedWithAddress4:address4 address6:address6];
[pool drain];
});
}
}
- (void)lookup:(int)aConnectIndex didSucceedWithAddress4:(NSData *)address4 address6:(NSData *)address6
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
NSAssert(address4 || address6, @"Expected at least one valid address");
if (aConnectIndex != connectIndex)
{
LogInfo(@"Ignoring lookupDidSucceed, already disconnected");
// The connect operation has been cancelled.
// That is, socket was disconnected, or connection has already timed out.
return;
}
// Check for problems
BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
if (isIPv4Disabled && (address6 == nil))
{
NSString *msg = @"IPv4 has been disabled and DNS lookup found no IPv6 address.";
[self closeWithError:[self otherError:msg]];
return;
}
if (isIPv6Disabled && (address4 == nil))
{
NSString *msg = @"IPv6 has been disabled and DNS lookup found no IPv4 address.";
[self closeWithError:[self otherError:msg]];
return;
}
// Start the normal connection process
NSError *err = nil;
if (![self connectWithAddress4:address4 address6:address6 error:&err])
{
[self closeWithError:err];
}
}
/**
* This method is called if the DNS lookup fails.
* This method is executed on the socketQueue.
*
* Since the DNS lookup executed synchronously on a global concurrent queue,
* the original connection request may have already been cancelled or timed-out by the time this method is invoked.
* The lookupIndex tells us whether the lookup is still valid or not.
**/
- (void)lookup:(int)aConnectIndex didFail:(NSError *)error
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
if (aConnectIndex != connectIndex)
{
LogInfo(@"Ignoring lookup:didFail: - already disconnected");
// The connect operation has been cancelled.
// That is, socket was disconnected, or connection has already timed out.
return;
}
[self endConnectTimeout];
[self closeWithError:error];
}
- (BOOL)connectWithAddress4:(NSData *)address4 address6:(NSData *)address6 error:(NSError **)errPtr
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
LogVerbose(@"IPv4: %@:%hu", [[self class] hostFromAddress:address4], [[self class] portFromAddress:address4]);
LogVerbose(@"IPv6: %@:%hu", [[self class] hostFromAddress:address6], [[self class] portFromAddress:address6]);
// Determine socket type
BOOL preferIPv6 = (config & kPreferIPv6) ? YES : NO;
BOOL useIPv6 = ((preferIPv6 && address6) || (address4 == nil));
// Create the socket
int socketFD;
NSData *address;
NSData *connectInterface;
if (useIPv6)
{
LogVerbose(@"Creating IPv6 socket");
socket6FD = socket(AF_INET6, SOCK_STREAM, 0);
socketFD = socket6FD;
address = address6;
connectInterface = connectInterface6;
}
else
{
LogVerbose(@"Creating IPv4 socket");
socket4FD = socket(AF_INET, SOCK_STREAM, 0);
socketFD = socket4FD;
address = address4;
connectInterface = connectInterface4;
}
if (socketFD == SOCKET_NULL)
{
if (errPtr)
*errPtr = [self errnoErrorWithReason:@"Error in socket() function"];
return NO;
}
// Bind the socket to the desired interface (if needed)
if (connectInterface)
{
LogVerbose(@"Binding socket...");
if ([[self class] portFromAddress:connectInterface] > 0)
{
// Since we're going to be binding to a specific port,
// we should turn on reuseaddr to allow us to override sockets in time_wait.
int reuseOn = 1;
setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
}
const struct sockaddr *interfaceAddr = (const struct sockaddr *)[connectInterface bytes];
int result = bind(socketFD, interfaceAddr, (socklen_t)[connectInterface length]);
if (result != 0)
{
if (errPtr)
*errPtr = [self errnoErrorWithReason:@"Error in bind() function"];
return NO;
}
}
// Start the connection process in a background queue
int aConnectIndex = connectIndex;
dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalConcurrentQueue, ^{
int result = connect(socketFD, (const struct sockaddr *)[address bytes], (socklen_t)[address length]);
if (result == 0)
{
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self didConnect:aConnectIndex];
[pool drain];
});
}
else
{
NSError *error = [self errnoErrorWithReason:@"Error in connect() function"];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self didNotConnect:aConnectIndex error:error];
[pool drain];
});
}
});
LogVerbose(@"Connecting...");
return YES;
}
- (void)didConnect:(int)aConnectIndex
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
if (aConnectIndex != connectIndex)
{
LogInfo(@"Ignoring didConnect, already disconnected");
// The connect operation has been cancelled.
// That is, socket was disconnected, or connection has already timed out.
return;
}
flags |= kConnected;
[self endConnectTimeout];
aConnectIndex = connectIndex;
// Setup read/write streams (as workaround for specific shortcomings in the iOS platform)
//
// Note:
// There may be configuration options that must be set by the delegate before opening the streams.
// The primary example is the kCFStreamNetworkServiceTypeVoIP flag, which only works on an unopened stream.
//
// Thus we wait until after the socket:didConnectToHost:port: delegate method has completed.
// This gives the delegate time to properly configure the streams if needed.
dispatch_block_t SetupStreamsPart1 = ^{
#if TARGET_OS_IPHONE
if (![self createReadAndWriteStream])
{
[self closeWithError:[self otherError:@"Error creating CFStreams"]];
return;
}
if (![self registerForStreamCallbacksIncludingReadWrite:NO])
{
[self closeWithError:[self otherError:@"Error in CFStreamSetClient"]];
return;
}
#endif
};
dispatch_block_t SetupStreamsPart2 = ^{
#if TARGET_OS_IPHONE
if (aConnectIndex != connectIndex)
{
// The socket has been disconnected.
return;
}
if (![self addStreamsToRunLoop])
{
[self closeWithError:[self otherError:@"Error in CFStreamScheduleWithRunLoop"]];
return;
}
if (![self openStreams])
{
[self closeWithError:[self otherError:@"Error creating CFStreams"]];
return;
}
#endif
};
// Notify delegate
NSString *host = [self connectedHost];
uint16_t port = [self connectedPort];
if (delegateQueue && [delegate respondsToSelector:@selector(socket:didConnectToHost:port:)])
{
SetupStreamsPart1();
id theDelegate = delegate;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *delegatePool = [[NSAutoreleasePool alloc] init];
[theDelegate socket:self didConnectToHost:host port:port];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *callbackPool = [[NSAutoreleasePool alloc] init];
SetupStreamsPart2();
[callbackPool drain];
});
[delegatePool drain];
});
}
else
{
SetupStreamsPart1();
SetupStreamsPart2();
}
// Get the connected socket
int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : socket6FD;
// Enable non-blocking IO on the socket
int result = fcntl(socketFD, F_SETFL, O_NONBLOCK);
if (result == -1)
{
NSString *errMsg = @"Error enabling non-blocking IO on socket (fcntl)";
[self closeWithError:[self otherError:errMsg]];
return;
}
// Prevent SIGPIPE signals
int nosigpipe = 1;
setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
// Setup our read/write sources
[self setupReadAndWriteSourcesForNewlyConnectedSocket:socketFD];
// Dequeue any pending read/write requests
[self maybeDequeueRead];
[self maybeDequeueWrite];
}
- (void)didNotConnect:(int)aConnectIndex error:(NSError *)error
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
if (aConnectIndex != connectIndex)
{
LogInfo(@"Ignoring didNotConnect, already disconnected");
// The connect operation has been cancelled.
// That is, socket was disconnected, or connection has already timed out.
return;
}
[self endConnectTimeout];
[self closeWithError:error];
}
- (void)startConnectTimeout:(NSTimeInterval)timeout
{
if (timeout >= 0.0)
{
connectTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue);
dispatch_source_set_event_handler(connectTimer, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self doConnectTimeout];
[pool drain];
});
dispatch_source_t theConnectTimer = connectTimer;
dispatch_source_set_cancel_handler(connectTimer, ^{
LogVerbose(@"dispatch_release(connectTimer)");
dispatch_release(theConnectTimer);
});
dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC));
dispatch_source_set_timer(connectTimer, tt, DISPATCH_TIME_FOREVER, 0);
dispatch_resume(connectTimer);
}
}
- (void)endConnectTimeout
{
LogTrace();
if (connectTimer)
{
dispatch_source_cancel(connectTimer);
connectTimer = NULL;
}
// Increment connectIndex.
// This will prevent us from processing results from any related background asynchronous operations.
//
// Note: This should be called from close method even if connectTimer is NULL.
// This is because one might disconnect a socket prior to a successful connection which had no timeout.
connectIndex++;
if (connectInterface4)
{
[connectInterface4 release];
connectInterface4 = nil;
}
if (connectInterface6)
{
[connectInterface6 release];
connectInterface6 = nil;
}
}
- (void)doConnectTimeout
{
LogTrace();
[self endConnectTimeout];
[self closeWithError:[self connectTimeoutError]];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Disconnecting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)closeWithError:(NSError *)error
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
[self endConnectTimeout];
if (currentRead != nil) [self endCurrentRead];
if (currentWrite != nil) [self endCurrentWrite];
[readQueue removeAllObjects];
[writeQueue removeAllObjects];
[partialReadBuffer setLength:0];
#if TARGET_OS_IPHONE
{
if (readStream || writeStream)
{
[self removeStreamsFromRunLoop];
if (readStream)
{
CFReadStreamSetClient(readStream, kCFStreamEventNone, NULL, NULL);
CFReadStreamClose(readStream);
CFRelease(readStream);
readStream = NULL;
}
if (writeStream)
{
CFWriteStreamSetClient(writeStream, kCFStreamEventNone, NULL, NULL);
CFWriteStreamClose(writeStream);
CFRelease(writeStream);
writeStream = NULL;
}
}
}
#else
{
[sslReadBuffer setLength:0];
if (sslContext)
{
// Getting a linker error here about SSLDisposeContext?
// You need to add the Security Framework to your application.
SSLDisposeContext(sslContext);
sslContext = NULL;
}
}
#endif
// For some crazy reason (in my opinion), cancelling a dispatch source doesn't
// invoke the cancel handler if the dispatch source is paused.
// So we have to unpause the source if needed.
// This allows the cancel handler to be run, which in turn releases the source and closes the socket.
if (accept4Source)
{
LogVerbose(@"dispatch_source_cancel(accept4Source)");
dispatch_source_cancel(accept4Source);
// We never suspend accept4Source
accept4Source = NULL;
}
if (accept6Source)
{
LogVerbose(@"dispatch_source_cancel(accept6Source)");
dispatch_source_cancel(accept6Source);
// We never suspend accept6Source
accept6Source = NULL;
}
if (readSource)
{
LogVerbose(@"dispatch_source_cancel(readSource)");
dispatch_source_cancel(readSource);
[self resumeReadSource];
readSource = NULL;
}
if (writeSource)
{
LogVerbose(@"dispatch_source_cancel(writeSource)");
dispatch_source_cancel(writeSource);
[self resumeWriteSource];
writeSource = NULL;
}
// The sockets will be closed by the cancel handlers of the corresponding source
socket4FD = SOCKET_NULL;
socket6FD = SOCKET_NULL;
// If the client has passed the connect/accept method, then the connection has at least begun.
// Notify delegate that it is now ending.
BOOL shouldCallDelegate = (flags & kSocketStarted);
// Clear stored socket info and all flags (config remains as is)
socketFDBytesAvailable = 0;
flags = 0;
if (shouldCallDelegate)
{
if (delegateQueue && [delegate respondsToSelector: @selector(socketDidDisconnect:withError:)])
{
id theDelegate = delegate;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socketDidDisconnect:self withError:error];
[pool drain];
});
}
}
}
- (void)disconnect
{
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (flags & kSocketStarted)
{
[self closeWithError:nil];
}
[pool drain];
};
// Synchronous disconnection, as documented in the header file
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
}
- (void)disconnectAfterReading
{
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (flags & kSocketStarted)
{
flags |= (kForbidReadsWrites | kDisconnectAfterReads);
[self maybeClose];
}
[pool drain];
});
}
- (void)disconnectAfterWriting
{
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (flags & kSocketStarted)
{
flags |= (kForbidReadsWrites | kDisconnectAfterWrites);
[self maybeClose];
}
[pool drain];
});
}
- (void)disconnectAfterReadingAndWriting
{
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (flags & kSocketStarted)
{
flags |= (kForbidReadsWrites | kDisconnectAfterReads | kDisconnectAfterWrites);
[self maybeClose];
}
[pool drain];
});
}
/**
* Closes the socket if possible.
* That is, if all writes have completed, and we're set to disconnect after writing,
* or if all reads have completed, and we're set to disconnect after reading.
**/
- (void)maybeClose
{
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
BOOL shouldClose = NO;
if (flags & kDisconnectAfterReads)
{
if (([readQueue count] == 0) && (currentRead == nil))
{
if (flags & kDisconnectAfterWrites)
{
if (([writeQueue count] == 0) && (currentWrite == nil))
{
shouldClose = YES;
}
}
else
{
shouldClose = YES;
}
}
}
else if (flags & kDisconnectAfterWrites)
{
if (([writeQueue count] == 0) && (currentWrite == nil))
{
shouldClose = YES;
}
}
if (shouldClose)
{
[self closeWithError:nil];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Errors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSError *)badConfigError:(NSString *)errMsg
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketBadConfigError userInfo:userInfo];
}
- (NSError *)badParamError:(NSString *)errMsg
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketBadParamError userInfo:userInfo];
}
- (NSError *)gaiError:(int)gai_error
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(gai_error) encoding:NSASCIIStringEncoding];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:gai_error userInfo:userInfo];
}
- (NSError *)errnoErrorWithReason:(NSString *)reason
{
NSString *errMsg = [NSString stringWithUTF8String:strerror(errno)];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:errMsg, NSLocalizedDescriptionKey,
reason, NSLocalizedFailureReasonErrorKey, nil];
return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo];
}
- (NSError *)errnoError
{
NSString *errMsg = [NSString stringWithUTF8String:strerror(errno)];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo];
}
- (NSError *)sslError:(OSStatus)ssl_error
{
NSString *msg = @"Error code definition can be found in Apple's SecureTransport.h";
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:msg forKey:NSLocalizedRecoverySuggestionErrorKey];
return [NSError errorWithDomain:@"kCFStreamErrorDomainSSL" code:ssl_error userInfo:userInfo];
}
- (NSError *)connectTimeoutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketConnectTimeoutError",
@"GCDAsyncSocket", [NSBundle mainBundle],
@"Attempt to connect to host timed out", nil);
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketConnectTimeoutError userInfo:userInfo];
}
/**
* Returns a standard AsyncSocket maxed out error.
**/
- (NSError *)readMaxedOutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketReadMaxedOutError",
@"GCDAsyncSocket", [NSBundle mainBundle],
@"Read operation reached set maximum length", nil);
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketReadMaxedOutError userInfo:info];
}
/**
* Returns a standard AsyncSocket write timeout error.
**/
- (NSError *)readTimeoutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketReadTimeoutError",
@"GCDAsyncSocket", [NSBundle mainBundle],
@"Read operation timed out", nil);
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketReadTimeoutError userInfo:userInfo];
}
/**
* Returns a standard AsyncSocket write timeout error.
**/
- (NSError *)writeTimeoutError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketWriteTimeoutError",
@"GCDAsyncSocket", [NSBundle mainBundle],
@"Write operation timed out", nil);
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketWriteTimeoutError userInfo:userInfo];
}
- (NSError *)connectionClosedError
{
NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketClosedError",
@"GCDAsyncSocket", [NSBundle mainBundle],
@"Socket closed by remote peer", nil);
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketClosedError userInfo:userInfo];
}
- (NSError *)otherError:(NSString *)errMsg
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketOtherError userInfo:userInfo];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Diagnostics
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)isDisconnected
{
__block BOOL result;
dispatch_block_t block = ^{
result = (flags & kSocketStarted) ? NO : YES;
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (BOOL)isConnected
{
__block BOOL result;
dispatch_block_t block = ^{
result = (flags & kConnected) ? YES : NO;
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (NSString *)connectedHost
{
if (dispatch_get_current_queue() == socketQueue)
{
if (socket4FD != SOCKET_NULL)
return [self connectedHostFromSocket4:socket4FD];
if (socket6FD != SOCKET_NULL)
return [self connectedHostFromSocket6:socket6FD];
return nil;
}
else
{
__block NSString *result = nil;
dispatch_sync(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (socket4FD != SOCKET_NULL)
result = [[self connectedHostFromSocket4:socket4FD] retain];
else if (socket6FD != SOCKET_NULL)
result = [[self connectedHostFromSocket6:socket6FD] retain];
[pool drain];
});
return [result autorelease];
}
}
- (uint16_t)connectedPort
{
if (dispatch_get_current_queue() == socketQueue)
{
if (socket4FD != SOCKET_NULL)
return [self connectedPortFromSocket4:socket4FD];
if (socket6FD != SOCKET_NULL)
return [self connectedPortFromSocket6:socket6FD];
return 0;
}
else
{
__block uint16_t result = 0;
dispatch_sync(socketQueue, ^{
// No need for autorelease pool
if (socket4FD != SOCKET_NULL)
result = [self connectedPortFromSocket4:socket4FD];
else if (socket6FD != SOCKET_NULL)
result = [self connectedPortFromSocket6:socket6FD];
});
return result;
}
}
- (NSString *)localHost
{
if (dispatch_get_current_queue() == socketQueue)
{
if (socket4FD != SOCKET_NULL)
return [self localHostFromSocket4:socket4FD];
if (socket6FD != SOCKET_NULL)
return [self localHostFromSocket6:socket6FD];
return nil;
}
else
{
__block NSString *result = nil;
dispatch_sync(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (socket4FD != SOCKET_NULL)
result = [[self localHostFromSocket4:socket4FD] retain];
else if (socket6FD != SOCKET_NULL)
result = [[self localHostFromSocket6:socket6FD] retain];
[pool drain];
});
return [result autorelease];
}
}
- (uint16_t)localPort
{
if (dispatch_get_current_queue() == socketQueue)
{
if (socket4FD != SOCKET_NULL)
return [self localPortFromSocket4:socket4FD];
if (socket6FD != SOCKET_NULL)
return [self localPortFromSocket6:socket6FD];
return 0;
}
else
{
__block uint16_t result = 0;
dispatch_sync(socketQueue, ^{
// No need for autorelease pool
if (socket4FD != SOCKET_NULL)
result = [self localPortFromSocket4:socket4FD];
else if (socket6FD != SOCKET_NULL)
result = [self localPortFromSocket6:socket6FD];
});
return result;
}
}
- (NSString *)connectedHost4
{
if (socket4FD != SOCKET_NULL)
return [self connectedHostFromSocket4:socket4FD];
return nil;
}
- (NSString *)connectedHost6
{
if (socket6FD != SOCKET_NULL)
return [self connectedHostFromSocket6:socket6FD];
return nil;
}
- (uint16_t)connectedPort4
{
if (socket4FD != SOCKET_NULL)
return [self connectedPortFromSocket4:socket4FD];
return 0;
}
- (uint16_t)connectedPort6
{
if (socket6FD != SOCKET_NULL)
return [self connectedPortFromSocket6:socket6FD];
return 0;
}
- (NSString *)localHost4
{
if (socket4FD != SOCKET_NULL)
return [self localHostFromSocket4:socket4FD];
return nil;
}
- (NSString *)localHost6
{
if (socket6FD != SOCKET_NULL)
return [self localHostFromSocket6:socket6FD];
return nil;
}
- (uint16_t)localPort4
{
if (socket4FD != SOCKET_NULL)
return [self localPortFromSocket4:socket4FD];
return 0;
}
- (uint16_t)localPort6
{
if (socket6FD != SOCKET_NULL)
return [self localPortFromSocket6:socket6FD];
return 0;
}
- (NSString *)connectedHostFromSocket4:(int)socketFD
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if (getpeername(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return nil;
}
return [[self class] hostFromAddress4:&sockaddr4];
}
- (NSString *)connectedHostFromSocket6:(int)socketFD
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if (getpeername(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return nil;
}
return [[self class] hostFromAddress6:&sockaddr6];
}
- (uint16_t)connectedPortFromSocket4:(int)socketFD
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if (getpeername(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return 0;
}
return [[self class] portFromAddress4:&sockaddr4];
}
- (uint16_t)connectedPortFromSocket6:(int)socketFD
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if (getpeername(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return 0;
}
return [[self class] portFromAddress6:&sockaddr6];
}
- (NSString *)localHostFromSocket4:(int)socketFD
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return nil;
}
return [[self class] hostFromAddress4:&sockaddr4];
}
- (NSString *)localHostFromSocket6:(int)socketFD
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return nil;
}
return [[self class] hostFromAddress6:&sockaddr6];
}
- (uint16_t)localPortFromSocket4:(int)socketFD
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
{
return 0;
}
return [[self class] portFromAddress4:&sockaddr4];
}
- (uint16_t)localPortFromSocket6:(int)socketFD
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
{
return 0;
}
return [[self class] portFromAddress6:&sockaddr6];
}
- (NSData *)connectedAddress
{
__block NSData *result = nil;
dispatch_block_t block = ^{
if (socket4FD != SOCKET_NULL)
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if (getpeername(socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0)
{
result = [[NSData alloc] initWithBytes:&sockaddr4 length:sockaddr4len];
}
}
if (socket6FD != SOCKET_NULL)
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if (getpeername(socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0)
{
result = [[NSData alloc] initWithBytes:&sockaddr6 length:sockaddr6len];
}
}
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
return [result autorelease];
}
- (NSData *)localAddress
{
__block NSData *result = nil;
dispatch_block_t block = ^{
if (socket4FD != SOCKET_NULL)
{
struct sockaddr_in sockaddr4;
socklen_t sockaddr4len = sizeof(sockaddr4);
if (getsockname(socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0)
{
result = [[NSData alloc] initWithBytes:&sockaddr4 length:sockaddr4len];
}
}
if (socket6FD != SOCKET_NULL)
{
struct sockaddr_in6 sockaddr6;
socklen_t sockaddr6len = sizeof(sockaddr6);
if (getsockname(socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0)
{
result = [[NSData alloc] initWithBytes:&sockaddr6 length:sockaddr6len];
}
}
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
return [result autorelease];
}
- (BOOL)isIPv4
{
if (dispatch_get_current_queue() == socketQueue)
{
return (socket4FD != SOCKET_NULL);
}
else
{
__block BOOL result = NO;
dispatch_sync(socketQueue, ^{
result = (socket4FD != SOCKET_NULL);
});
return result;
}
}
- (BOOL)isIPv6
{
if (dispatch_get_current_queue() == socketQueue)
{
return (socket6FD != SOCKET_NULL);
}
else
{
__block BOOL result = NO;
dispatch_sync(socketQueue, ^{
result = (socket6FD != SOCKET_NULL);
});
return result;
}
}
- (BOOL)isSecure
{
if (dispatch_get_current_queue() == socketQueue)
{
return (flags & kSocketSecure) ? YES : NO;
}
else
{
__block BOOL result;
dispatch_sync(socketQueue, ^{
result = (flags & kSocketSecure) ? YES : NO;
});
return result;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Utilities
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finds the address of an interface description.
* An inteface description may be an interface name (en0, en1, lo0) or corresponding IP (192.168.4.34).
*
* The interface description may optionally contain a port number at the end, separated by a colon.
* If a non-zero port parameter is provided, any port number in the interface description is ignored.
*
* The returned value is a 'struct sockaddr' wrapped in an NSMutableData object.
**/
- (void)getInterfaceAddress4:(NSMutableData **)interfaceAddr4Ptr
address6:(NSMutableData **)interfaceAddr6Ptr
fromDescription:(NSString *)interfaceDescription
port:(uint16_t)port
{
NSMutableData *addr4 = nil;
NSMutableData *addr6 = nil;
NSString *interface = nil;
NSArray *components = [interfaceDescription componentsSeparatedByString:@":"];
if ([components count] > 0)
{
NSString *temp = [components objectAtIndex:0];
if ([temp length] > 0)
{
interface = temp;
}
}
if ([components count] > 1 && port == 0)
{
long portL = strtol([[components objectAtIndex:1] UTF8String], NULL, 10);
if (portL > 0 && portL <= UINT16_MAX)
{
port = (uint16_t)portL;
}
}
if (interface == nil)
{
// ANY address
struct sockaddr_in nativeAddr4;
memset(&nativeAddr4, 0, sizeof(nativeAddr4));
nativeAddr4.sin_len = sizeof(nativeAddr4);
nativeAddr4.sin_family = AF_INET;
nativeAddr4.sin_port = htons(port);
nativeAddr4.sin_addr.s_addr = htonl(INADDR_ANY);
struct sockaddr_in6 nativeAddr6;
memset(&nativeAddr6, 0, sizeof(nativeAddr6));
nativeAddr6.sin6_len = sizeof(nativeAddr6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_addr = in6addr_any;
addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
}
else if ([interface isEqualToString:@"localhost"] || [interface isEqualToString:@"loopback"])
{
// LOOPBACK address
struct sockaddr_in nativeAddr4;
memset(&nativeAddr4, 0, sizeof(nativeAddr4));
nativeAddr4.sin_len = sizeof(struct sockaddr_in);
nativeAddr4.sin_family = AF_INET;
nativeAddr4.sin_port = htons(port);
nativeAddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
struct sockaddr_in6 nativeAddr6;
memset(&nativeAddr6, 0, sizeof(nativeAddr6));
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_addr = in6addr_loopback;
addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
}
else
{
const char *iface = [interface UTF8String];
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
if ((getifaddrs(&addrs) == 0))
{
cursor = addrs;
while (cursor != NULL)
{
if ((addr4 == nil) && (cursor->ifa_addr->sa_family == AF_INET))
{
// IPv4
struct sockaddr_in nativeAddr4;
memcpy(&nativeAddr4, cursor->ifa_addr, sizeof(nativeAddr4));
if (strcmp(cursor->ifa_name, iface) == 0)
{
// Name match
nativeAddr4.sin_port = htons(port);
addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
}
else
{
char ip[INET_ADDRSTRLEN];
const char *conversion = inet_ntop(AF_INET, &nativeAddr4.sin_addr, ip, sizeof(ip));
if ((conversion != NULL) && (strcmp(ip, iface) == 0))
{
// IP match
nativeAddr4.sin_port = htons(port);
addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
}
}
}
else if ((addr6 == nil) && (cursor->ifa_addr->sa_family == AF_INET6))
{
// IPv6
struct sockaddr_in6 nativeAddr6;
memcpy(&nativeAddr6, cursor->ifa_addr, sizeof(nativeAddr6));
if (strcmp(cursor->ifa_name, iface) == 0)
{
// Name match
nativeAddr6.sin6_port = htons(port);
addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
}
else
{
char ip[INET6_ADDRSTRLEN];
const char *conversion = inet_ntop(AF_INET6, &nativeAddr6.sin6_addr, ip, sizeof(ip));
if ((conversion != NULL) && (strcmp(ip, iface) == 0))
{
// IP match
nativeAddr6.sin6_port = htons(port);
addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
}
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
}
if (interfaceAddr4Ptr) *interfaceAddr4Ptr = addr4;
if (interfaceAddr6Ptr) *interfaceAddr6Ptr = addr6;
}
- (void)setupReadAndWriteSourcesForNewlyConnectedSocket:(int)socketFD
{
readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socketFD, 0, socketQueue);
writeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socketFD, 0, socketQueue);
// Setup event handlers
dispatch_source_set_event_handler(readSource, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
LogVerbose(@"readEventBlock");
socketFDBytesAvailable = dispatch_source_get_data(readSource);
LogVerbose(@"socketFDBytesAvailable: %lu", socketFDBytesAvailable);
if (socketFDBytesAvailable > 0)
[self doReadData];
else
[self doReadEOF];
[pool drain];
});
dispatch_source_set_event_handler(writeSource, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
LogVerbose(@"writeEventBlock");
flags |= kSocketCanAcceptBytes;
[self doWriteData];
[pool drain];
});
// Setup cancel handlers
__block int socketFDRefCount = 2;
dispatch_source_t theReadSource = readSource;
dispatch_source_t theWriteSource = writeSource;
dispatch_source_set_cancel_handler(readSource, ^{
LogVerbose(@"readCancelBlock");
LogVerbose(@"dispatch_release(readSource)");
dispatch_release(theReadSource);
if (--socketFDRefCount == 0)
{
LogVerbose(@"close(socketFD)");
close(socketFD);
}
});
dispatch_source_set_cancel_handler(writeSource, ^{
LogVerbose(@"writeCancelBlock");
LogVerbose(@"dispatch_release(writeSource)");
dispatch_release(theWriteSource);
if (--socketFDRefCount == 0)
{
LogVerbose(@"close(socketFD)");
close(socketFD);
}
});
// We will not be able to read until data arrives.
// But we should be able to write immediately.
socketFDBytesAvailable = 0;
flags &= ~kReadSourceSuspended;
LogVerbose(@"dispatch_resume(readSource)");
dispatch_resume(readSource);
flags |= kSocketCanAcceptBytes;
flags |= kWriteSourceSuspended;
}
- (BOOL)usingCFStream
{
#if TARGET_OS_IPHONE
if (flags & kSocketSecure)
{
// Due to the fact that Apple doesn't give us the full power of SecureTransport on iOS,
// we are relegated to using the slower, less powerful, and RunLoop based CFStream API. :( Boo!
//
// Thus we're not able to use the GCD read/write sources in this particular scenario.
return YES;
}
#endif
return NO;
}
- (void)suspendReadSource
{
if (!(flags & kReadSourceSuspended))
{
LogVerbose(@"dispatch_suspend(readSource)");
dispatch_suspend(readSource);
flags |= kReadSourceSuspended;
}
}
- (void)resumeReadSource
{
if (flags & kReadSourceSuspended)
{
LogVerbose(@"dispatch_resume(readSource)");
dispatch_resume(readSource);
flags &= ~kReadSourceSuspended;
}
}
- (void)suspendWriteSource
{
if (!(flags & kWriteSourceSuspended))
{
LogVerbose(@"dispatch_suspend(writeSource)");
dispatch_suspend(writeSource);
flags |= kWriteSourceSuspended;
}
}
- (void)resumeWriteSource
{
if (flags & kWriteSourceSuspended)
{
LogVerbose(@"dispatch_resume(writeSource)");
dispatch_resume(writeSource);
flags &= ~kWriteSourceSuspended;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Reading
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag
{
[self readDataWithTimeout:timeout buffer:nil bufferOffset:0 maxLength:0 tag:tag];
}
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag
{
[self readDataWithTimeout:timeout buffer:buffer bufferOffset:offset maxLength:0 tag:tag];
}
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag
{
if (offset > [buffer length]) return;
GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer
startOffset:offset
maxLength:length
timeout:timeout
readLength:0
terminator:nil
tag:tag];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
LogTrace();
if ((flags & kSocketStarted) && !(flags & kForbidReadsWrites))
{
[readQueue addObject:packet];
[self maybeDequeueRead];
}
[pool drain];
});
// Do not rely on the block being run in order to release the packet,
// as the queue might get released without the block completing.
[packet release];
}
- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
[self readDataToLength:length withTimeout:timeout buffer:nil bufferOffset:0 tag:tag];
}
- (void)readDataToLength:(NSUInteger)length
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag
{
if (length == 0) return;
if (offset > [buffer length]) return;
GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer
startOffset:offset
maxLength:0
timeout:timeout
readLength:length
terminator:nil
tag:tag];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
LogTrace();
if ((flags & kSocketStarted) && !(flags & kForbidReadsWrites))
{
[readQueue addObject:packet];
[self maybeDequeueRead];
}
[pool drain];
});
// Do not rely on the block being run in order to release the packet,
// as the queue might get released without the block completing.
[packet release];
}
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
[self readDataToData:data withTimeout:timeout buffer:nil bufferOffset:0 maxLength:0 tag:tag];
}
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag
{
[self readDataToData:data withTimeout:timeout buffer:buffer bufferOffset:offset maxLength:0 tag:tag];
}
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag
{
[self readDataToData:data withTimeout:timeout buffer:nil bufferOffset:0 maxLength:length tag:tag];
}
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag
{
if ([data length] == 0) return;
if (offset > [buffer length]) return;
if (length > 0 && length < [data length]) return;
GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer
startOffset:offset
maxLength:length
timeout:timeout
readLength:0
terminator:data
tag:tag];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
LogTrace();
if ((flags & kSocketStarted) && !(flags & kForbidReadsWrites))
{
[readQueue addObject:packet];
[self maybeDequeueRead];
}
[pool drain];
});
// Do not rely on the block being run in order to release the packet,
// as the queue might get released without the block completing.
[packet release];
}
/**
* This method starts a new read, if needed.
*
* It is called when:
* - a user requests a read
* - after a read request has finished (to handle the next request)
* - immediately after the socket opens to handle any pending requests
*
* This method also handles auto-disconnect post read/write completion.
**/
- (void)maybeDequeueRead
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
// If we're not currently processing a read AND we have an available read stream
if ((currentRead == nil) && (flags & kConnected))
{
if ([readQueue count] > 0)
{
// Dequeue the next object in the write queue
currentRead = [[readQueue objectAtIndex:0] retain];
[readQueue removeObjectAtIndex:0];
if ([currentRead isKindOfClass:[GCDAsyncSpecialPacket class]])
{
LogVerbose(@"Dequeued GCDAsyncSpecialPacket");
// Attempt to start TLS
flags |= kStartingReadTLS;
// This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set
[self maybeStartTLS];
}
else
{
LogVerbose(@"Dequeued GCDAsyncReadPacket");
// Setup read timer (if needed)
[self setupReadTimerWithTimeout:currentRead->timeout];
// Immediately read, if possible
[self doReadData];
}
}
else if (flags & kDisconnectAfterReads)
{
if (flags & kDisconnectAfterWrites)
{
if (([writeQueue count] == 0) && (currentWrite == nil))
{
[self closeWithError:nil];
}
}
else
{
[self closeWithError:nil];
}
}
else if (flags & kSocketSecure)
{
[self flushSSLBuffers];
// Edge case:
//
// We just drained all data from the ssl buffers,
// and all known data from the socket (socketFDBytesAvailable).
//
// If we didn't get any data from this process,
// then we may have reached the end of the TCP stream.
//
// Be sure callbacks are enabled so we're notified about a disconnection.
if ([partialReadBuffer length] == 0)
{
if ([self usingCFStream]) {
// Callbacks never disabled
}
else {
[self resumeReadSource];
}
}
}
}
}
- (void)flushSSLBuffers
{
LogTrace();
NSAssert((flags & kSocketSecure), @"Cannot flush ssl buffers on non-secure socket");
if ([partialReadBuffer length] > 0)
{
// Only flush the ssl buffers if the partialReadBuffer is empty.
// This is to avoid growing the partialReadBuffer inifinitely large.
return;
}
#if TARGET_OS_IPHONE
if (flags & kSecureSocketHasBytesAvailable)
{
LogVerbose(@"%@ - Flushing ssl buffers into partialReadBuffer...", THIS_METHOD);
CFIndex defaultBytesToRead = (1024 * 16);
NSUInteger partialReadBufferOffset = [partialReadBuffer length];
[partialReadBuffer increaseLengthBy:defaultBytesToRead];
uint8_t *buffer = [partialReadBuffer mutableBytes] + partialReadBufferOffset;
CFIndex result = CFReadStreamRead(readStream, buffer, defaultBytesToRead);
LogVerbose(@"%@ - CFReadStreamRead(): result = %i", THIS_METHOD, (int)result);
if (result <= 0)
{
[partialReadBuffer setLength:partialReadBufferOffset];
}
else
{
[partialReadBuffer setLength:(partialReadBufferOffset + result)];
}
flags &= ~kSecureSocketHasBytesAvailable;
}
#else
__block NSUInteger estimatedBytesAvailable;
dispatch_block_t updateEstimatedBytesAvailable = ^{
// Figure out if there is any data available to be read
//
// socketFDBytesAvailable <- Number of encrypted bytes we haven't read from the bsd socket
// [sslReadBuffer length] <- Number of encrypted bytes we've buffered from bsd socket
// sslInternalBufSize <- Number od decrypted bytes SecureTransport has buffered
//
// We call the variable "estimated" because we don't know how many decrypted bytes we'll get
// from the encrypted bytes in the sslReadBuffer.
// However, we do know this is an upper bound on the estimation.
estimatedBytesAvailable = socketFDBytesAvailable + [sslReadBuffer length];
size_t sslInternalBufSize = 0;
SSLGetBufferedReadSize(sslContext, &sslInternalBufSize);
estimatedBytesAvailable += sslInternalBufSize;
};
updateEstimatedBytesAvailable();
if (estimatedBytesAvailable > 0)
{
LogVerbose(@"%@ - Flushing ssl buffers into partialReadBuffer...", THIS_METHOD);
BOOL done = NO;
do
{
LogVerbose(@"%@ - estimatedBytesAvailable = %lu", THIS_METHOD, (unsigned long)estimatedBytesAvailable);
// Make room in the partialReadBuffer
NSUInteger partialReadBufferOffset = [partialReadBuffer length];
[partialReadBuffer increaseLengthBy:estimatedBytesAvailable];
uint8_t *buffer = (uint8_t *)[partialReadBuffer mutableBytes] + partialReadBufferOffset;
size_t bytesRead = 0;
// Read data into partialReadBuffer
OSStatus result = SSLRead(sslContext, buffer, (size_t)estimatedBytesAvailable, &bytesRead);
LogVerbose(@"%@ - read from secure socket = %u", THIS_METHOD, (unsigned)bytesRead);
[partialReadBuffer setLength:(partialReadBufferOffset + bytesRead)];
LogVerbose(@"%@ - partialReadBuffer.length = %lu", THIS_METHOD, (unsigned long)[partialReadBuffer length]);
if (result != noErr)
{
done = YES;
}
else
{
updateEstimatedBytesAvailable();
}
} while (!done && estimatedBytesAvailable > 0);
}
#endif
}
- (void)doReadData
{
LogTrace();
// This method is called on the socketQueue.
// It might be called directly, or via the readSource when data is available to be read.
if ((currentRead == nil) || (flags & kReadsPaused))
{
LogVerbose(@"No currentRead or kReadsPaused");
// Unable to read at this time
if (flags & kSocketSecure)
{
// Here's the situation:
//
// We have an established secure connection.
// There may not be a currentRead, but there might be encrypted data sitting around for us.
// When the user does get around to issuing a read, that encrypted data will need to be decrypted.
//
// So why make the user wait?
// We might as well get a head start on decrypting some data now.
//
// The other reason we do this has to do with detecting a socket disconnection.
// The SSL/TLS protocol has it's own disconnection handshake.
// So when a secure socket is closed, a "goodbye" packet comes across the wire.
// We want to make sure we read the "goodbye" packet so we can properly detect the TCP disconnection.
[self flushSSLBuffers];
}
if ([self usingCFStream])
{
// CFReadStream only fires once when there is available data.
// It won't fire again until we've invoked CFReadStreamRead.
}
else
{
// If the readSource is firing, we need to pause it
// or else it will continue to fire over and over again.
//
// If the readSource is not firing,
// we want it to continue monitoring the socket.
if (socketFDBytesAvailable > 0)
{
[self suspendReadSource];
}
}
return;
}
BOOL hasBytesAvailable;
unsigned long estimatedBytesAvailable;
#if TARGET_OS_IPHONE
if (flags & kSocketSecure)
{
// Relegated to using CFStream... :( Boo! Give us SecureTransport Apple!
estimatedBytesAvailable = 0;
hasBytesAvailable = (flags & kSecureSocketHasBytesAvailable) ? YES : NO;
}
else
{
estimatedBytesAvailable = socketFDBytesAvailable;
hasBytesAvailable = (estimatedBytesAvailable > 0);
}
#else
estimatedBytesAvailable = socketFDBytesAvailable;
if (flags & kSocketSecure)
{
// There are 2 buffers to be aware of here.
//
// We are using SecureTransport, a TLS/SSL security layer which sits atop TCP.
// We issue a read to the SecureTranport API, which in turn issues a read to our SSLReadFunction.
// Our SSLReadFunction then reads from the BSD socket and returns the encrypted data to SecureTransport.
// SecureTransport then decrypts the data, and finally returns the decrypted data back to us.
//
// The first buffer is one we create.
// SecureTransport often requests small amounts of data.
// This has to do with the encypted packets that are coming across the TCP stream.
// But it's non-optimal to do a bunch of small reads from the BSD socket.
// So our SSLReadFunction reads all available data from the socket (optimizing the sys call)
// and may store excess in the sslReadBuffer.
estimatedBytesAvailable += [sslReadBuffer length];
// The second buffer is within SecureTransport.
// As mentioned earlier, there are encrypted packets coming across the TCP stream.
// SecureTransport needs the entire packet to decrypt it.
// But if the entire packet produces X bytes of decrypted data,
// and we only asked SecureTransport for X/2 bytes of data,
// it must store the extra X/2 bytes of decrypted data for the next read.
//
// The SSLGetBufferedReadSize function will tell us the size of this internal buffer.
// From the documentation:
//
// "This function does not block or cause any low-level read operations to occur."
size_t sslInternalBufSize = 0;
SSLGetBufferedReadSize(sslContext, &sslInternalBufSize);
estimatedBytesAvailable += sslInternalBufSize;
}
hasBytesAvailable = (estimatedBytesAvailable > 0);
#endif
if ((hasBytesAvailable == NO) && ([partialReadBuffer length] == 0))
{
LogVerbose(@"No data available to read...");
// No data available to read.
if (![self usingCFStream])
{
// Need to wait for readSource to fire and notify us of
// available data in the socket's internal read buffer.
[self resumeReadSource];
}
return;
}
if (flags & kStartingReadTLS)
{
LogVerbose(@"Waiting for SSL/TLS handshake to complete");
// The readQueue is waiting for SSL/TLS handshake to complete.
if (flags & kStartingWriteTLS)
{
#if !TARGET_OS_IPHONE
// We are in the process of a SSL Handshake.
// We were waiting for incoming data which has just arrived.
[self continueSSLHandshake];
#endif
}
else
{
// We are still waiting for the writeQueue to drain and start the SSL/TLS process.
// We now know data is available to read.
if (![self usingCFStream])
{
// Suspend the read source or else it will continue to fire nonstop.
[self suspendReadSource];
}
}
return;
}
BOOL done = NO; // Completed read operation
BOOL waiting = NO; // Ran out of data, waiting for more
BOOL socketEOF = (flags & kSocketHasReadEOF) ? YES : NO; // Nothing more to via socket (end of file)
NSError *error = nil; // Error occured
NSUInteger totalBytesReadForCurrentRead = 0;
//
// STEP 1 - READ FROM PREBUFFER
//
NSUInteger partialReadBufferLength = [partialReadBuffer length];
if (partialReadBufferLength > 0)
{
// There are 3 types of read packets:
//
// 1) Read all available data.
// 2) Read a specific length of data.
// 3) Read up to a particular terminator.
NSUInteger bytesToCopy;
if (currentRead->term != nil)
{
// Read type #3 - read up to a terminator
bytesToCopy = [currentRead readLengthForTermWithPreBuffer:partialReadBuffer found:&done];
}
else
{
// Read type #1 or #2
bytesToCopy = [currentRead readLengthForNonTermWithHint:partialReadBufferLength];
}
// Make sure we have enough room in the buffer for our read.
[currentRead ensureCapacityForAdditionalDataOfLength:bytesToCopy];
// Copy bytes from prebuffer into packet buffer
uint8_t *buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset +
currentRead->bytesDone;
memcpy(buffer, [partialReadBuffer bytes], bytesToCopy);
// Remove the copied bytes from the partial read buffer
[partialReadBuffer replaceBytesInRange:NSMakeRange(0, bytesToCopy) withBytes:NULL length:0];
partialReadBufferLength -= bytesToCopy;
LogVerbose(@"copied(%lu) partialReadBufferLength(%lu)", bytesToCopy, partialReadBufferLength);
// Update totals
currentRead->bytesDone += bytesToCopy;
totalBytesReadForCurrentRead += bytesToCopy;
// Check to see if the read operation is done
if (currentRead->readLength > 0)
{
// Read type #2 - read a specific length of data
done = (currentRead->bytesDone == currentRead->readLength);
}
else if (currentRead->term != nil)
{
// Read type #3 - read up to a terminator
// Our 'done' variable was updated via the readLengthForTermWithPreBuffer:found: method
if (!done && currentRead->maxLength > 0)
{
// We're not done and there's a set maxLength.
// Have we reached that maxLength yet?
if (currentRead->bytesDone >= currentRead->maxLength)
{
error = [self readMaxedOutError];
}
}
}
else
{
// Read type #1 - read all available data
//
// We're done as soon as
// - we've read all available data (in prebuffer and socket)
// - we've read the maxLength of read packet.
done = ((currentRead->maxLength > 0) && (currentRead->bytesDone == currentRead->maxLength));
}
}
//
// STEP 2 - READ FROM SOCKET
//
if (!done && !waiting && !socketEOF && !error && hasBytesAvailable)
{
NSAssert((partialReadBufferLength == 0), @"Invalid logic");
// There are 3 types of read packets:
//
// 1) Read all available data.
// 2) Read a specific length of data.
// 3) Read up to a particular terminator.
BOOL readIntoPartialReadBuffer = NO;
NSUInteger bytesToRead;
if ([self usingCFStream])
{
// Since Apple has neglected to make SecureTransport available on iOS,
// we are relegated to using the slower, less powerful, RunLoop based CFStream API.
//
// This API doesn't tell us how much data is available on the socket to be read.
// If we had that information we could optimize our memory allocations, and sys calls.
//
// But alas...
// So we do it old school, and just read as much data from the socket as we can.
NSUInteger defaultReadLength = (1024 * 32);
bytesToRead = [currentRead optimalReadLengthWithDefault:defaultReadLength
shouldPreBuffer:&readIntoPartialReadBuffer];
}
else
{
if (currentRead->term != nil)
{
// Read type #3 - read up to a terminator
bytesToRead = [currentRead readLengthForTermWithHint:estimatedBytesAvailable
shouldPreBuffer:&readIntoPartialReadBuffer];
}
else
{
// Read type #1 or #2
bytesToRead = [currentRead readLengthForNonTermWithHint:estimatedBytesAvailable];
}
}
if (bytesToRead > SIZE_MAX) // NSUInteger may be bigger than size_t (read param 3)
{
bytesToRead = SIZE_MAX;
}
// Make sure we have enough room in the buffer for our read.
//
// We are either reading directly into the currentRead->buffer,
// or we're reading into the temporary partialReadBuffer.
uint8_t *buffer;
if (readIntoPartialReadBuffer)
{
if (bytesToRead > partialReadBufferLength)
{
[partialReadBuffer setLength:bytesToRead];
}
buffer = [partialReadBuffer mutableBytes];
}
else
{
[currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead];
buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset + currentRead->bytesDone;
}
// Read data into buffer
size_t bytesRead = 0;
if (flags & kSocketSecure)
{
#if TARGET_OS_IPHONE
CFIndex result = CFReadStreamRead(readStream, buffer, (CFIndex)bytesToRead);
LogVerbose(@"CFReadStreamRead(): result = %i", (int)result);
if (result < 0)
{
error = [NSMakeCollectable(CFReadStreamCopyError(readStream)) autorelease];
if (readIntoPartialReadBuffer)
[partialReadBuffer setLength:0];
}
else if (result == 0)
{
socketEOF = YES;
if (readIntoPartialReadBuffer)
[partialReadBuffer setLength:0];
}
else
{
waiting = YES;
bytesRead = (size_t)result;
}
// We only know how many decrypted bytes were read.
// The actual number of bytes read was likely more due to the overhead of the encryption.
// So we reset our flag, and rely on the next callback to alert us of more data.
flags &= ~kSecureSocketHasBytesAvailable;
#else
OSStatus result = SSLRead(sslContext, buffer, (size_t)bytesToRead, &bytesRead);
LogVerbose(@"read from secure socket = %u", (unsigned)bytesRead);
if (result != noErr)
{
if (result == errSSLWouldBlock)
waiting = YES;
else
error = [self sslError:result];
// It's possible that bytesRead > 0, yet the result is errSSLWouldBlock.
// This happens when the SSLRead function is able to read some data,
// but not the entire amount we requested.
if (bytesRead <= 0)
{
bytesRead = 0;
if (readIntoPartialReadBuffer)
[partialReadBuffer setLength:0];
}
}
// Do not modify socketFDBytesAvailable.
// It will be updated via the SSLReadFunction().
#endif
}
else
{
int socketFD = (socket4FD == SOCKET_NULL) ? socket6FD : socket4FD;
ssize_t result = read(socketFD, buffer, (size_t)bytesToRead);
LogVerbose(@"read from socket = %i", (int)result);
if (result < 0)
{
if (errno == EWOULDBLOCK)
waiting = YES;
else
error = [self errnoErrorWithReason:@"Error in read() function"];
socketFDBytesAvailable = 0;
if (readIntoPartialReadBuffer)
[partialReadBuffer setLength:0];
}
else if (result == 0)
{
socketEOF = YES;
socketFDBytesAvailable = 0;
if (readIntoPartialReadBuffer)
[partialReadBuffer setLength:0];
}
else
{
bytesRead = result;
if (socketFDBytesAvailable <= bytesRead)
socketFDBytesAvailable = 0;
else
socketFDBytesAvailable -= bytesRead;
if (socketFDBytesAvailable == 0)
{
waiting = YES;
}
}
}
if (bytesRead > 0)
{
// Check to see if the read operation is done
if (currentRead->readLength > 0)
{
// Read type #2 - read a specific length of data
//
// Note: We should never be using a prebuffer when we're reading a specific length of data.
NSAssert(readIntoPartialReadBuffer == NO, @"Invalid logic");
currentRead->bytesDone += bytesRead;
totalBytesReadForCurrentRead += bytesRead;
done = (currentRead->bytesDone == currentRead->readLength);
}
else if (currentRead->term != nil)
{
// Read type #3 - read up to a terminator
if (readIntoPartialReadBuffer)
{
// We just read a big chunk of data into the partialReadBuffer.
// Search for the terminating sequence.
//
// Note: We are depending upon [partialReadBuffer length] to tell us how much data is
// available in the partialReadBuffer. So we need to be sure this matches how many bytes
// have actually been read into said buffer.
[partialReadBuffer setLength:bytesRead];
bytesToRead = [currentRead readLengthForTermWithPreBuffer:partialReadBuffer found:&done];
// Ensure there's room on the read packet's buffer
[currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead];
// Copy bytes from prebuffer into read buffer
uint8_t *preBuf = [partialReadBuffer mutableBytes];
uint8_t *readBuf = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset
+ currentRead->bytesDone;
memcpy(readBuf, preBuf, bytesToRead);
// Remove the copied bytes from the prebuffer
[partialReadBuffer replaceBytesInRange:NSMakeRange(0, bytesToRead) withBytes:NULL length:0];
// Update totals
currentRead->bytesDone += bytesToRead;
totalBytesReadForCurrentRead += bytesToRead;
// Our 'done' variable was updated via the readLengthForTermWithPreBuffer:found: method above
}
else
{
// We just read a big chunk of data directly into the packet's buffer.
// We need to move any overflow into the prebuffer.
NSInteger overflow = [currentRead searchForTermAfterPreBuffering:bytesRead];
if (overflow == 0)
{
// Perfect match!
// Every byte we read stays in the read buffer,
// and the last byte we read was the last byte of the term.
currentRead->bytesDone += bytesRead;
totalBytesReadForCurrentRead += bytesRead;
done = YES;
}
else if (overflow > 0)
{
// The term was found within the data that we read,
// and there are extra bytes that extend past the end of the term.
// We need to move these excess bytes out of the read packet and into the prebuffer.
NSInteger underflow = bytesRead - overflow;
// Copy excess data into partialReadBuffer
void *overflowBuffer = buffer + currentRead->bytesDone + underflow;
[partialReadBuffer appendBytes:overflowBuffer length:overflow];
// Note: The completeCurrentRead method will trim the buffer for us.
currentRead->bytesDone += underflow;
totalBytesReadForCurrentRead += underflow;
done = YES;
}
else
{
// The term was not found within the data that we read.
currentRead->bytesDone += bytesRead;
totalBytesReadForCurrentRead += bytesRead;
done = NO;
}
}
if (!done && currentRead->maxLength > 0)
{
// We're not done and there's a set maxLength.
// Have we reached that maxLength yet?
if (currentRead->bytesDone >= currentRead->maxLength)
{
error = [self readMaxedOutError];
}
}
}
else
{
// Read type #1 - read all available data
if (readIntoPartialReadBuffer)
{
// We just read a chunk of data into the partialReadBuffer.
// Copy the data into the read packet.
//
// Recall that we didn't read directly into the packet's buffer to avoid
// over-allocating memory since we had no clue how much data was available to be read.
//
// Note: We are depending upon [partialReadBuffer length] to tell us how much data is
// available in the partialReadBuffer. So we need to be sure this matches how many bytes
// have actually been read into said buffer.
[partialReadBuffer setLength:bytesRead];
// Ensure there's room on the read packet's buffer
[currentRead ensureCapacityForAdditionalDataOfLength:bytesRead];
// Copy bytes from prebuffer into read buffer
uint8_t *preBuf = [partialReadBuffer mutableBytes];
uint8_t *readBuf = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset
+ currentRead->bytesDone;
memcpy(readBuf, preBuf, bytesRead);
// Remove the copied bytes from the prebuffer
[partialReadBuffer replaceBytesInRange:NSMakeRange(0, bytesRead) withBytes:NULL length:0];
// Update totals
currentRead->bytesDone += bytesRead;
totalBytesReadForCurrentRead += bytesRead;
}
else
{
currentRead->bytesDone += bytesRead;
totalBytesReadForCurrentRead += bytesRead;
}
done = YES;
}
} // if (bytesRead > 0)
} // if (!done && !error && hasBytesAvailable)
if (!done && currentRead->readLength == 0 && currentRead->term == nil)
{
// Read type #1 - read all available data
//
// We might arrive here if we read data from the prebuffer but not from the socket.
done = (totalBytesReadForCurrentRead > 0);
}
// Only one of the following can possibly be true:
//
// - waiting
// - socketEOF
// - socketError
// - maxoutError
//
// They may all be false.
// One of the above may be true even if done is true.
// This might be the case if we completed read type #1 via data from the prebuffer.
if (done)
{
[self completeCurrentRead];
if (!error && (!socketEOF || partialReadBufferLength > 0))
{
[self maybeDequeueRead];
}
}
else if (totalBytesReadForCurrentRead > 0)
{
// We're not done read type #2 or #3 yet, but we have read in some bytes
if (delegateQueue && [delegate respondsToSelector:@selector(socket:didReadPartialDataOfLength:tag:)])
{
id theDelegate = delegate;
GCDAsyncReadPacket *theRead = currentRead;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socket:self didReadPartialDataOfLength:totalBytesReadForCurrentRead tag:theRead->tag];
[pool drain];
});
}
}
// Check for errors
if (error)
{
[self closeWithError:error];
}
else if (socketEOF)
{
[self doReadEOF];
}
else if (waiting)
{
if (![self usingCFStream])
{
// Monitor the socket for readability (if we're not already doing so)
[self resumeReadSource];
}
}
// Do not add any code here without first adding return statements in the error cases above.
}
- (void)doReadEOF
{
LogTrace();
// This method may be called more than once.
// If the EOF is read while there is still data in the partialReadBuffer,
// then this method may be called continually after invocations of doReadData to see if it's time to disconnect.
flags |= kSocketHasReadEOF;
if (flags & kSocketSecure)
{
// If the SSL layer has any buffered data, flush it into the partialReadBuffer now.
[self flushSSLBuffers];
}
BOOL shouldDisconnect;
NSError *error = nil;
if ((flags & kStartingReadTLS) || (flags & kStartingWriteTLS))
{
// We received an EOF during or prior to startTLS.
// The SSL/TLS handshake is now impossible, so this is an unrecoverable situation.
shouldDisconnect = YES;
#if !TARGET_OS_IPHONE
error = [self sslError:errSSLClosedAbort];
#endif
}
else if (flags & kReadStreamClosed)
{
// The partialReadBuffer has already been drained.
// The config allows half-duplex connections.
// We've previously checked the socket, and it appeared writeable.
// So we marked the read stream as closed and notified the delegate.
//
// As per the half-duplex contract, the socket will be closed when a write fails,
// or when the socket is manually closed.
shouldDisconnect = NO;
}
else if ([partialReadBuffer length] > 0)
{
LogVerbose(@"Socket reached EOF, but there is still data available in prebuffer");
// Although we won't be able to read any more data from the socket,
// there is existing data that has been prebuffered that we can read.
shouldDisconnect = NO;
}
else if (config & kAllowHalfDuplexConnection)
{
// We just received an EOF (end of file) from the socket's read stream.
// This means the remote end of the socket (the peer we're connected to)
// has explicitly stated that it will not be sending us any more data.
//
// Query the socket to see if it is still writeable. (Perhaps the peer will continue reading data from us)
int socketFD = (socket4FD == SOCKET_NULL) ? socket6FD : socket4FD;
struct pollfd pfd[1];
pfd[0].fd = socketFD;
pfd[0].events = POLLOUT;
pfd[0].revents = 0;
poll(pfd, 1, 0);
if (pfd[0].revents & POLLOUT)
{
// Socket appears to still be writeable
shouldDisconnect = NO;
flags |= kReadStreamClosed;
// Notify the delegate that we're going half-duplex
if (delegateQueue && [delegate respondsToSelector:@selector(socketDidCloseReadStream:)])
{
id theDelegate = delegate;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socketDidCloseReadStream:self];
[pool drain];
});
}
}
else
{
shouldDisconnect = YES;
}
}
else
{
shouldDisconnect = YES;
}
if (shouldDisconnect)
{
if (error == nil)
{
error = [self connectionClosedError];
}
[self closeWithError:error];
}
else
{
if (![self usingCFStream])
{
// Suspend the read source (if needed)
[self suspendReadSource];
}
}
}
- (void)completeCurrentRead
{
LogTrace();
NSAssert(currentRead, @"Trying to complete current read when there is no current read.");
NSData *result;
if (currentRead->bufferOwner)
{
// We created the buffer on behalf of the user.
// Trim our buffer to be the proper size.
[currentRead->buffer setLength:currentRead->bytesDone];
result = currentRead->buffer;
}
else
{
// We did NOT create the buffer.
// The buffer is owned by the caller.
// Only trim the buffer if we had to increase its size.
if ([currentRead->buffer length] > currentRead->originalBufferLength)
{
NSUInteger readSize = currentRead->startOffset + currentRead->bytesDone;
NSUInteger origSize = currentRead->originalBufferLength;
NSUInteger buffSize = MAX(readSize, origSize);
[currentRead->buffer setLength:buffSize];
}
uint8_t *buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset;
result = [NSData dataWithBytesNoCopy:buffer length:currentRead->bytesDone freeWhenDone:NO];
}
if (delegateQueue && [delegate respondsToSelector:@selector(socket:didReadData:withTag:)])
{
id theDelegate = delegate;
GCDAsyncReadPacket *theRead = currentRead;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socket:self didReadData:result withTag:theRead->tag];
[pool drain];
});
}
[self endCurrentRead];
}
- (void)endCurrentRead
{
if (readTimer)
{
dispatch_source_cancel(readTimer);
readTimer = NULL;
}
[currentRead release];
currentRead = nil;
}
- (void)setupReadTimerWithTimeout:(NSTimeInterval)timeout
{
if (timeout >= 0.0)
{
readTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue);
dispatch_source_set_event_handler(readTimer, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self doReadTimeout];
[pool drain];
});
dispatch_source_t theReadTimer = readTimer;
dispatch_source_set_cancel_handler(readTimer, ^{
LogVerbose(@"dispatch_release(readTimer)");
dispatch_release(theReadTimer);
});
dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC));
dispatch_source_set_timer(readTimer, tt, DISPATCH_TIME_FOREVER, 0);
dispatch_resume(readTimer);
}
}
- (void)doReadTimeout
{
// This is a little bit tricky.
// Ideally we'd like to synchronously query the delegate about a timeout extension.
// But if we do so synchronously we risk a possible deadlock.
// So instead we have to do so asynchronously, and callback to ourselves from within the delegate block.
flags |= kReadsPaused;
if (delegateQueue && [delegate respondsToSelector:@selector(socket:shouldTimeoutReadWithTag:elapsed:bytesDone:)])
{
id theDelegate = delegate;
GCDAsyncReadPacket *theRead = currentRead;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *delegatePool = [[NSAutoreleasePool alloc] init];
NSTimeInterval timeoutExtension = 0.0;
timeoutExtension = [theDelegate socket:self shouldTimeoutReadWithTag:theRead->tag
elapsed:theRead->timeout
bytesDone:theRead->bytesDone];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *callbackPool = [[NSAutoreleasePool alloc] init];
[self doReadTimeoutWithExtension:timeoutExtension];
[callbackPool drain];
});
[delegatePool drain];
});
}
else
{
[self doReadTimeoutWithExtension:0.0];
}
}
- (void)doReadTimeoutWithExtension:(NSTimeInterval)timeoutExtension
{
if (currentRead)
{
if (timeoutExtension > 0.0)
{
currentRead->timeout += timeoutExtension;
// Reschedule the timer
dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeoutExtension * NSEC_PER_SEC));
dispatch_source_set_timer(readTimer, tt, DISPATCH_TIME_FOREVER, 0);
// Unpause reads, and continue
flags &= ~kReadsPaused;
[self doReadData];
}
else
{
LogVerbose(@"ReadTimeout");
[self closeWithError:[self readTimeoutError]];
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Writing
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
if ([data length] == 0) return;
GCDAsyncWritePacket *packet = [[GCDAsyncWritePacket alloc] initWithData:data timeout:timeout tag:tag];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
LogTrace();
if ((flags & kSocketStarted) && !(flags & kForbidReadsWrites))
{
[writeQueue addObject:packet];
[self maybeDequeueWrite];
}
[pool drain];
});
// Do not rely on the block being run in order to release the packet,
// as the queue might get released without the block completing.
[packet release];
}
/**
* Conditionally starts a new write.
*
* It is called when:
* - a user requests a write
* - after a write request has finished (to handle the next request)
* - immediately after the socket opens to handle any pending requests
*
* This method also handles auto-disconnect post read/write completion.
**/
- (void)maybeDequeueWrite
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
// If we're not currently processing a write AND we have an available write stream
if ((currentWrite == nil) && (flags & kConnected))
{
if ([writeQueue count] > 0)
{
// Dequeue the next object in the write queue
currentWrite = [[writeQueue objectAtIndex:0] retain];
[writeQueue removeObjectAtIndex:0];
if ([currentWrite isKindOfClass:[GCDAsyncSpecialPacket class]])
{
LogVerbose(@"Dequeued GCDAsyncSpecialPacket");
// Attempt to start TLS
flags |= kStartingWriteTLS;
// This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set
[self maybeStartTLS];
}
else
{
LogVerbose(@"Dequeued GCDAsyncWritePacket");
// Setup write timer (if needed)
[self setupWriteTimerWithTimeout:currentWrite->timeout];
// Immediately write, if possible
[self doWriteData];
}
}
else if (flags & kDisconnectAfterWrites)
{
if (flags & kDisconnectAfterReads)
{
if (([readQueue count] == 0) && (currentRead == nil))
{
[self closeWithError:nil];
}
}
else
{
[self closeWithError:nil];
}
}
}
}
- (void)doWriteData
{
LogTrace();
// This method is called by the writeSource via the socketQueue
if ((currentWrite == nil) || (flags & kWritesPaused))
{
LogVerbose(@"No currentWrite or kWritesPaused");
// Unable to write at this time
if ([self usingCFStream])
{
// CFWriteStream only fires once when there is available data.
// It won't fire again until we've invoked CFWriteStreamWrite.
}
else
{
// If the writeSource is firing, we need to pause it
// or else it will continue to fire over and over again.
if (flags & kSocketCanAcceptBytes)
{
[self suspendWriteSource];
}
}
return;
}
if (!(flags & kSocketCanAcceptBytes))
{
LogVerbose(@"No space available to write...");
// No space available to write.
if (![self usingCFStream])
{
// Need to wait for writeSource to fire and notify us of
// available space in the socket's internal write buffer.
[self resumeWriteSource];
}
return;
}
if (flags & kStartingWriteTLS)
{
LogVerbose(@"Waiting for SSL/TLS handshake to complete");
// The writeQueue is waiting for SSL/TLS handshake to complete.
if (flags & kStartingReadTLS)
{
#if !TARGET_OS_IPHONE
// We are in the process of a SSL Handshake.
// We were waiting for available space in the socket's internal OS buffer to continue writing.
[self continueSSLHandshake];
#endif
}
else
{
// We are still waiting for the readQueue to drain and start the SSL/TLS process.
// We now know we can write to the socket.
if (![self usingCFStream])
{
// Suspend the write source or else it will continue to fire nonstop.
[self suspendWriteSource];
}
}
return;
}
// Note: This method is not called if theCurrentWrite is an GCDAsyncSpecialPacket (startTLS packet)
BOOL waiting = NO;
NSError *error = nil;
size_t bytesWritten = 0;
if (flags & kSocketSecure)
{
#if TARGET_OS_IPHONE
const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone;
NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone;
if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3)
{
bytesToWrite = SIZE_MAX;
}
CFIndex result = CFWriteStreamWrite(writeStream, buffer, (CFIndex)bytesToWrite);
LogVerbose(@"CFWriteStreamWrite(%lu) = %li", bytesToWrite, result);
if (result < 0)
{
error = [NSMakeCollectable(CFWriteStreamCopyError(writeStream)) autorelease];
}
else
{
bytesWritten = (size_t)result;
// We always set waiting to true in this scenario.
// CFStream may have altered our underlying socket to non-blocking.
// Thus if we attempt to write without a callback, we may end up blocking our queue.
waiting = YES;
}
#else
// We're going to use the SSLWrite function.
//
// OSStatus SSLWrite(SSLContextRef context, const void *data, size_t dataLength, size_t *processed)
//
// Parameters:
// context - An SSL session context reference.
// data - A pointer to the buffer of data to write.
// dataLength - The amount, in bytes, of data to write.
// processed - On return, the length, in bytes, of the data actually written.
//
// It sounds pretty straight-forward,
// but there are a few caveats you should be aware of.
//
// The SSLWrite method operates in a non-obvious (and rather annoying) manner.
// According to the documentation:
//
// Because you may configure the underlying connection to operate in a non-blocking manner,
// a write operation might return errSSLWouldBlock, indicating that less data than requested
// was actually transferred. In this case, you should repeat the call to SSLWrite until some
// other result is returned.
//
// This sounds perfect, but when our SSLWriteFunction returns errSSLWouldBlock,
// then the SSLWrite method returns (with the proper errSSLWouldBlock return value),
// but it sets bytesWritten to bytesToWrite !!
//
// In other words, if the SSLWrite function doesn't completely write all the data we tell it to,
// then it doesn't tell us how many bytes were actually written.
//
// You might be wondering:
// If the SSLWrite function doesn't tell us how many bytes were written,
// then how in the world are we supposed to update our parameters (buffer & bytesToWrite)
// for the next time we invoke SSLWrite?
//
// The answer is that SSLWrite cached all the data we told it to write,
// and it will push out that data next time we call SSLWrite.
// If we call SSLWrite with new data, it will push out the cached data first, and then the new data.
// If we call SSLWrite with empty data, then it will simply push out the cached data.
//
// For this purpose we're going to break large writes into a series of smaller writes.
// This allows us to report progress back to the delegate.
OSStatus result;
BOOL hasCachedDataToWrite = (sslWriteCachedLength > 0);
BOOL hasNewDataToWrite = YES;
if (hasCachedDataToWrite)
{
size_t processed = 0;
result = SSLWrite(sslContext, NULL, 0, &processed);
if (result == noErr)
{
bytesWritten = sslWriteCachedLength;
sslWriteCachedLength = 0;
if (currentWrite->bytesDone == [currentWrite->buffer length])
{
// We've written all data for the current write.
hasNewDataToWrite = NO;
}
}
else
{
if (result == errSSLWouldBlock)
{
waiting = YES;
}
else
{
error = [self sslError:result];
}
// Can't write any new data since we were unable to write the cached data.
hasNewDataToWrite = NO;
}
}
if (hasNewDataToWrite)
{
const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone + bytesWritten;
NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone - bytesWritten;
if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3)
{
bytesToWrite = SIZE_MAX;
}
size_t bytesRemaining = bytesToWrite;
BOOL keepLooping = YES;
while (keepLooping)
{
size_t sslBytesToWrite = MIN(bytesRemaining, 32768);
size_t sslBytesWritten = 0;
result = SSLWrite(sslContext, buffer, sslBytesToWrite, &sslBytesWritten);
if (result == noErr)
{
buffer += sslBytesWritten;
bytesWritten += sslBytesWritten;
bytesRemaining -= sslBytesWritten;
keepLooping = (bytesRemaining > 0);
}
else
{
if (result == errSSLWouldBlock)
{
waiting = YES;
sslWriteCachedLength = sslBytesToWrite;
}
else
{
error = [self sslError:result];
}
keepLooping = NO;
}
} // while (keepLooping)
} // if (hasNewDataToWrite)
#endif
}
else
{
int socketFD = (socket4FD == SOCKET_NULL) ? socket6FD : socket4FD;
const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone;
NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone;
if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3)
{
bytesToWrite = SIZE_MAX;
}
ssize_t result = write(socketFD, buffer, (size_t)bytesToWrite);
LogVerbose(@"wrote to socket = %zd", result);
// Check results
if (result < 0)
{
if (errno == EWOULDBLOCK)
{
waiting = YES;
}
else
{
error = [self errnoErrorWithReason:@"Error in write() function"];
}
}
else
{
bytesWritten = result;
}
}
// We're done with our writing.
// If we explictly ran into a situation where the socket told us there was no room in the buffer,
// then we immediately resume listening for notifications.
//
// We must do this before we dequeue another write,
// as that may in turn invoke this method again.
//
// Note that if CFStream is involved, it may have maliciously put our socket in blocking mode.
if (waiting)
{
flags &= ~kSocketCanAcceptBytes;
if (![self usingCFStream])
{
[self resumeWriteSource];
}
}
// Check our results
BOOL done = NO;
if (bytesWritten > 0)
{
// Update total amount read for the current write
currentWrite->bytesDone += bytesWritten;
LogVerbose(@"currentWrite->bytesDone = %lu", currentWrite->bytesDone);
// Is packet done?
done = (currentWrite->bytesDone == [currentWrite->buffer length]);
}
if (done)
{
[self completeCurrentWrite];
if (!error)
{
[self maybeDequeueWrite];
}
}
else
{
// We were unable to finish writing the data,
// so we're waiting for another callback to notify us of available space in the lower-level output buffer.
if (!waiting & !error)
{
// This would be the case if our write was able to accept some data, but not all of it.
flags &= ~kSocketCanAcceptBytes;
if (![self usingCFStream])
{
[self resumeWriteSource];
}
}
if (bytesWritten > 0)
{
// We're not done with the entire write, but we have written some bytes
if (delegateQueue && [delegate respondsToSelector:@selector(socket:didWritePartialDataOfLength:tag:)])
{
id theDelegate = delegate;
GCDAsyncWritePacket *theWrite = currentWrite;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socket:self didWritePartialDataOfLength:bytesWritten tag:theWrite->tag];
[pool drain];
});
}
}
}
// Check for errors
if (error)
{
[self closeWithError:[self errnoErrorWithReason:@"Error in write() function"]];
}
// Do not add any code here without first adding a return statement in the error case above.
}
- (void)completeCurrentWrite
{
LogTrace();
NSAssert(currentWrite, @"Trying to complete current write when there is no current write.");
if (delegateQueue && [delegate respondsToSelector:@selector(socket:didWriteDataWithTag:)])
{
id theDelegate = delegate;
GCDAsyncWritePacket *theWrite = currentWrite;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socket:self didWriteDataWithTag:theWrite->tag];
[pool drain];
});
}
[self endCurrentWrite];
}
- (void)endCurrentWrite
{
if (writeTimer)
{
dispatch_source_cancel(writeTimer);
writeTimer = NULL;
}
[currentWrite release];
currentWrite = nil;
}
- (void)setupWriteTimerWithTimeout:(NSTimeInterval)timeout
{
if (timeout >= 0.0)
{
writeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue);
dispatch_source_set_event_handler(writeTimer, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self doWriteTimeout];
[pool drain];
});
dispatch_source_t theWriteTimer = writeTimer;
dispatch_source_set_cancel_handler(writeTimer, ^{
LogVerbose(@"dispatch_release(writeTimer)");
dispatch_release(theWriteTimer);
});
dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC));
dispatch_source_set_timer(writeTimer, tt, DISPATCH_TIME_FOREVER, 0);
dispatch_resume(writeTimer);
}
}
- (void)doWriteTimeout
{
// This is a little bit tricky.
// Ideally we'd like to synchronously query the delegate about a timeout extension.
// But if we do so synchronously we risk a possible deadlock.
// So instead we have to do so asynchronously, and callback to ourselves from within the delegate block.
flags |= kWritesPaused;
if (delegateQueue && [delegate respondsToSelector:@selector(socket:shouldTimeoutWriteWithTag:elapsed:bytesDone:)])
{
id theDelegate = delegate;
GCDAsyncWritePacket *theWrite = currentWrite;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *delegatePool = [[NSAutoreleasePool alloc] init];
NSTimeInterval timeoutExtension = 0.0;
timeoutExtension = [theDelegate socket:self shouldTimeoutWriteWithTag:theWrite->tag
elapsed:theWrite->timeout
bytesDone:theWrite->bytesDone];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *callbackPool = [[NSAutoreleasePool alloc] init];
[self doWriteTimeoutWithExtension:timeoutExtension];
[callbackPool drain];
});
[delegatePool drain];
});
}
else
{
[self doWriteTimeoutWithExtension:0.0];
}
}
- (void)doWriteTimeoutWithExtension:(NSTimeInterval)timeoutExtension
{
if (currentWrite)
{
if (timeoutExtension > 0.0)
{
currentWrite->timeout += timeoutExtension;
// Reschedule the timer
dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeoutExtension * NSEC_PER_SEC));
dispatch_source_set_timer(writeTimer, tt, DISPATCH_TIME_FOREVER, 0);
// Unpause writes, and continue
flags &= ~kWritesPaused;
[self doWriteData];
}
else
{
LogVerbose(@"WriteTimeout");
[self closeWithError:[self writeTimeoutError]];
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Security
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)startTLS:(NSDictionary *)tlsSettings
{
LogTrace();
if (tlsSettings == nil)
{
// Passing nil/NULL to CFReadStreamSetProperty will appear to work the same as passing an empty dictionary,
// but causes problems if we later try to fetch the remote host's certificate.
//
// To be exact, it causes the following to return NULL instead of the normal result:
// CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates)
//
// So we use an empty dictionary instead, which works perfectly.
tlsSettings = [NSDictionary dictionary];
}
GCDAsyncSpecialPacket *packet = [[GCDAsyncSpecialPacket alloc] initWithTLSSettings:tlsSettings];
dispatch_async(socketQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ((flags & kSocketStarted) && !(flags & kQueuedTLS) && !(flags & kForbidReadsWrites))
{
[readQueue addObject:packet];
[writeQueue addObject:packet];
flags |= kQueuedTLS;
[self maybeDequeueRead];
[self maybeDequeueWrite];
}
[pool drain];
});
[packet release];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Security - Mac OS X
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if !TARGET_OS_IPHONE
- (OSStatus)sslReadWithBuffer:(void *)buffer length:(size_t *)bufferLength
{
LogVerbose(@"sslReadWithBuffer:%p length:%lu", buffer, (unsigned long)*bufferLength);
if ((socketFDBytesAvailable == 0) && ([sslReadBuffer length] == 0))
{
LogVerbose(@"%@ - No data available to read...", THIS_METHOD);
// No data available to read.
//
// Need to wait for readSource to fire and notify us of
// available data in the socket's internal read buffer.
[self resumeReadSource];
*bufferLength = 0;
return errSSLWouldBlock;
}
size_t totalBytesRead = 0;
size_t totalBytesLeftToBeRead = *bufferLength;
BOOL done = NO;
BOOL socketError = NO;
//
// STEP 1 : READ FROM SSL PRE BUFFER
//
NSUInteger sslReadBufferLength = [sslReadBuffer length];
if (sslReadBufferLength > 0)
{
LogVerbose(@"%@: Reading from SSL pre buffer...", THIS_METHOD);
size_t bytesToCopy;
if (sslReadBufferLength > totalBytesLeftToBeRead)
bytesToCopy = totalBytesLeftToBeRead;
else
bytesToCopy = (size_t)sslReadBufferLength;
LogVerbose(@"%@: Copying %zu bytes from sslReadBuffer", THIS_METHOD, bytesToCopy);
memcpy(buffer, [sslReadBuffer mutableBytes], bytesToCopy);
[sslReadBuffer replaceBytesInRange:NSMakeRange(0, bytesToCopy) withBytes:NULL length:0];
LogVerbose(@"%@: sslReadBuffer.length = %lu", THIS_METHOD, (unsigned long)[sslReadBuffer length]);
totalBytesRead += bytesToCopy;
totalBytesLeftToBeRead -= bytesToCopy;
done = (totalBytesLeftToBeRead == 0);
if (done) LogVerbose(@"%@: Complete", THIS_METHOD);
}
//
// STEP 2 : READ FROM SOCKET
//
if (!done && (socketFDBytesAvailable > 0))
{
LogVerbose(@"%@: Reading from socket...", THIS_METHOD);
int socketFD = (socket6FD == SOCKET_NULL) ? socket4FD : socket6FD;
BOOL readIntoPreBuffer;
size_t bytesToRead;
uint8_t *buf;
if (socketFDBytesAvailable > totalBytesLeftToBeRead)
{
// Read all available data from socket into sslReadBuffer.
// Then copy requested amount into dataBuffer.
LogVerbose(@"%@: Reading into sslReadBuffer...", THIS_METHOD);
if ([sslReadBuffer length] < socketFDBytesAvailable)
{
[sslReadBuffer setLength:socketFDBytesAvailable];
}
readIntoPreBuffer = YES;
bytesToRead = (size_t)socketFDBytesAvailable;
buf = [sslReadBuffer mutableBytes];
}
else
{
// Read available data from socket directly into dataBuffer.
LogVerbose(@"%@: Reading directly into dataBuffer...", THIS_METHOD);
readIntoPreBuffer = NO;
bytesToRead = totalBytesLeftToBeRead;
buf = (uint8_t *)buffer + totalBytesRead;
}
ssize_t result = read(socketFD, buf, bytesToRead);
LogVerbose(@"%@: read from socket = %zd", THIS_METHOD, result);
if (result < 0)
{
LogVerbose(@"%@: read errno = %i", THIS_METHOD, errno);
if (errno != EWOULDBLOCK)
{
socketError = YES;
}
socketFDBytesAvailable = 0;
if (readIntoPreBuffer)
{
[sslReadBuffer setLength:0];
}
}
else if (result == 0)
{
LogVerbose(@"%@: read EOF", THIS_METHOD);
socketError = YES;
socketFDBytesAvailable = 0;
if (readIntoPreBuffer)
{
[sslReadBuffer setLength:0];
}
}
else
{
size_t bytesReadFromSocket = result;
if (socketFDBytesAvailable > bytesReadFromSocket)
socketFDBytesAvailable -= bytesReadFromSocket;
else
socketFDBytesAvailable = 0;
if (readIntoPreBuffer)
{
size_t bytesToCopy = MIN(totalBytesLeftToBeRead, bytesReadFromSocket);
LogVerbose(@"%@: Copying %zu bytes out of sslReadBuffer", THIS_METHOD, bytesToCopy);
memcpy((uint8_t *)buffer + totalBytesRead, [sslReadBuffer bytes], bytesToCopy);
[sslReadBuffer setLength:bytesReadFromSocket];
[sslReadBuffer replaceBytesInRange:NSMakeRange(0, bytesToCopy) withBytes:NULL length:0];
totalBytesRead += bytesToCopy;
totalBytesLeftToBeRead -= bytesToCopy;
LogVerbose(@"%@: sslReadBuffer.length = %lu", THIS_METHOD, (unsigned long)[sslReadBuffer length]);
}
else
{
totalBytesRead += bytesReadFromSocket;
totalBytesLeftToBeRead -= bytesReadFromSocket;
}
done = (totalBytesLeftToBeRead == 0);
if (done) LogVerbose(@"%@: Complete", THIS_METHOD);
}
}
*bufferLength = totalBytesRead;
if (done)
return noErr;
if (socketError)
return errSSLClosedAbort;
return errSSLWouldBlock;
}
- (OSStatus)sslWriteWithBuffer:(const void *)buffer length:(size_t *)bufferLength
{
if (!(flags & kSocketCanAcceptBytes))
{
// Unable to write.
//
// Need to wait for writeSource to fire and notify us of
// available space in the socket's internal write buffer.
[self resumeWriteSource];
*bufferLength = 0;
return errSSLWouldBlock;
}
size_t bytesToWrite = *bufferLength;
size_t bytesWritten = 0;
BOOL done = NO;
BOOL socketError = NO;
int socketFD = (socket4FD == SOCKET_NULL) ? socket6FD : socket4FD;
ssize_t result = write(socketFD, buffer, bytesToWrite);
if (result < 0)
{
if (errno != EWOULDBLOCK)
{
socketError = YES;
}
flags &= ~kSocketCanAcceptBytes;
}
else if (result == 0)
{
flags &= ~kSocketCanAcceptBytes;
}
else
{
bytesWritten = result;
done = (bytesWritten == bytesToWrite);
}
*bufferLength = bytesWritten;
if (done)
return noErr;
if (socketError)
return errSSLClosedAbort;
return errSSLWouldBlock;
}
static OSStatus SSLReadFunction(SSLConnectionRef connection, void *data, size_t *dataLength)
{
GCDAsyncSocket *asyncSocket = (GCDAsyncSocket *)connection;
NSCAssert(dispatch_get_current_queue() == asyncSocket->socketQueue, @"What the deuce?");
return [asyncSocket sslReadWithBuffer:data length:dataLength];
}
static OSStatus SSLWriteFunction(SSLConnectionRef connection, const void *data, size_t *dataLength)
{
GCDAsyncSocket *asyncSocket = (GCDAsyncSocket *)connection;
NSCAssert(dispatch_get_current_queue() == asyncSocket->socketQueue, @"What the deuce?");
return [asyncSocket sslWriteWithBuffer:data length:dataLength];
}
- (void)maybeStartTLS
{
LogTrace();
// We can't start TLS until:
// - All queued reads prior to the user calling startTLS are complete
// - All queued writes prior to the user calling startTLS are complete
//
// We'll know these conditions are met when both kStartingReadTLS and kStartingWriteTLS are set
if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS))
{
LogVerbose(@"Starting TLS...");
OSStatus status;
GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead;
NSDictionary *tlsSettings = tlsPacket->tlsSettings;
// Create SSLContext, and setup IO callbacks and connection ref
BOOL isServer = [[tlsSettings objectForKey:(NSString *)kCFStreamSSLIsServer] boolValue];
status = SSLNewContext(isServer, &sslContext);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLNewContext"]];
return;
}
status = SSLSetIOFuncs(sslContext, &SSLReadFunction, &SSLWriteFunction);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetIOFuncs"]];
return;
}
status = SSLSetConnection(sslContext, (SSLConnectionRef)self);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetConnection"]];
return;
}
// Configure SSLContext from given settings
//
// Checklist:
// 1. kCFStreamSSLPeerName
// 2. kCFStreamSSLAllowsAnyRoot
// 3. kCFStreamSSLAllowsExpiredRoots
// 4. kCFStreamSSLValidatesCertificateChain
// 5. kCFStreamSSLAllowsExpiredCertificates
// 6. kCFStreamSSLCertificates
// 7. kCFStreamSSLLevel
// 8. GCDAsyncSocketSSLCipherSuites
// 9. GCDAsyncSocketSSLDiffieHellmanParameters
id value;
// 1. kCFStreamSSLPeerName
value = [tlsSettings objectForKey:(NSString *)kCFStreamSSLPeerName];
if ([value isKindOfClass:[NSString class]])
{
NSString *peerName = (NSString *)value;
const char *peer = [peerName UTF8String];
size_t peerLen = strlen(peer);
status = SSLSetPeerDomainName(sslContext, peer, peerLen);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetPeerDomainName"]];
return;
}
}
// 2. kCFStreamSSLAllowsAnyRoot
value = [tlsSettings objectForKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
if (value)
{
BOOL allowsAnyRoot = [value boolValue];
status = SSLSetAllowsAnyRoot(sslContext, allowsAnyRoot);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetAllowsAnyRoot"]];
return;
}
}
// 3. kCFStreamSSLAllowsExpiredRoots
value = [tlsSettings objectForKey:(NSString *)kCFStreamSSLAllowsExpiredRoots];
if (value)
{
BOOL allowsExpiredRoots = [value boolValue];
status = SSLSetAllowsExpiredRoots(sslContext, allowsExpiredRoots);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetAllowsExpiredRoots"]];
return;
}
}
// 4. kCFStreamSSLValidatesCertificateChain
value = [tlsSettings objectForKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
if (value)
{
BOOL validatesCertChain = [value boolValue];
status = SSLSetEnableCertVerify(sslContext, validatesCertChain);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetEnableCertVerify"]];
return;
}
}
// 5. kCFStreamSSLAllowsExpiredCertificates
value = [tlsSettings objectForKey:(NSString *)kCFStreamSSLAllowsExpiredCertificates];
if (value)
{
BOOL allowsExpiredCerts = [value boolValue];
status = SSLSetAllowsExpiredCerts(sslContext, allowsExpiredCerts);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetAllowsExpiredCerts"]];
return;
}
}
// 6. kCFStreamSSLCertificates
value = [tlsSettings objectForKey:(NSString *)kCFStreamSSLCertificates];
if (value)
{
CFArrayRef certs = (CFArrayRef)value;
status = SSLSetCertificate(sslContext, certs);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetCertificate"]];
return;
}
}
// 7. kCFStreamSSLLevel
value = [tlsSettings objectForKey:(NSString *)kCFStreamSSLLevel];
if (value)
{
NSString *sslLevel = (NSString *)value;
if ([sslLevel isEqualToString:(NSString *)kCFStreamSocketSecurityLevelSSLv2])
{
// kCFStreamSocketSecurityLevelSSLv2:
//
// Specifies that SSL version 2 be set as the security protocol.
SSLSetProtocolVersionEnabled(sslContext, kSSLProtocolAll, NO);
SSLSetProtocolVersionEnabled(sslContext, kSSLProtocol2, YES);
}
else if ([sslLevel isEqualToString:(NSString *)kCFStreamSocketSecurityLevelSSLv3])
{
// kCFStreamSocketSecurityLevelSSLv3:
//
// Specifies that SSL version 3 be set as the security protocol.
// If SSL version 3 is not available, specifies that SSL version 2 be set as the security protocol.
SSLSetProtocolVersionEnabled(sslContext, kSSLProtocolAll, NO);
SSLSetProtocolVersionEnabled(sslContext, kSSLProtocol2, YES);
SSLSetProtocolVersionEnabled(sslContext, kSSLProtocol3, YES);
}
else if ([sslLevel isEqualToString:(NSString *)kCFStreamSocketSecurityLevelTLSv1])
{
// kCFStreamSocketSecurityLevelTLSv1:
//
// Specifies that TLS version 1 be set as the security protocol.
SSLSetProtocolVersionEnabled(sslContext, kSSLProtocolAll, NO);
SSLSetProtocolVersionEnabled(sslContext, kTLSProtocol1, YES);
}
else if ([sslLevel isEqualToString:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL])
{
// kCFStreamSocketSecurityLevelNegotiatedSSL:
//
// Specifies that the highest level security protocol that can be negotiated be used.
SSLSetProtocolVersionEnabled(sslContext, kSSLProtocolAll, YES);
}
}
// 8. GCDAsyncSocketSSLCipherSuites
value = [tlsSettings objectForKey:GCDAsyncSocketSSLCipherSuites];
if (value)
{
NSArray *cipherSuites = (NSArray *)value;
NSUInteger numberCiphers = [cipherSuites count];
SSLCipherSuite ciphers[numberCiphers];
NSUInteger cipherIndex;
for (cipherIndex = 0; cipherIndex < numberCiphers; cipherIndex++)
{
NSNumber *cipherObject = [cipherSuites objectAtIndex:cipherIndex];
ciphers[cipherIndex] = [cipherObject shortValue];
}
status = SSLSetEnabledCiphers(sslContext, ciphers, numberCiphers);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetEnabledCiphers"]];
return;
}
}
// 9. GCDAsyncSocketSSLDiffieHellmanParameters
value = [tlsSettings objectForKey:GCDAsyncSocketSSLDiffieHellmanParameters];
if (value)
{
NSData *diffieHellmanData = (NSData *)value;
status = SSLSetDiffieHellmanParams(sslContext, [diffieHellmanData bytes], [diffieHellmanData length]);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetDiffieHellmanParams"]];
return;
}
}
// Setup the sslReadBuffer
//
// If there is any data in the partialReadBuffer,
// this needs to be moved into the sslReadBuffer,
// as this data is now part of the secure read stream.
sslReadBuffer = [[NSMutableData alloc] init];
if ([partialReadBuffer length] > 0)
{
[sslReadBuffer appendData:partialReadBuffer];
[partialReadBuffer setLength:0];
}
// Start the SSL Handshake process
[self continueSSLHandshake];
}
}
- (void)continueSSLHandshake
{
LogTrace();
// If the return value is noErr, the session is ready for normal secure communication.
// If the return value is errSSLWouldBlock, the SSLHandshake function must be called again.
// Otherwise, the return value indicates an error code.
OSStatus status = SSLHandshake(sslContext);
if (status == noErr)
{
LogVerbose(@"SSLHandshake complete");
flags &= ~kStartingReadTLS;
flags &= ~kStartingWriteTLS;
flags |= kSocketSecure;
if (delegateQueue && [delegate respondsToSelector:@selector(socketDidSecure:)])
{
id theDelegate = delegate;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socketDidSecure:self];
[pool drain];
});
}
[self endCurrentRead];
[self endCurrentWrite];
[self maybeDequeueRead];
[self maybeDequeueWrite];
}
else if (status == errSSLWouldBlock)
{
LogVerbose(@"SSLHandshake continues...");
// Handshake continues...
//
// This method will be called again from doReadData or doWriteData.
}
else
{
[self closeWithError:[self sslError:status]];
}
}
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Security - iOS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if TARGET_OS_IPHONE
- (void)finishSSLHandshake
{
LogTrace();
if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS))
{
flags &= ~kStartingReadTLS;
flags &= ~kStartingWriteTLS;
flags |= kSocketSecure;
if (delegateQueue && [delegate respondsToSelector:@selector(socketDidSecure:)])
{
id theDelegate = delegate;
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[theDelegate socketDidSecure:self];
[pool release];
});
}
[self endCurrentRead];
[self endCurrentWrite];
[self maybeDequeueRead];
[self maybeDequeueWrite];
}
}
- (void)abortSSLHandshake:(NSError *)error
{
LogTrace();
if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS))
{
flags &= ~kStartingReadTLS;
flags &= ~kStartingWriteTLS;
[self closeWithError:error];
}
}
- (void)maybeStartTLS
{
LogTrace();
// We can't start TLS until:
// - All queued reads prior to the user calling startTLS are complete
// - All queued writes prior to the user calling startTLS are complete
//
// We'll know these conditions are met when both kStartingReadTLS and kStartingWriteTLS are set
if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS))
{
LogVerbose(@"Starting TLS...");
if ([partialReadBuffer length] > 0)
{
NSString *msg = @"Invalid TLS transition. Handshake has already been read from socket.";
[self closeWithError:[self otherError:msg]];
return;
}
[self suspendReadSource];
[self suspendWriteSource];
socketFDBytesAvailable = 0;
flags &= ~kSocketCanAcceptBytes;
flags &= ~kSecureSocketHasBytesAvailable;
if (![self createReadAndWriteStream])
{
[self closeWithError:[self otherError:@"Error in CFStreamCreatePairWithSocket"]];
return;
}
if (![self registerForStreamCallbacksIncludingReadWrite:YES])
{
[self closeWithError:[self otherError:@"Error in CFStreamSetClient"]];
return;
}
if (![self addStreamsToRunLoop])
{
[self closeWithError:[self otherError:@"Error in CFStreamScheduleWithRunLoop"]];
return;
}
NSAssert([currentRead isKindOfClass:[GCDAsyncSpecialPacket class]], @"Invalid read packet for startTLS");
NSAssert([currentWrite isKindOfClass:[GCDAsyncSpecialPacket class]], @"Invalid write packet for startTLS");
GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead;
NSDictionary *tlsSettings = tlsPacket->tlsSettings;
// Getting an error concerning kCFStreamPropertySSLSettings ?
// You need to add the CFNetwork framework to your iOS application.
BOOL r1 = CFReadStreamSetProperty(readStream, kCFStreamPropertySSLSettings, (CFDictionaryRef)tlsSettings);
BOOL r2 = CFWriteStreamSetProperty(writeStream, kCFStreamPropertySSLSettings, (CFDictionaryRef)tlsSettings);
// For some reason, starting around the time of iOS 4.3,
// the first call to set the kCFStreamPropertySSLSettings will return true,
// but the second will return false.
//
// Order doesn't seem to matter.
// So you could call CFReadStreamSetProperty and then CFWriteStreamSetProperty, or you could reverse the order.
// Either way, the first call will return true, and the second returns false.
//
// Interestingly, this doesn't seem to affect anything.
// Which is not altogether unusual, as the documentation seems to suggest that (for many settings)
// setting it on one side of the stream automatically sets it for the other side of the stream.
//
// Although there isn't anything in the documentation to suggest that the second attempt would fail.
//
// Furthermore, this only seems to affect streams that are negotiating a security upgrade.
// In other words, the socket gets connected, there is some back-and-forth communication over the unsecure
// connection, and then a startTLS is issued.
// So this mostly affects newer protocols (XMPP, IMAP) as opposed to older protocols (HTTPS).
if (!r1 && !r2) // Yes, the && is correct - workaround for apple bug.
{
[self closeWithError:[self otherError:@"Error in CFStreamSetProperty"]];
return;
}
if (![self openStreams])
{
[self closeWithError:[self otherError:@"Error in CFStreamOpen"]];
return;
}
LogVerbose(@"Waiting for SSL Handshake to complete...");
}
}
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark CFStream
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if TARGET_OS_IPHONE
+ (void)startListenerThreadIfNeeded
{
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
listenerThread = [[NSThread alloc] initWithTarget:self
selector:@selector(listenerThread)
object:nil];
[listenerThread start];
});
}
+ (void)listenerThread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
LogInfo(@"ListenerThread: Started");
// We can't run the run loop unless it has an associated input source or a timer.
// So we'll just create a timer that will never fire - unless the server runs for 10,000 years.
[NSTimer scheduledTimerWithTimeInterval:DBL_MAX target:self selector:@selector(ignore:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] run];
LogInfo(@"ListenerThread: Stopped");
[pool release];
}
+ (void)addStreamListener:(GCDAsyncSocket *)asyncSocket
{
LogTrace();
NSAssert([NSThread currentThread] == listenerThread, @"Invoked on wrong thread");
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
if (asyncSocket->readStream)
CFReadStreamScheduleWithRunLoop(asyncSocket->readStream, runLoop, kCFRunLoopDefaultMode);
if (asyncSocket->writeStream)
CFWriteStreamScheduleWithRunLoop(asyncSocket->writeStream, runLoop, kCFRunLoopDefaultMode);
}
+ (void)removeStreamListener:(GCDAsyncSocket *)asyncSocket
{
LogTrace();
NSAssert([NSThread currentThread] == listenerThread, @"Invoked on wrong thread");
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
if (asyncSocket->readStream)
CFReadStreamUnscheduleFromRunLoop(asyncSocket->readStream, runLoop, kCFRunLoopDefaultMode);
if (asyncSocket->writeStream)
CFWriteStreamUnscheduleFromRunLoop(asyncSocket->writeStream, runLoop, kCFRunLoopDefaultMode);
}
static void CFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type, void *pInfo)
{
GCDAsyncSocket *asyncSocket = [(GCDAsyncSocket *)pInfo retain];
switch(type)
{
case kCFStreamEventHasBytesAvailable:
{
dispatch_async(asyncSocket->socketQueue, ^{
LogCVerbose(@"CFReadStreamCallback - HasBytesAvailable");
if (asyncSocket->readStream != stream)
return_from_block;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
{
asyncSocket->flags |= kSecureSocketHasBytesAvailable;
[asyncSocket finishSSLHandshake];
}
else
{
asyncSocket->flags |= kSecureSocketHasBytesAvailable;
[asyncSocket doReadData];
}
[pool release];
});
break;
}
default:
{
NSError *error = NSMakeCollectable(CFReadStreamCopyError(stream));
if (error == nil && type == kCFStreamEventEndEncountered)
{
error = [[asyncSocket connectionClosedError] retain];
}
dispatch_async(asyncSocket->socketQueue, ^{
LogCVerbose(@"CFReadStreamCallback - Other");
if (asyncSocket->readStream != stream)
return_from_block;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
{
[asyncSocket abortSSLHandshake:error];
}
else
{
[asyncSocket closeWithError:error];
}
[pool release];
});
[error release];
break;
}
}
[asyncSocket release];
}
static void CFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType type, void *pInfo)
{
GCDAsyncSocket *asyncSocket = [(GCDAsyncSocket *)pInfo retain];
switch(type)
{
case kCFStreamEventCanAcceptBytes:
{
dispatch_async(asyncSocket->socketQueue, ^{
LogCVerbose(@"CFWriteStreamCallback - CanAcceptBytes");
if (asyncSocket->writeStream != stream)
return_from_block;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
{
asyncSocket->flags |= kSocketCanAcceptBytes;
[asyncSocket finishSSLHandshake];
}
else
{
asyncSocket->flags |= kSocketCanAcceptBytes;
[asyncSocket doWriteData];
}
[pool release];
});
break;
}
default:
{
NSError *error = NSMakeCollectable(CFWriteStreamCopyError(stream));
if (error == nil && type == kCFStreamEventEndEncountered)
{
error = [[asyncSocket connectionClosedError] retain];
}
dispatch_async(asyncSocket->socketQueue, ^{
LogCVerbose(@"CFWriteStreamCallback - Other");
if (asyncSocket->writeStream != stream)
return_from_block;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
{
[asyncSocket abortSSLHandshake:error];
}
else
{
[asyncSocket closeWithError:error];
}
[pool release];
});
[error release];
break;
}
}
[asyncSocket release];
}
- (BOOL)createReadAndWriteStream
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
if (readStream || writeStream)
{
// Streams already created
return YES;
}
int socketFD = (socket6FD == SOCKET_NULL) ? socket4FD : socket6FD;
if (socketFD == SOCKET_NULL)
{
// Cannot create streams without a file descriptor
return NO;
}
if (![self isConnected])
{
// Cannot create streams until file descriptor is connected
return NO;
}
LogVerbose(@"Creating read and write stream...");
CFStreamCreatePairWithSocket(NULL, (CFSocketNativeHandle)socketFD, &readStream, &writeStream);
// The kCFStreamPropertyShouldCloseNativeSocket property should be false by default (for our case).
// But let's not take any chances.
if (readStream)
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
if (writeStream)
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
if ((readStream == NULL) || (writeStream == NULL))
{
LogWarn(@"Unable to create read and write stream...");
if (readStream)
{
CFReadStreamClose(readStream);
CFRelease(readStream);
readStream = NULL;
}
if (writeStream)
{
CFWriteStreamClose(writeStream);
CFRelease(writeStream);
writeStream = NULL;
}
return NO;
}
return YES;
}
- (BOOL)registerForStreamCallbacksIncludingReadWrite:(BOOL)includeReadWrite
{
LogVerbose(@"%@ %@", THIS_METHOD, (includeReadWrite ? @"YES" : @"NO"));
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
streamContext.version = 0;
streamContext.info = self;
streamContext.retain = nil;
streamContext.release = nil;
streamContext.copyDescription = nil;
CFOptionFlags readStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if (includeReadWrite)
readStreamEvents |= kCFStreamEventHasBytesAvailable;
if (!CFReadStreamSetClient(readStream, readStreamEvents, &CFReadStreamCallback, &streamContext))
{
return NO;
}
CFOptionFlags writeStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if (includeReadWrite)
writeStreamEvents |= kCFStreamEventCanAcceptBytes;
if (!CFWriteStreamSetClient(writeStream, writeStreamEvents, &CFWriteStreamCallback, &streamContext))
{
return NO;
}
return YES;
}
- (BOOL)addStreamsToRunLoop
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
if (!(flags & kAddedStreamListener))
{
[[self class] startListenerThreadIfNeeded];
[[self class] performSelector:@selector(addStreamListener:)
onThread:listenerThread
withObject:self
waitUntilDone:YES];
flags |= kAddedStreamListener;
}
return YES;
}
- (void)removeStreamsFromRunLoop
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
if (flags & kAddedStreamListener)
{
[[self class] performSelector:@selector(removeStreamListener:)
onThread:listenerThread
withObject:self
waitUntilDone:YES];
flags &= ~kAddedStreamListener;
}
}
- (BOOL)openStreams
{
LogTrace();
NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");
NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
CFStreamStatus readStatus = CFReadStreamGetStatus(readStream);
CFStreamStatus writeStatus = CFWriteStreamGetStatus(writeStream);
if ((readStatus == kCFStreamStatusNotOpen) || (writeStatus == kCFStreamStatusNotOpen))
{
LogVerbose(@"Opening read and write stream...");
BOOL r1 = CFReadStreamOpen(readStream);
BOOL r2 = CFWriteStreamOpen(writeStream);
if (!r1 || !r2)
{
LogError(@"Error in CFStreamOpen");
return NO;
}
}
return YES;
}
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Advanced
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)performBlock:(dispatch_block_t)block
{
dispatch_sync(socketQueue, block);
}
- (int)socketFD
{
if (dispatch_get_current_queue() == socketQueue)
{
if (socket4FD != SOCKET_NULL)
return socket4FD;
else
return socket6FD;
}
else
{
return SOCKET_NULL;
}
}
- (int)socket4FD
{
if (dispatch_get_current_queue() == socketQueue)
return socket4FD;
else
return SOCKET_NULL;
}
- (int)socket6FD
{
if (dispatch_get_current_queue() == socketQueue)
return socket6FD;
else
return SOCKET_NULL;
}
#if TARGET_OS_IPHONE
- (CFReadStreamRef)readStream
{
if (dispatch_get_current_queue() == socketQueue)
{
if (readStream == NULL)
[self createReadAndWriteStream];
return readStream;
}
else
{
return NULL;
}
}
- (CFWriteStreamRef)writeStream
{
if (dispatch_get_current_queue() == socketQueue)
{
if (writeStream == NULL)
[self createReadAndWriteStream];
return writeStream;
}
else
{
return NULL;
}
}
- (BOOL)enableBackgroundingOnSocketWithCaveat:(BOOL)caveat
{
if (![self createReadAndWriteStream])
{
// Error occured creating streams (perhaps socket isn't open)
return NO;
}
BOOL r1, r2;
LogVerbose(@"Enabling backgrouding on socket");
r1 = CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
r2 = CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
if (!r1 || !r2)
{
LogError(@"Error setting voip type");
return NO;
}
if (!caveat)
{
if (![self openStreams])
{
return NO;
}
}
return YES;
}
- (BOOL)enableBackgroundingOnSocket
{
LogTrace();
if (dispatch_get_current_queue() == socketQueue)
{
return [self enableBackgroundingOnSocketWithCaveat:NO];
}
else
{
return NO;
}
}
- (BOOL)enableBackgroundingOnSocketWithCaveat // Deprecated in iOS 4.???
{
// This method was created as a workaround for a bug in iOS.
// Apple has since fixed this bug.
// I'm not entirely sure which version of iOS they fixed it in...
LogTrace();
if (dispatch_get_current_queue() == socketQueue)
{
return [self enableBackgroundingOnSocketWithCaveat:YES];
}
else
{
return NO;
}
}
#else
- (SSLContextRef)sslContext
{
if (dispatch_get_current_queue() == socketQueue)
return sslContext;
else
return NULL;
}
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Class Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ (NSString *)hostFromAddress4:(const struct sockaddr_in *)pSockaddr4
{
char addrBuf[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
{
addrBuf[0] = '\0';
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
+ (NSString *)hostFromAddress6:(const struct sockaddr_in6 *)pSockaddr6
{
char addrBuf[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
{
addrBuf[0] = '\0';
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
+ (uint16_t)portFromAddress4:(const struct sockaddr_in *)pSockaddr4
{
return ntohs(pSockaddr4->sin_port);
}
+ (uint16_t)portFromAddress6:(const struct sockaddr_in6 *)pSockaddr6
{
return ntohs(pSockaddr6->sin6_port);
}
+ (NSString *)hostFromAddress:(NSData *)address
{
NSString *host;
if ([self getHost:&host port:NULL fromAddress:address])
return host;
else
return nil;
}
+ (uint16_t)portFromAddress:(NSData *)address
{
uint16_t port;
if ([self getHost:NULL port:&port fromAddress:address])
return port;
else
return 0;
}
+ (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr fromAddress:(NSData *)address
{
if ([address length] >= sizeof(struct sockaddr))
{
const struct sockaddr *addrX = (const struct sockaddr *)[address bytes];
if (addrX->sa_family == AF_INET)
{
if ([address length] >= sizeof(struct sockaddr_in))
{
const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addrX;
if (hostPtr) *hostPtr = [self hostFromAddress4:addr4];
if (portPtr) *portPtr = [self portFromAddress4:addr4];
return YES;
}
}
else if (addrX->sa_family == AF_INET6)
{
if ([address length] >= sizeof(struct sockaddr_in6))
{
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addrX;
if (hostPtr) *hostPtr = [self hostFromAddress6:addr6];
if (portPtr) *portPtr = [self portFromAddress6:addr6];
return YES;
}
}
}
return NO;
}
+ (NSData *)CRLFData
{
return [NSData dataWithBytes:"\x0D\x0A" length:2];
}
+ (NSData *)CRData
{
return [NSData dataWithBytes:"\x0D" length:1];
}
+ (NSData *)LFData
{
return [NSData dataWithBytes:"\x0A" length:1];
}
+ (NSData *)ZeroData
{
return [NSData dataWithBytes:"" length:1];
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/GCDAsyncSocket.m
|
Objective-C
|
oos
| 182,835
|
//
// GCDAsyncSocket.h
//
// This class is in the public domain.
// Originally created by Robbie Hanson in Q3 2010.
// Updated and maintained by Deusty LLC and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import <Foundation/Foundation.h>
#import <Security/Security.h>
#import <dispatch/dispatch.h>
@class GCDAsyncReadPacket;
@class GCDAsyncWritePacket;
extern NSString *const GCDAsyncSocketException;
extern NSString *const GCDAsyncSocketErrorDomain;
#if !TARGET_OS_IPHONE
extern NSString *const GCDAsyncSocketSSLCipherSuites;
extern NSString *const GCDAsyncSocketSSLDiffieHellmanParameters;
#endif
enum GCDAsyncSocketError
{
GCDAsyncSocketNoError = 0, // Never used
GCDAsyncSocketBadConfigError, // Invalid configuration
GCDAsyncSocketBadParamError, // Invalid parameter was passed
GCDAsyncSocketConnectTimeoutError, // A connect operation timed out
GCDAsyncSocketReadTimeoutError, // A read operation timed out
GCDAsyncSocketWriteTimeoutError, // A write operation timed out
GCDAsyncSocketReadMaxedOutError, // Reached set maxLength without completing
GCDAsyncSocketClosedError, // The remote peer closed the connection
GCDAsyncSocketOtherError, // Description provided in userInfo
};
typedef enum GCDAsyncSocketError GCDAsyncSocketError;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface GCDAsyncSocket : NSObject
{
uint32_t flags;
uint16_t config;
id delegate;
dispatch_queue_t delegateQueue;
int socket4FD;
int socket6FD;
int connectIndex;
NSData * connectInterface4;
NSData * connectInterface6;
dispatch_queue_t socketQueue;
dispatch_source_t accept4Source;
dispatch_source_t accept6Source;
dispatch_source_t connectTimer;
dispatch_source_t readSource;
dispatch_source_t writeSource;
dispatch_source_t readTimer;
dispatch_source_t writeTimer;
NSMutableArray *readQueue;
NSMutableArray *writeQueue;
GCDAsyncReadPacket *currentRead;
GCDAsyncWritePacket *currentWrite;
unsigned long socketFDBytesAvailable;
NSMutableData *partialReadBuffer;
#if TARGET_OS_IPHONE
CFStreamClientContext streamContext;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
#else
SSLContextRef sslContext;
NSMutableData *sslReadBuffer;
size_t sslWriteCachedLength;
#endif
id userData;
}
/**
* GCDAsyncSocket uses the standard delegate paradigm,
* but executes all delegate callbacks on a given delegate dispatch queue.
* This allows for maximum concurrency, while at the same time providing easy thread safety.
*
* You MUST set a delegate AND delegate dispatch queue before attempting to
* use the socket, or you will get an error.
*
* The socket queue is optional.
* If you pass NULL, GCDAsyncSocket will automatically create it's own socket queue.
* If you choose to provide a socket queue, the socket queue must not be a concurrent queue.
*
* The delegate queue and socket queue can optionally be the same.
**/
- (id)init;
- (id)initWithSocketQueue:(dispatch_queue_t)sq;
- (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq;
- (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq;
#pragma mark Configuration
- (id)delegate;
- (void)setDelegate:(id)delegate;
- (void)synchronouslySetDelegate:(id)delegate;
- (dispatch_queue_t)delegateQueue;
- (void)setDelegateQueue:(dispatch_queue_t)delegateQueue;
- (void)synchronouslySetDelegateQueue:(dispatch_queue_t)delegateQueue;
- (void)getDelegate:(id *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr;
- (void)setDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
- (void)synchronouslySetDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
/**
* Traditionally sockets are not closed until the conversation is over.
* However, it is technically possible for the remote enpoint to close its write stream.
* Our socket would then be notified that there is no more data to be read,
* but our socket would still be writeable and the remote endpoint could continue to receive our data.
*
* The argument for this confusing functionality stems from the idea that a client could shut down its
* write stream after sending a request to the server, thus notifying the server there are to be no further requests.
* In practice, however, this technique did little to help server developers.
*
* To make matters worse, from a TCP perspective there is no way to tell the difference from a read stream close
* and a full socket close. They both result in the TCP stack receiving a FIN packet. The only way to tell
* is by continuing to write to the socket. If it was only a read stream close, then writes will continue to work.
* Otherwise an error will be occur shortly (when the remote end sends us a RST packet).
*
* In addition to the technical challenges and confusion, many high level socket/stream API's provide
* no support for dealing with the problem. If the read stream is closed, the API immediately declares the
* socket to be closed, and shuts down the write stream as well. In fact, this is what Apple's CFStream API does.
* It might sound like poor design at first, but in fact it simplifies development.
*
* The vast majority of the time if the read stream is closed it's because the remote endpoint closed its socket.
* Thus it actually makes sense to close the socket at this point.
* And in fact this is what most networking developers want and expect to happen.
* However, if you are writing a server that interacts with a plethora of clients,
* you might encounter a client that uses the discouraged technique of shutting down its write stream.
* If this is the case, you can set this property to NO,
* and make use of the socketDidCloseReadStream delegate method.
*
* The default value is YES.
**/
- (BOOL)autoDisconnectOnClosedReadStream;
- (void)setAutoDisconnectOnClosedReadStream:(BOOL)flag;
/**
* By default, both IPv4 and IPv6 are enabled.
*
* For accepting incoming connections, this means GCDAsyncSocket automatically supports both protocols,
* and can simulataneously accept incoming connections on either protocol.
*
* For outgoing connections, this means GCDAsyncSocket can connect to remote hosts running either protocol.
* If a DNS lookup returns only IPv4 results, GCDAsyncSocket will automatically use IPv4.
* If a DNS lookup returns only IPv6 results, GCDAsyncSocket will automatically use IPv6.
* If a DNS lookup returns both IPv4 and IPv6 results, the preferred protocol will be chosen.
* By default, the preferred protocol is IPv4, but may be configured as desired.
**/
- (BOOL)isIPv4Enabled;
- (void)setIPv4Enabled:(BOOL)flag;
- (BOOL)isIPv6Enabled;
- (void)setIPv6Enabled:(BOOL)flag;
- (BOOL)isIPv4PreferredOverIPv6;
- (void)setPreferIPv4OverIPv6:(BOOL)flag;
/**
* User data allows you to associate arbitrary information with the socket.
* This data is not used internally by socket in any way.
**/
- (id)userData;
- (void)setUserData:(id)arbitraryUserData;
#pragma mark Accepting
/**
* Tells the socket to begin listening and accepting connections on the given port.
* When a connection is accepted, a new instance of GCDAsyncSocket will be spawned to handle it,
* and the socket:didAcceptNewSocket: delegate method will be invoked.
*
* The socket will listen on all available interfaces (e.g. wifi, ethernet, etc)
**/
- (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr;
/**
* This method is the same as acceptOnPort:error: with the
* additional option of specifying which interface to listen on.
*
* For example, you could specify that the socket should only accept connections over ethernet,
* and not other interfaces such as wifi.
*
* The interface may be specified by name (e.g. "en1" or "lo0") or by IP address (e.g. "192.168.4.34").
* You may also use the special strings "localhost" or "loopback" to specify that
* the socket only accept connections from the local machine.
*
* You can see the list of interfaces via the command line utility "ifconfig",
* or programmatically via the getifaddrs() function.
*
* To accept connections on any interface pass nil, or simply use the acceptOnPort:error: method.
**/
- (BOOL)acceptOnInterface:(NSString *)interface port:(uint16_t)port error:(NSError **)errPtr;
#pragma mark Connecting
/**
* Connects to the given host and port.
*
* This method invokes connectToHost:onPort:viaInterface:withTimeout:error:
* and uses the default interface, and no timeout.
**/
- (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr;
/**
* Connects to the given host and port with an optional timeout.
*
* This method invokes connectToHost:onPort:viaInterface:withTimeout:error: and uses the default interface.
**/
- (BOOL)connectToHost:(NSString *)host
onPort:(uint16_t)port
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr;
/**
* Connects to the given host & port, via the optional interface, with an optional timeout.
*
* The host may be a domain name (e.g. "deusty.com") or an IP address string (e.g. "192.168.0.2").
* The host may also be the special strings "localhost" or "loopback" to specify connecting
* to a service on the local machine.
*
* The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
* The interface may also be used to specify the local port (see below).
*
* To not time out use a negative time interval.
*
* This method will return NO if an error is detected, and set the error pointer (if one was given).
* Possible errors would be a nil host, invalid interface, or socket is already connected.
*
* If no errors are detected, this method will start a background connect operation and immediately return YES.
* The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.
*
* Since this class supports queued reads and writes, you can immediately start reading and/or writing.
* All read/write operations will be queued, and upon socket connection,
* the operations will be dequeued and processed in order.
*
* The interface may optionally contain a port number at the end of the string, separated by a colon.
* This allows you to specify the local port that should be used for the outgoing connection. (read paragraph to end)
* To specify both interface and local port: "en1:8082" or "192.168.4.35:2424".
* To specify only local port: ":8082".
* Please note this is an advanced feature, and is somewhat hidden on purpose.
* You should understand that 99.999% of the time you should NOT specify the local port for an outgoing connection.
* If you think you need to, there is a very good chance you have a fundamental misunderstanding somewhere.
* Local ports do NOT need to match remote ports. In fact, they almost never do.
* This feature is here for networking professionals using very advanced techniques.
**/
- (BOOL)connectToHost:(NSString *)host
onPort:(uint16_t)port
viaInterface:(NSString *)interface
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr;
/**
* Connects to the given address, specified as a sockaddr structure wrapped in a NSData object.
* For example, a NSData object returned from NSNetservice's addresses method.
*
* If you have an existing struct sockaddr you can convert it to a NSData object like so:
* struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
* struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
*
* This method invokes connectToAdd
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
/**
* This method is the same as connectToAddress:error: with an additional timeout option.
* To not time out use a negative time interval, or simply use the connectToAddress:error: method.
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr;
/**
* Connects to the given address, using the specified interface and timeout.
*
* The address is specified as a sockaddr structure wrapped in a NSData object.
* For example, a NSData object returned from NSNetservice's addresses method.
*
* If you have an existing struct sockaddr you can convert it to a NSData object like so:
* struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
* struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
*
* The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
* The interface may also be used to specify the local port (see below).
*
* The timeout is optional. To not time out use a negative time interval.
*
* This method will return NO if an error is detected, and set the error pointer (if one was given).
* Possible errors would be a nil host, invalid interface, or socket is already connected.
*
* If no errors are detected, this method will start a background connect operation and immediately return YES.
* The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.
*
* Since this class supports queued reads and writes, you can immediately start reading and/or writing.
* All read/write operations will be queued, and upon socket connection,
* the operations will be dequeued and processed in order.
*
* The interface may optionally contain a port number at the end of the string, separated by a colon.
* This allows you to specify the local port that should be used for the outgoing connection. (read paragraph to end)
* To specify both interface and local port: "en1:8082" or "192.168.4.35:2424".
* To specify only local port: ":8082".
* Please note this is an advanced feature, and is somewhat hidden on purpose.
* You should understand that 99.999% of the time you should NOT specify the local port for an outgoing connection.
* If you think you need to, there is a very good chance you have a fundamental misunderstanding somewhere.
* Local ports do NOT need to match remote ports. In fact, they almost never do.
* This feature is here for networking professionals using very advanced techniques.
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr
viaInterface:(NSString *)interface
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr;
#pragma mark Disconnecting
/**
* Disconnects immediately (synchronously). Any pending reads or writes are dropped.
*
* If the socket is not already disconnected, an invocation to the socketDidDisconnect:withError: delegate method
* will be queued onto the delegateQueue asynchronously (behind any previously queued delegate methods).
* In other words, the disconnected delegate method will be invoked sometime shortly after this method returns.
*
* Please note the recommended way of releasing a GCDAsyncSocket instance (e.g. in a dealloc method)
* [asyncSocket setDelegate:nil];
* [asyncSocket disconnect];
* [asyncSocket release];
*
* If you plan on disconnecting the socket, and then immediately asking it to connect again,
* you'll likely want to do so like this:
* [asyncSocket setDelegate:nil];
* [asyncSocket disconnect];
* [asyncSocket setDelegate:self];
* [asyncSocket connect...];
**/
- (void)disconnect;
/**
* Disconnects after all pending reads have completed.
* After calling this, the read and write methods will do nothing.
* The socket will disconnect even if there are still pending writes.
**/
- (void)disconnectAfterReading;
/**
* Disconnects after all pending writes have completed.
* After calling this, the read and write methods will do nothing.
* The socket will disconnect even if there are still pending reads.
**/
- (void)disconnectAfterWriting;
/**
* Disconnects after all pending reads and writes have completed.
* After calling this, the read and write methods will do nothing.
**/
- (void)disconnectAfterReadingAndWriting;
#pragma mark Diagnostics
/**
* Returns whether the socket is disconnected or connected.
*
* A disconnected socket may be recycled.
* That is, it can used again for connecting or listening.
*
* If a socket is in the process of connecting, it may be neither disconnected nor connected.
**/
- (BOOL)isDisconnected;
- (BOOL)isConnected;
/**
* Returns the local or remote host and port to which this socket is connected, or nil and 0 if not connected.
* The host will be an IP address.
**/
- (NSString *)connectedHost;
- (uint16_t)connectedPort;
- (NSString *)localHost;
- (uint16_t)localPort;
/**
* Returns the local or remote address to which this socket is connected,
* specified as a sockaddr structure wrapped in a NSData object.
*
* See also the connectedHost, connectedPort, localHost and localPort methods.
**/
- (NSData *)connectedAddress;
- (NSData *)localAddress;
/**
* Returns whether the socket is IPv4 or IPv6.
* An accepting socket may be both.
**/
- (BOOL)isIPv4;
- (BOOL)isIPv6;
/**
* Returns whether or not the socket has been secured via SSL/TLS.
*
* See also the startTLS method.
**/
- (BOOL)isSecure;
#pragma mark Reading
// The readData and writeData methods won't block (they are asynchronous).
//
// When a read is complete the socket:didReadData:withTag: delegate method is dispatched on the delegateQueue.
// When a write is complete the socket:didWriteDataWithTag: delegate method is dispatched on the delegateQueue.
//
// You may optionally set a timeout for any read/write operation. (To not timeout, use a negative time interval.)
// If a read/write opertion times out, the corresponding "socket:shouldTimeout..." delegate method
// is called to optionally allow you to extend the timeout.
// Upon a timeout, the "socket:willDisconnectWithError:" method is called, followed by "socketDidDisconnect".
//
// The tag is for your convenience.
// You can use it as an array index, step number, state id, pointer, etc.
/**
* Reads the first available bytes that become available on the socket.
*
* If the timeout value is negative, the read operation will not use a timeout.
**/
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Reads the first available bytes that become available on the socket.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, the socket will create a buffer for you.
*
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
**/
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag;
/**
* Reads the first available bytes that become available on the socket.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
* A maximum of length bytes will be read.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
* If maxLength is zero, no length restriction is enforced.
*
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
**/
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag;
/**
* Reads the given number of bytes.
*
* If the timeout value is negative, the read operation will not use a timeout.
*
* If the length is 0, this method does nothing and the delegate is not called.
**/
- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Reads the given number of bytes.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
*
* If the length is 0, this method does nothing and the delegate is not called.
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
**/
- (void)readDataToLength:(NSUInteger)length
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
*
* If the timeout value is negative, the read operation will not use a timeout.
*
* If you pass nil or zero-length data as the "data" parameter,
* the method will do nothing, and the delegate will not be called.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
*
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
*
* If the timeout value is negative, the read operation will not use a timeout.
*
* If maxLength is zero, no length restriction is enforced.
* Otherwise if maxLength bytes are read without completing the read,
* it is treated similarly to a timeout - the socket is closed with a GCDAsyncSocketReadMaxedOutError.
* The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
*
* If you pass nil or zero-length data as the "data" parameter,
* the method will do nothing, and the delegate will not be called.
* If you pass a maxLength parameter that is less than the length of the data parameter,
* the method will do nothing, and the delegate will not be called.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag;
/**
* Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
* The bytes will be appended to the given byte buffer starting at the given offset.
* The given buffer will automatically be increased in size if needed.
*
* If the timeout value is negative, the read operation will not use a timeout.
* If the buffer if nil, a buffer will automatically be created for you.
*
* If maxLength is zero, no length restriction is enforced.
* Otherwise if maxLength bytes are read without completing the read,
* it is treated similarly to a timeout - the socket is closed with a GCDAsyncSocketReadMaxedOutError.
* The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
*
* If you pass a maxLength parameter that is less than the length of the data parameter,
* the method will do nothing, and the delegate will not be called.
* If the bufferOffset is greater than the length of the given buffer,
* the method will do nothing, and the delegate will not be called.
*
* If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
* After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
* That is, it will reference the bytes that were appended to the given buffer.
*
* To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
* Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
* a character, the read will prematurely end.
**/
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag;
#pragma mark Writing
/**
* Writes data to the socket, and calls the delegate when finished.
*
* If you pass in nil or zero-length data, this method does nothing and the delegate will not be called.
* If the timeout value is negative, the write operation will not use a timeout.
**/
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
#pragma mark Security
/**
* Secures the connection using SSL/TLS.
*
* This method may be called at any time, and the TLS handshake will occur after all pending reads and writes
* are finished. This allows one the option of sending a protocol dependent StartTLS message, and queuing
* the upgrade to TLS at the same time, without having to wait for the write to finish.
* Any reads or writes scheduled after this method is called will occur over the secured connection.
*
* The possible keys and values for the TLS settings are well documented.
* Some possible keys are:
* - kCFStreamSSLLevel
* - kCFStreamSSLAllowsExpiredCertificates
* - kCFStreamSSLAllowsExpiredRoots
* - kCFStreamSSLAllowsAnyRoot
* - kCFStreamSSLValidatesCertificateChain
* - kCFStreamSSLPeerName
* - kCFStreamSSLCertificates
* - kCFStreamSSLIsServer
*
* Please refer to Apple's documentation for associated values, as well as other possible keys.
*
* If you pass in nil or an empty dictionary, the default settings will be used.
*
* The default settings will check to make sure the remote party's certificate is signed by a
* trusted 3rd party certificate agency (e.g. verisign) and that the certificate is not expired.
* However it will not verify the name on the certificate unless you
* give it a name to verify against via the kCFStreamSSLPeerName key.
* The security implications of this are important to understand.
* Imagine you are attempting to create a secure connection to MySecureServer.com,
* but your socket gets directed to MaliciousServer.com because of a hacked DNS server.
* If you simply use the default settings, and MaliciousServer.com has a valid certificate,
* the default settings will not detect any problems since the certificate is valid.
* To properly secure your connection in this particular scenario you
* should set the kCFStreamSSLPeerName property to "MySecureServer.com".
* If you do not know the peer name of the remote host in advance (for example, you're not sure
* if it will be "domain.com" or "www.domain.com"), then you can use the default settings to validate the
* certificate, and then use the X509Certificate class to verify the issuer after the socket has been secured.
* The X509Certificate class is part of the CocoaAsyncSocket open source project.
**/
- (void)startTLS:(NSDictionary *)tlsSettings;
#pragma mark Advanced
/**
* It's not thread-safe to access certain variables from outside the socket's internal queue.
*
* For example, the socket file descriptor.
* File descriptors are simply integers which reference an index in the per-process file table.
* However, when one requests a new file descriptor (by opening a file or socket),
* the file descriptor returned is guaranteed to be the lowest numbered unused descriptor.
* So if we're not careful, the following could be possible:
*
* - Thread A invokes a method which returns the socket's file descriptor.
* - The socket is closed via the socket's internal queue on thread B.
* - Thread C opens a file, and subsequently receives the file descriptor that was previously the socket's FD.
* - Thread A is now accessing/altering the file instead of the socket.
*
* In addition to this, other variables are not actually objects,
* and thus cannot be retained/released or even autoreleased.
* An example is the sslContext, of type SSLContextRef, which is actually a malloc'd struct.
*
* Although there are internal variables that make it difficult to maintain thread-safety,
* it is important to provide access to these variables
* to ensure this class can be used in a wide array of environments.
* This method helps to accomplish this by invoking the current block on the socket's internal queue.
* The methods below can be invoked from within the block to access
* those generally thread-unsafe internal variables in a thread-safe manner.
* The given block will be invoked synchronously on the socket's internal queue.
*
* If you save references to any protected variables and use them outside the block, you do so at your own peril.
**/
- (void)performBlock:(dispatch_block_t)block;
/**
* These methods are only available from within the context of a performBlock: invocation.
* See the documentation for the performBlock: method above.
*
* Provides access to the socket's file descriptor(s).
* If the socket is a server socket (is accepting incoming connections),
* it might actually have multiple internal socket file descriptors - one for IPv4 and one for IPv6.
**/
- (int)socketFD;
- (int)socket4FD;
- (int)socket6FD;
#if TARGET_OS_IPHONE
/**
* These methods are only available from within the context of a performBlock: invocation.
* See the documentation for the performBlock: method above.
*
* Provides access to the socket's internal CFReadStream/CFWriteStream.
*
* These streams are only used as workarounds for specific iOS shortcomings:
*
* - Apple has decided to keep the SecureTransport framework private is iOS.
* This means the only supplied way to do SSL/TLS is via CFStream or some other API layered on top of it.
* Thus, in order to provide SSL/TLS support on iOS we are forced to rely on CFStream,
* instead of the preferred and faster and more powerful SecureTransport.
*
* - If a socket doesn't have backgrounding enabled, and that socket is closed while the app is backgrounded,
* Apple only bothers to notify us via the CFStream API.
* The faster and more powerful GCD API isn't notified properly in this case.
*
* See also: (BOOL)enableBackgroundingOnSocket
**/
- (CFReadStreamRef)readStream;
- (CFWriteStreamRef)writeStream;
/**
* This method is only available from within the context of a performBlock: invocation.
* See the documentation for the performBlock: method above.
*
* Configures the socket to allow it to operate when the iOS application has been backgrounded.
* In other words, this method creates a read & write stream, and invokes:
*
* CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
* CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
*
* Returns YES if successful, NO otherwise.
*
* Note: Apple does not officially support backgrounding server sockets.
* That is, if your socket is accepting incoming connections, Apple does not officially support
* allowing iOS applications to accept incoming connections while an app is backgrounded.
*
* Example usage:
*
* - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
* {
* [asyncSocket performBlock:^{
* [asyncSocket enableBackgroundingOnSocket];
* }];
* }
**/
- (BOOL)enableBackgroundingOnSocket;
#else
/**
* This method is only available from within the context of a performBlock: invocation.
* See the documentation for the performBlock: method above.
*
* Provides access to the socket's SSLContext, if SSL/TLS has been started on the socket.
**/
- (SSLContextRef)sslContext;
#endif
#pragma mark Utilities
/**
* Extracting host and port information from raw address data.
**/
+ (NSString *)hostFromAddress:(NSData *)address;
+ (uint16_t)portFromAddress:(NSData *)address;
+ (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr fromAddress:(NSData *)address;
/**
* A few common line separators, for use with the readDataToData:... methods.
**/
+ (NSData *)CRLFData; // 0x0D0A
+ (NSData *)CRData; // 0x0D
+ (NSData *)LFData; // 0x0A
+ (NSData *)ZeroData; // 0x00
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@protocol GCDAsyncSocketDelegate
@optional
/**
* This method is called immediately prior to socket:didAcceptNewSocket:.
* It optionally allows a listening socket to specify the socketQueue for a new accepted socket.
* If this method is not implemented, or returns NULL, the new accepted socket will create its own default queue.
*
* Since you cannot autorelease a dispatch_queue,
* this method uses the "new" prefix in its name to specify that the returned queue has been retained.
*
* Thus you could do something like this in the implementation:
* return dispatch_queue_create("MyQueue", NULL);
*
* If you are placing multiple sockets on the same queue,
* then care should be taken to increment the retain count each time this method is invoked.
*
* For example, your implementation might look something like this:
* dispatch_retain(myExistingQueue);
* return myExistingQueue;
**/
- (dispatch_queue_t)newSocketQueueForConnectionFromAddress:(NSData *)address onSocket:(GCDAsyncSocket *)sock;
/**
* Called when a socket accepts a connection.
* Another socket is automatically spawned to handle it.
*
* You must retain the newSocket if you wish to handle the connection.
* Otherwise the newSocket instance will be released and the spawned connection will be closed.
*
* By default the new socket will have the same delegate and delegateQueue.
* You may, of course, change this at any time.
**/
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket;
/**
* Called when a socket connects and is ready for reading and writing.
* The host parameter will be an IP address, not a DNS name.
**/
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
/**
* Called when a socket has completed reading the requested data into memory.
* Not called if there is an error.
**/
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
/**
* Called when a socket has read in data, but has not yet completed the read.
* This would occur if using readToData: or readToLength: methods.
* It may be used to for things such as updating progress bars.
**/
- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
/**
* Called when a socket has completed writing the requested data. Not called if there is an error.
**/
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;
/**
* Called when a socket has written some data, but has not yet completed the entire write.
* It may be used to for things such as updating progress bars.
**/
- (void)socket:(GCDAsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
/**
* Called if a read operation has reached its timeout without completing.
* This method allows you to optionally extend the timeout.
* If you return a positive time interval (> 0) the read's timeout will be extended by the given amount.
* If you don't implement this method, or return a non-positive time interval (<= 0) the read will timeout as usual.
*
* The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
* The length parameter is the number of bytes that have been read so far for the read operation.
*
* Note that this method may be called multiple times for a single read if you return positive numbers.
**/
- (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length;
/**
* Called if a write operation has reached its timeout without completing.
* This method allows you to optionally extend the timeout.
* If you return a positive time interval (> 0) the write's timeout will be extended by the given amount.
* If you don't implement this method, or return a non-positive time interval (<= 0) the write will timeout as usual.
*
* The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
* The length parameter is the number of bytes that have been written so far for the write operation.
*
* Note that this method may be called multiple times for a single write if you return positive numbers.
**/
- (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length;
/**
* Conditionally called if the read stream closes, but the write stream may still be writeable.
*
* This delegate method is only called if autoDisconnectOnClosedReadStream has been set to NO.
* See the discussion on the autoDisconnectOnClosedReadStream method for more information.
**/
- (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock;
/**
* Called when a socket disconnects with or without error.
*
* If you call the disconnect method, and the socket wasn't already disconnected,
* this delegate method will be called before the disconnect method returns.
**/
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err;
/**
* Called after the socket has successfully completed SSL/TLS negotiation.
* This method is not called unless you use the provided startTLS method.
*
* If a SSL/TLS negotiation fails (invalid certificate, etc) then the socket will immediately close,
* and the socketDidDisconnect:withError: delegate method will be called with the specific SSL error code.
**/
- (void)socketDidSecure:(GCDAsyncSocket *)sock;
@end
|
zzymoon-cocoaasyncsocket
|
GCD/GCDAsyncSocket.h
|
Objective-C
|
oos
| 41,246
|
<html>
<body>
<h1>Welcome to the CocoaAsyncSocket project!</h1>
<p>
A wealth of documentation can be found on the Google Code homepage:</br>
<a href="http://code.google.com/p/cocoaasyncsocket/">http://code.google.com/p/cocoaasyncsocket/</a>
</p>
<p>
If you are new to networking, it is recommended you start by reading the Intro page:<br/>
<a href="http://code.google.com/p/cocoaasyncsocket/wiki/Intro">http://code.google.com/p/cocoaasyncsocket/wiki/Intro</a>
</p>
<p>
If you are a seasoned networking professional, with 10+ years of experience writing low-level socket code,
and detailed knowledge of the underlying BSD networking stack, then you can skip the CommonPitfalls page.<br/>
Otherwise, it should be considered mandatory reading:<br/>
<a href="http://code.google.com/p/cocoaasyncsocket/wiki/CommonPitfalls">http://code.google.com/p/cocoaasyncsocket/wiki/CommonPitfalls</a>
</p>
<h4>
A little bit of investment in your knowledge and understanding of networking fundamentals can go a long way.<br/>
And it can save you a LOT of time and frustration in the long run.
</h4>
<p>
The API reference page can be found here:</br/>
<a href="http://code.google.com/p/cocoaasyncsocket/wiki/Reference_GCDAsyncSocket">http://code.google.com/p/cocoaasyncsocket/wiki/Reference_GCDAsyncSocket</a>
</p>
<p>
In addition to this, the headers are generally well documented.
</p>
<p>
If you have any questions you are welcome to post to the CocoaAsyncSocket mailing list:<br/>
<a href="http://groups.google.com/group/cocoaasyncsocket">http://groups.google.com/group/cocoaasyncsocket</a><br/>
<br/>
The list is archived, and available for browsing online.<br/>
You may be able to instantly find the answer you're looking for with a quick search.<br/>
</p>
<h3>We hope the CocoaAsyncSocket project can provide you with powerful and easy to use networking libraries.</h3>
</body>
</html>
|
zzymoon-cocoaasyncsocket
|
GCD/Documentation.html
|
HTML
|
oos
| 1,883
|
#import "ConnectTestAppDelegate.h"
#import "ConnectTestViewController.h"
#import "GCDAsyncSocket.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_INFO;
#define USE_SECURE_CONNECTION 1
#define ENABLE_BACKGROUNDING 0
@implementation ConnectTestAppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Application Lifecycle
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (id)init
{
if ((self = [super init]))
{
// Setup logging framework
[DDLog addLogger:[DDTTYLogger sharedInstance]];
}
return self;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
DDLogInfo(@"%@", THIS_METHOD);
// Setup our socket (GCDAsyncSocket).
// The socket will invoke our delegate methods using the usual delegate paradigm.
// However, it will invoke the delegate methods on a specified GCD delegate dispatch queue.
//
// Now we can configure the delegate dispatch queue however we want.
// We could use a dedicated dispatch queue for easy parallelization.
// Or we could simply use the dispatch queue for the main thread.
//
// The best approach for your application will depend upon convenience, requirements and performance.
//
// For this simple example, we're just going to use the main thread.
dispatch_queue_t mainQueue = dispatch_get_main_queue();
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
#if USE_SECURE_CONNECTION
{
NSString *host = @"www.paypal.com";
uint16_t port = 443;
DDLogInfo(@"Connecting to \"%@\" on port %hu...", host, port);
self.viewController.label.text = @"Connecting...";
NSError *error = nil;
if (![asyncSocket connectToHost:@"www.paypal.com" onPort:port error:&error])
{
DDLogError(@"Error connecting: %@", error);
self.viewController.label.text = @"Oops";
}
}
#else
{
NSString *host = @"deusty.com";
uint16_t port = 80;
DDLogInfo(@"Connecting to \"%@\" on port %hu...", host, port);
self.viewController.label.text = @"Connecting...";
NSError *error = nil;
if (![asyncSocket connectToHost:host onPort:port error:&error])
{
DDLogError(@"Error connecting: %@", error);
self.viewController.label.text = @"Oops";
}
// You can also specify an optional connect timeout.
// NSError *error = nil;
// if (![asyncSocket connectToHost:host onPort:80 withTimeout:5.0 error:&error])
// {
// DDLogError(@"Error connecting: %@", error);
// }
}
#endif
// Add the view controller's view to the window and display.
[self.window addSubview:self.viewController.view];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
DDLogInfo(@"%@", THIS_METHOD);
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
DDLogInfo(@"%@", THIS_METHOD);
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
DDLogInfo(@"%@", THIS_METHOD);
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
static BOOL isAppLaunch = YES;
if (isAppLaunch)
{
isAppLaunch = NO;
return;
}
DDLogInfo(@"%@", THIS_METHOD);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Socket Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
DDLogInfo(@"socket:%p didConnectToHost:%@ port:%hu", sock, host, port);
self.viewController.label.text = @"Connected";
// DDLogInfo(@"localHost :%@ port:%hu", [sock localHost], [sock localPort]);
#if USE_SECURE_CONNECTION
{
// Connected to secure server (HTTPS)
#if ENABLE_BACKGROUNDING && !TARGET_IPHONE_SIMULATOR
{
// Backgrounding doesn't seem to be supported on the simulator yet
[sock performBlock:^{
if ([sock enableBackgroundingOnSocket])
DDLogInfo(@"Enabled backgrounding on socket");
else
DDLogWarn(@"Enabling backgrounding failed!");
}];
}
#endif
// Configure SSL/TLS settings
NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];
// If you simply want to ensure that the remote host's certificate is valid,
// then you can use an empty dictionary.
// If you know the name of the remote host, then you should specify the name here.
//
// NOTE:
// You should understand the security implications if you do not specify the peer name.
// Please see the documentation for the startTLS method in GCDAsyncSocket.h for a full discussion.
[settings setObject:@"www.paypal.com"
forKey:(NSString *)kCFStreamSSLPeerName];
// To connect to a test server, with a self-signed certificate, use settings similar to this:
// // Allow expired certificates
// [settings setObject:[NSNumber numberWithBool:YES]
// forKey:(NSString *)kCFStreamSSLAllowsExpiredCertificates];
//
// // Allow self-signed certificates
// [settings setObject:[NSNumber numberWithBool:YES]
// forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
//
// // In fact, don't even validate the certificate chain
// [settings setObject:[NSNumber numberWithBool:NO]
// forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
DDLogInfo(@"Starting TLS with settings:\n%@", settings);
[sock startTLS:settings];
// You can also pass nil to the startTLS method, which is the same as passing an empty dictionary.
// Again, you should understand the security implications of doing so.
// Please see the documentation for the startTLS method in GCDAsyncSocket.h for a full discussion.
}
#else
{
// Connected to normal server (HTTP)
#if ENABLE_BACKGROUNDING && !TARGET_IPHONE_SIMULATOR
{
// Backgrounding doesn't seem to be supported on the simulator yet
[sock performBlock:^{
if ([sock enableBackgroundingOnSocket])
DDLogInfo(@"Enabled backgrounding on socket");
else
DDLogWarn(@"Enabling backgrounding failed!");
}];
}
#endif
}
#endif
}
- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
DDLogInfo(@"socketDidSecure:%p", sock);
self.viewController.label.text = @"Connected + Secure";
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
DDLogInfo(@"socket:%p didWriteDataWithTag:%d", sock, tag);
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
DDLogInfo(@"socket:%p didReadData:withTag:%d", sock, tag);
NSString *httpResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
DDLogInfo(@"HTTP Response:\n%@", httpResponse);
[httpResponse release];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
DDLogInfo(@"socketDidDisconnect:%p withError: %@", sock, err);
self.viewController.label.text = @"Disconnected";
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Mobile/ConnectTest/ConnectTest/ConnectTestAppDelegate.m
|
Objective-C
|
oos
| 7,237
|
#import "ConnectTestViewController.h"
@implementation ConnectTestViewController
@synthesize label = _label;
- (void)dealloc
{
[super dealloc];
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Mobile/ConnectTest/ConnectTest/ConnectTestViewController.m
|
Objective-C
|
oos
| 159
|
#import <UIKit/UIKit.h>
@interface ConnectTestViewController : UIViewController {
}
@property (nonatomic, retain) IBOutlet UILabel *label;
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Mobile/ConnectTest/ConnectTest/ConnectTestViewController.h
|
Objective-C
|
oos
| 153
|
#import <UIKit/UIKit.h>
@class ConnectTestViewController;
@class GCDAsyncSocket;
@interface ConnectTestAppDelegate : NSObject <UIApplicationDelegate>
{
GCDAsyncSocket *asyncSocket;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet ConnectTestViewController *viewController;
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Mobile/ConnectTest/ConnectTest/ConnectTestAppDelegate.h
|
Objective-C
|
oos
| 333
|
//
// main.m
// ConnectTest
//
// Created by Robbie Hanson on 7/25/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Mobile/ConnectTest/ConnectTest/main.m
|
Objective-C
|
oos
| 348
|
#import "ConnectTestAppDelegate.h"
#import "GCDAsyncSocket.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_INFO;
#define USE_SECURE_CONNECTION 0
@implementation ConnectTestAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Setup logging framework
[DDLog addLogger:[DDTTYLogger sharedInstance]];
DDLogInfo(@"%@", THIS_METHOD);
// Setup our socket (GCDAsyncSocket).
// The socket will invoke our delegate methods using the usual delegate paradigm.
// However, it will invoke the delegate methods on a specified GCD delegate dispatch queue.
//
// Now we can configure the delegate dispatch queue however we want.
// We could use a dedicated dispatch queue for easy parallelization.
// Or we could simply use the dispatch queue for the main thread.
//
// The best approach for your application will depend upon convenience, requirements and performance.
//
// For this simple example, we're just going to use the main thread.
dispatch_queue_t mainQueue = dispatch_get_main_queue();
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
#if USE_SECURE_CONNECTION
{
NSString *host = @"www.paypal.com";
uint16_t port = 443;
DDLogInfo(@"Connecting to \"%@\" on port %hu...", host, port);
NSError *error = nil;
if (![asyncSocket connectToHost:@"www.paypal.com" onPort:port error:&error])
{
DDLogError(@"Error connecting: %@", error);
}
}
#else
{
NSString *host = @"deusty.com";
uint16_t port = 80;
DDLogInfo(@"Connecting to \"%@\" on port %hu...", host, port);
NSError *error = nil;
if (![asyncSocket connectToHost:host onPort:port error:&error])
{
DDLogError(@"Error connecting: %@", error);
}
// You can also specify an optional connect timeout.
// NSError *error = nil;
// if (![asyncSocket connectToHost:host onPort:80 withTimeout:5.0 error:&error])
// {
// DDLogError(@"Error connecting: %@", error);
// }
}
#endif
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Socket Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
DDLogInfo(@"socket:%p didConnectToHost:%@ port:%hu", sock, host, port);
// DDLogInfo(@"localHost :%@ port:%hu", [sock localHost], [sock localPort]);
#if USE_SECURE_CONNECTION
{
// Connected to secure server (HTTPS)
// Configure SSL/TLS settings
NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];
// If you simply want to ensure that the remote host's certificate is valid,
// then you can use an empty dictionary.
// If you know the name of the remote host, then you should specify the name here.
//
// NOTE:
// You should understand the security implications if you do not specify the peer name.
// Please see the documentation for the startTLS method in GCDAsyncSocket.h for a full discussion.
[settings setObject:@"www.paypal.com"
forKey:(NSString *)kCFStreamSSLPeerName];
// To connect to a test server, with a self-signed certificate, use settings similar to this:
// // Allow expired certificates
// [settings setObject:[NSNumber numberWithBool:YES]
// forKey:(NSString *)kCFStreamSSLAllowsExpiredCertificates];
//
// // Allow self-signed certificates
// [settings setObject:[NSNumber numberWithBool:YES]
// forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
//
// // In fact, don't even validate the certificate chain
// [settings setObject:[NSNumber numberWithBool:NO]
// forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
DDLogInfo(@"Starting TLS with settings:\n%@", settings);
[sock startTLS:settings];
// You can also pass nil to the startTLS method, which is the same as passing an empty dictionary.
// Again, you should understand the security implications of doing so.
// Please see the documentation for the startTLS method in GCDAsyncSocket.h for a full discussion.
}
#else
{
// Connected to normal server (HTTP)
}
#endif
}
- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
DDLogInfo(@"socketDidSecure:%p", sock);
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
DDLogInfo(@"socket:%p didWriteDataWithTag:%d", sock, tag);
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
DDLogInfo(@"socket:%p didReadData:withTag:%d", sock, tag);
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
DDLogInfo(@"socketDidDisconnect:%p withError: %@", sock, err);
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Desktop/ConnectTest/ConnectTest/ConnectTestAppDelegate.m
|
Objective-C
|
oos
| 4,864
|
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw9840\paperh8400
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
\f0\b\fs24 \cf0 Engineering:
\b0 \
Some people\
\
\b Human Interface Design:
\b0 \
Some other people\
\
\b Testing:
\b0 \
Hopefully not nobody\
\
\b Documentation:
\b0 \
Whoever\
\
\b With special thanks to:
\b0 \
Mom\
}
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Desktop/ConnectTest/ConnectTest/en.lproj/Credits.rtf
|
Rich Text Format
|
oos
| 436
|
#import <Cocoa/Cocoa.h>
@class GCDAsyncSocket;
@interface ConnectTestAppDelegate : NSObject <NSApplicationDelegate> {
@private
GCDAsyncSocket *asyncSocket;
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Desktop/ConnectTest/ConnectTest/ConnectTestAppDelegate.h
|
Objective-C
|
oos
| 236
|
//
// main.m
// ConnectTest
//
// Created by Robbie Hanson on 7/23/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/ConnectTest/Desktop/ConnectTest/ConnectTest/main.m
|
Objective-C
|
oos
| 253
|
#import <Cocoa/Cocoa.h>
@class GCDAsyncSocket;
@interface EchoServerAppDelegate : NSObject <NSApplicationDelegate>
{
dispatch_queue_t socketQueue;
GCDAsyncSocket *listenSocket;
NSMutableArray *connectedSockets;
BOOL isRunning;
IBOutlet id logView;
IBOutlet id portField;
IBOutlet id startStopButton;
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
- (IBAction)startStop:(id)sender;
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/EchoServer/EchoServerAppDelegate.h
|
Objective-C
|
oos
| 427
|
#import "EchoServerAppDelegate.h"
#import "GCDAsyncSocket.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#define WELCOME_MSG 0
#define ECHO_MSG 1
#define WARNING_MSG 2
#define READ_TIMEOUT 15.0
#define READ_TIMEOUT_EXTENSION 10.0
#define FORMAT(format, ...) [NSString stringWithFormat:(format), ##__VA_ARGS__]
@interface EchoServerAppDelegate (PrivateAPI)
- (void)logError:(NSString *)msg;
- (void)logInfo:(NSString *)msg;
- (void)logMessage:(NSString *)msg;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation EchoServerAppDelegate
@synthesize window;
- (id)init
{
if((self = [super init]))
{
// Setup our logging framework.
// Logging isn't used in this file, but can optionally be enabled in GCDAsyncSocket.
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Setup our server socket (GCDAsyncSocket).
// The socket will invoke our delegate methods using the usual delegate paradigm.
// However, it will invoke the delegate methods on a specified GCD delegate dispatch queue.
//
// Now we can setup these delegate dispatch queues however we want.
// Here are a few examples:
//
// - A different delegate queue for each client connection.
// - Simply use the main dispatch queue, so the delegate methods are invoked on the main thread.
// - Add each client connection to the same dispatch queue.
//
// The best approach for your application will depend upon convenience, requirements and performance.
//
// For this simple example, we're just going to share the same dispatch queue amongst all client connections.
socketQueue = dispatch_queue_create("SocketQueue", NULL);
listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];
// Setup an array to store all accepted client connections
connectedSockets = [[NSMutableArray alloc] initWithCapacity:1];
isRunning = NO;
}
return self;
}
- (void)awakeFromNib
{
[logView setString:@""];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Reserved
}
- (void)scrollToBottom
{
NSScrollView *scrollView = [logView enclosingScrollView];
NSPoint newScrollOrigin;
if ([[scrollView documentView] isFlipped])
newScrollOrigin = NSMakePoint(0.0F, NSMaxY([[scrollView documentView] frame]));
else
newScrollOrigin = NSMakePoint(0.0F, 0.0F);
[[scrollView documentView] scrollPoint:newScrollOrigin];
}
- (void)logError:(NSString *)msg
{
NSString *paragraph = [NSString stringWithFormat:@"%@\n", msg];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:1];
[attributes setObject:[NSColor redColor] forKey:NSForegroundColorAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[logView textStorage] appendAttributedString:as];
[self scrollToBottom];
}
- (void)logInfo:(NSString *)msg
{
NSString *paragraph = [NSString stringWithFormat:@"%@\n", msg];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:1];
[attributes setObject:[NSColor purpleColor] forKey:NSForegroundColorAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[logView textStorage] appendAttributedString:as];
[self scrollToBottom];
}
- (void)logMessage:(NSString *)msg
{
NSString *paragraph = [NSString stringWithFormat:@"%@\n", msg];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:1];
[attributes setObject:[NSColor blackColor] forKey:NSForegroundColorAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[logView textStorage] appendAttributedString:as];
[self scrollToBottom];
}
- (IBAction)startStop:(id)sender
{
if(!isRunning)
{
int port = [portField intValue];
if(port < 0 || port > 65535)
{
[portField setStringValue:@""];
port = 0;
}
NSError *error = nil;
if(![listenSocket acceptOnPort:port error:&error])
{
[self logError:FORMAT(@"Error starting server: %@", error)];
return;
}
[self logInfo:FORMAT(@"Echo server started on port %hu", [listenSocket localPort])];
isRunning = YES;
[portField setEnabled:NO];
[startStopButton setTitle:@"Stop"];
}
else
{
// Stop accepting connections
[listenSocket disconnect];
// Stop any client connections
@synchronized(connectedSockets)
{
NSUInteger i;
for (i = 0; i < [connectedSockets count]; i++)
{
// Call disconnect on the socket,
// which will invoke the socketDidDisconnect: method,
// which will remove the socket from the list.
[[connectedSockets objectAtIndex:i] disconnect];
}
}
[self logInfo:@"Stopped Echo server"];
isRunning = false;
[portField setEnabled:YES];
[startStopButton setTitle:@"Start"];
}
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
// This method is executed on the socketQueue (not the main thread)
@synchronized(connectedSockets)
{
[connectedSockets addObject:newSocket];
}
NSString *host = [newSocket connectedHost];
UInt16 port = [newSocket connectedPort];
dispatch_async(dispatch_get_main_queue(), ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self logInfo:FORMAT(@"Accepted client %@:%hu", host, port)];
[pool release];
});
NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
[newSocket writeData:welcomeData withTimeout:-1 tag:WELCOME_MSG];
[newSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
if (tag == ECHO_MSG)
{
[sock readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
dispatch_async(dispatch_get_main_queue(), ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
NSString *msg = [[[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding] autorelease];
if (msg)
{
[self logMessage:msg];
}
else
{
[self logError:@"Error converting received data into UTF-8 String"];
}
[pool release];
});
// Echo message back to client
[sock writeData:data withTimeout:-1 tag:ECHO_MSG];
}
/**
* This method is called if a read has timed out.
* It allows us to optionally extend the timeout.
* We use this method to issue a warning to the user prior to disconnecting them.
**/
- (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length
{
if (elapsed <= READ_TIMEOUT)
{
NSString *warningMsg = @"Are you still there?\r\n";
NSData *warningData = [warningMsg dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:warningData withTimeout:-1 tag:WARNING_MSG];
return READ_TIMEOUT_EXTENSION;
}
return 0.0;
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
if (sock != listenSocket)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self logInfo:FORMAT(@"Client Disconnected")];
[pool release];
});
@synchronized(connectedSockets)
{
[connectedSockets removeObject:sock];
}
}
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/EchoServer/EchoServerAppDelegate.m
|
Objective-C
|
oos
| 7,926
|
//
// main.m
// EchoServer
//
// Created by Robbie Hanson on 11/4/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/EchoServer/main.m
|
Objective-C
|
oos
| 257
|
#import "SimpleHTTPClientAppDelegate.h"
#import "SimpleHTTPClientViewController.h"
#import "GCDAsyncSocket.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#define USE_SECURE_CONNECTION 0
#define READ_HEADER_LINE_BY_LINE 0
@implementation SimpleHTTPClientAppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// AsyncSocket optionally uses the Lumberjack logging framework.
//
// Lumberjack is a professional logging framework. It's extremely fast and flexible.
// It also uses GCD, making it a great fit for GCDAsyncSocket.
//
// As mentioned earlier, enabling logging in GCDAsyncSocket is entirely optional.
// Doing so simply helps give you a deeper understanding of the inner workings of the library (if you care).
// You can do so at the top of GCDAsyncSocket.m,
// where you can also control things such as the log level,
// and whether or not logging should be asynchronous (helps to improve speed, and
// perfect for reducing interference with those pesky timing bugs in your code).
//
// There is a massive amount of documentation on the Lumberjack project page:
// http://code.google.com/p/cocoalumberjack/
//
// But this one line is all you need to instruct Lumberjack to spit out log statements to the Xcode console.
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Create our GCDAsyncSocket instance.
//
// Notice that we give it the normal delegate AND a delegate queue.
// The socket will do all of its operations in a background queue,
// and you can tell it which thread/queue to invoke your delegate on.
// In this case, we're just saying invoke us on the main thread.
// But you can see how trivial it would be to create your own queue,
// and parallelize your networking processing code by having your
// delegate methods invoked and run on background queues.
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
// Now we tell the ASYNCHRONOUS socket to connect.
//
// Recall that GCDAsyncSocket is ... asynchronous.
// This means when you tell the socket to connect, it will do so ... asynchronously.
// After all, do you want your main thread to block on a slow network connection?
//
// So what's with the BOOL return value, and error pointer?
// These are for early detection of obvious problems, such as:
//
// - The socket is already connected.
// - You passed in an invalid parameter.
// - The socket isn't configured properly.
//
// The error message might be something like "Attempting to connect without a delegate. Set a delegate first."
//
// When the asynchronous sockets connects, it will invoke the socket:didConnectToHost:port: delegate method.
NSError *error = nil;
#if USE_SECURE_CONNECTION
uint16_t port = 443; // HTTPS
#else
uint16_t port = 80; // HTTP
#endif
if (![asyncSocket connectToHost:@"deusty.com" onPort:port error:&error])
{
DDLogError(@"Unable to connect to due to invalid configuration: %@", error);
}
else
{
DDLogVerbose(@"Connecting...");
}
#if USE_SECURE_CONNECTION
// The connect method above is asynchronous.
// At this point, the connection has been initiated, but hasn't completed.
// When the connection is establish, our socket:didConnectToHost:port: delegate method will be invoked.
//
// Now, for a secure connection we have to connect to the HTTPS server running on port 443.
// The SSL/TLS protocol runs atop TCP, so after the connection is established we want to start the TLS handshake.
//
// We already know this is what we want to do.
// Wouldn't it be convenient if we could tell the socket to queue the security upgrade now instead of waiting?
// Well in fact you can! This is part of the queued architecture of AsyncSocket.
//
// After the connection has been established, AsyncSocket will look in it's queue for the next task.
// There it will find, dequeue and execute our request to start the TLS security protocol.
//
// The options passed to the startTLS method are fully documented in the GCDAsyncSocket header file.
// The deusty server only has a development (self-signed) X.509 certificate.
// So we tell it not to attempt to validate the cert (cause if it did it would fail).
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
[asyncSocket startTLS:options];
#endif
// Normal iOS stuff...
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
DDLogVerbose(@"socket:didConnectToHost:%@ port:%hu", host, port);
// HTTP is a really simple protocol.
//
// If you don't already know all about it, this is one of the best resources I know (short and sweet):
// http://www.jmarshall.com/easy/http/
//
// We're just going to tell the server to send us the metadata (essentially) about a particular resource.
// The server will send an http response, and then immediately close the connection.
NSString *requestStr = @"HEAD / HTTP/1.0\r\nHost: deusty.com\r\n\r\n";
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:requestData withTimeout:-1.0 tag:0];
// Side Note:
//
// The AsyncSocket family supports queued reads and writes.
//
// This means that you don't have to wait for the socket to connect before issuing your read or write commands.
// If you do so before the socket is connected, it will simply queue the requests,
// and process them after the socket is connected.
// Also, you can issue multiple write commands (or read commands) at a time.
// You don't have to wait for one write operation to complete before sending another write command.
//
// The whole point is to make YOUR code easier to write, easier to read, and easier to maintain.
// Do networking stuff when it is easiest for you, or when it makes the most sense for you.
// AsyncSocket adapts to your schedule, not the other way around.
#if READ_HEADER_LINE_BY_LINE
// Now we tell the socket to read the first line of the http response header.
// As per the http protocol, we know each header line is terminated with a CRLF (carriage return, line feed).
[asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1.0 tag:0];
#else
// Now we tell the socket to read the full header for the http response.
// As per the http protocol, we know the header is terminated with two CRLF's (carriage return, line feed).
NSData *responseTerminatorData = [@"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding];
[asyncSocket readDataToData:responseTerminatorData withTimeout:-1.0 tag:0];
#endif
}
- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
// This method will be called if USE_SECURE_CONNECTION is set
DDLogVerbose(@"socketDidSecure:");
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
DDLogVerbose(@"socket:didWriteDataWithTag:");
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
DDLogVerbose(@"socket:didReadData:withTag:");
NSString *httpResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
#if READ_HEADER_LINE_BY_LINE
DDLogInfo(@"Line httpResponse: %@", httpResponse);
// As per the http protocol, we know the header is terminated with two CRLF's.
// In other words, an empty line.
if ([data length] == 2) // 2 bytes = CRLF
{
DDLogInfo(@"<done>");
}
else
{
// Read the next line of the header
[asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1.0 tag:0];
}
#else
DDLogInfo(@"Full httpResponse: %@", httpResponse);
#endif
[httpResponse release];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
// Since we requested HTTP/1.0, we expect the server to close the connection as soon as it has sent the response.
DDLogVerbose(@"socketDidDisconnect:withError: \"%@\"", err);
}
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/SimpleHTTPClient/Mobile/SimpleHTTPClient/SimpleHTTPClientAppDelegate.m
|
Objective-C
|
oos
| 8,428
|
#import <UIKit/UIKit.h>
@interface SimpleHTTPClientViewController : UIViewController {
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/SimpleHTTPClient/Mobile/SimpleHTTPClient/SimpleHTTPClientViewController.h
|
Objective-C
|
oos
| 102
|
//
// main.m
// SimpleHTTPClient
//
// Created by Robbie Hanson on 7/5/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/SimpleHTTPClient/Mobile/SimpleHTTPClient/main.m
|
Objective-C
|
oos
| 352
|
#import "SimpleHTTPClientViewController.h"
@implementation SimpleHTTPClientViewController
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/SimpleHTTPClient/Mobile/SimpleHTTPClient/SimpleHTTPClientViewController.m
|
Objective-C
|
oos
| 98
|
#import <UIKit/UIKit.h>
@class SimpleHTTPClientViewController;
@class GCDAsyncSocket;
@interface SimpleHTTPClientAppDelegate : NSObject <UIApplicationDelegate>
{
GCDAsyncSocket *asyncSocket;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet SimpleHTTPClientViewController *viewController;
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/SimpleHTTPClient/Mobile/SimpleHTTPClient/SimpleHTTPClientAppDelegate.h
|
Objective-C
|
oos
| 348
|
#import "SimpleHTTPClientAppDelegate.h"
#import "GCDAsyncSocket.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#define USE_SECURE_CONNECTION 0
#define READ_HEADER_LINE_BY_LINE 0
@implementation SimpleHTTPClientAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// AsyncSocket optionally uses the Lumberjack logging framework.
//
// Lumberjack is a professional logging framework. It's extremely fast and flexible.
// It also uses GCD, making it a great fit for GCDAsyncSocket.
//
// As mentioned earlier, enabling logging in GCDAsyncSocket is entirely optional.
// Doing so simply helps give you a deeper understanding of the inner workings of the library (if you care).
// You can do so at the top of GCDAsyncSocket.m,
// where you can also control things such as the log level,
// and whether or not logging should be asynchronous (helps to improve speed, and
// perfect for reducing interference with those pesky timing bugs in your code).
//
// There is a massive amount of documentation on the Lumberjack project page:
// http://code.google.com/p/cocoalumberjack/
//
// But this one line is all you need to instruct Lumberjack to spit out log statements to the Xcode console.
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Create our GCDAsyncSocket instance.
//
// Notice that we give it the normal delegate AND a delegate queue.
// The socket will do all of its operations in a background queue,
// and you can tell it which thread/queue to invoke your delegate on.
// In this case, we're just saying invoke us on the main thread.
// But you can see how trivial it would be to create your own queue,
// and parallelize your networking processing code by having your
// delegate methods invoked and run on background queues.
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
// Now we tell the ASYNCHRONOUS socket to connect.
//
// Recall that GCDAsyncSocket is ... asynchronous.
// This means when you tell the socket to connect, it will do so ... asynchronously.
// After all, do you want your main thread to block on a slow network connection?
//
// So what's with the BOOL return value, and error pointer?
// These are for early detection of obvious problems, such as:
//
// - The socket is already connected.
// - You passed in an invalid parameter.
// - The socket isn't configured properly.
//
// The error message might be something like "Attempting to connect without a delegate. Set a delegate first."
//
// When the asynchronous sockets connects, it will invoke the socket:didConnectToHost:port: delegate method.
NSError *error = nil;
#if USE_SECURE_CONNECTION
uint16_t port = 443; // HTTPS
#else
uint16_t port = 80; // HTTP
#endif
if (![asyncSocket connectToHost:@"deusty.com" onPort:port error:&error])
{
DDLogError(@"Unable to connect to due to invalid configuration: %@", error);
}
else
{
DDLogVerbose(@"Connecting...");
}
#if USE_SECURE_CONNECTION
// The connect method above is asynchronous.
// At this point, the connection has been initiated, but hasn't completed.
// When the connection is establish, our socket:didConnectToHost:port: delegate method will be invoked.
//
// Now, for a secure connection we have to connect to the HTTPS server running on port 443.
// The SSL/TLS protocol runs atop TCP, so after the connection is established we want to start the TLS handshake.
//
// We already know this is what we want to do.
// Wouldn't it be convenient if we could tell the socket to queue the security upgrade now instead of waiting?
// Well in fact you can! This is part of the queued architecture of AsyncSocket.
//
// After the connection has been established, AsyncSocket will look in it's queue for the next task.
// There it will find, dequeue and execute our request to start the TLS security protocol.
//
// The options passed to the startTLS method are fully documented in the GCDAsyncSocket header file.
// The deusty server only has a development (self-signed) X.509 certificate.
// So we tell it not to attempt to validate the cert (cause if it did it would fail).
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
[asyncSocket startTLS:options];
#endif
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
DDLogVerbose(@"socket:didConnectToHost:%@ port:%hu", host, port);
// HTTP is a really simple protocol.
//
// If you don't already know all about it, this is one of the best resources I know (short and sweet):
// http://www.jmarshall.com/easy/http/
//
// We're just going to tell the server to send us the metadata (essentially) about a particular resource.
// The server will send an http response, and then immediately close the connection.
NSString *requestStr = @"HEAD / HTTP/1.0\r\nHost: deusty.com\r\nConnection: Close\r\n\r\n";
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:requestData withTimeout:-1.0 tag:0];
// Side Note:
//
// The AsyncSocket family supports queued reads and writes.
//
// This means that you don't have to wait for the socket to connect before issuing your read or write commands.
// If you do so before the socket is connected, it will simply queue the requests,
// and process them after the socket is connected.
// Also, you can issue multiple write commands (or read commands) at a time.
// You don't have to wait for one write operation to complete before sending another write command.
//
// The whole point is to make YOUR code easier to write, easier to read, and easier to maintain.
// Do networking stuff when it is easiest for you, or when it makes the most sense for you.
// AsyncSocket adapts to your schedule, not the other way around.
#if READ_HEADER_LINE_BY_LINE
// Now we tell the socket to read the first line of the http response header.
// As per the http protocol, we know each header line is terminated with a CRLF (carriage return, line feed).
[asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1.0 tag:0];
#else
// Now we tell the socket to read the full header for the http response.
// As per the http protocol, we know the header is terminated with two CRLF's (carriage return, line feed).
NSData *responseTerminatorData = [@"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding];
[asyncSocket readDataToData:responseTerminatorData withTimeout:-1.0 tag:0];
#endif
}
- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
// This method will be called if USE_SECURE_CONNECTION is set
DDLogVerbose(@"socketDidSecure:");
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
DDLogVerbose(@"socket:didWriteDataWithTag:");
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
DDLogVerbose(@"socket:didReadData:withTag:");
NSString *httpResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
#if READ_HEADER_LINE_BY_LINE
DDLogInfo(@"Line httpResponse: %@", httpResponse);
// As per the http protocol, we know the header is terminated with two CRLF's.
// In other words, an empty line.
if ([data length] == 2) // 2 bytes = CRLF
{
DDLogInfo(@"<done>");
}
else
{
// Read the next line of the header
[asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1.0 tag:0];
}
#else
DDLogInfo(@"Full httpResponse: %@", httpResponse);
#endif
[httpResponse release];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
// Since we requested HTTP/1.0, we expect the server to close the connection as soon as it has sent the response.
DDLogVerbose(@"socketDidDisconnect:withError:%@", err);
}
@end
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/SimpleHTTPClient/Desktop/SimpleHTTPClient/SimpleHTTPClientAppDelegate.m
|
Objective-C
|
oos
| 8,085
|
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw9840\paperh8400
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
\f0\b\fs24 \cf0 Engineering:
\b0 \
Some people\
\
\b Human Interface Design:
\b0 \
Some other people\
\
\b Testing:
\b0 \
Hopefully not nobody\
\
\b Documentation:
\b0 \
Whoever\
\
\b With special thanks to:
\b0 \
Mom\
}
|
zzymoon-cocoaasyncsocket
|
GCD/Xcode/SimpleHTTPClient/Desktop/SimpleHTTPClient/en.lproj/Credits.rtf
|
Rich Text Format
|
oos
| 436
|