code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public HttpHeaders set(CharSequence name, Iterable<?> values) { return set(name.toString(), values); }
Sets a header with the specified name and values. If there is an existing header with the same name, it is removed. This getMethod can be represented approximately as the following code: <pre> headers.remove(name); for (Object v: values) { if (v == null) { break; } headers.add(name, v); } </pre> @param name The name of the headers being set @param values The values of the headers being set @return {@code this}
public HttpHeaders set(HttpHeaders headers) { checkNotNull(headers, "headers"); clear(); if (headers.isEmpty()) { return this; } for (Entry<String, String> entry : headers) { add(entry.getKey(), entry.getValue()); } return this; }
Cleans the current header entries and copies all header entries of the specified {@code headers}. @return {@code this}
public HttpHeaders setAll(HttpHeaders headers) { checkNotNull(headers, "headers"); if (headers.isEmpty()) { return this; } for (Entry<String, String> entry : headers) { set(entry.getKey(), entry.getValue()); } return this; }
Retains all current headers but calls {@link #set(String, Object)} for each entry in {@code headers} @param headers The headers used to {@link #set(String, Object)} values in this instance @return {@code this}
public boolean containsValue(CharSequence name, CharSequence value, boolean ignoreCase) { Iterator<? extends CharSequence> itr = valueCharSequenceIterator(name); while (itr.hasNext()) { if (containsCommaSeparatedTrimmed(itr.next(), value, ignoreCase)) { return true; } } return false; }
Returns {@code true} if a header with the {@code name} and {@code value} exists, {@code false} otherwise. This also handles multiple values that are separated with a {@code ,}. <p> If {@code ignoreCase} is {@code true} then a case insensitive compare is done on the value. @param name the name of the header to find @param value the value of the header to find @param ignoreCase {@code true} then a case insensitive compare is run to compare values. otherwise a case sensitive compare is run to compare values.
public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) { return contains(name.toString(), value.toString(), ignoreCase); }
Returns {@code true} if a header with the {@code name} and {@code value} exists, {@code false} otherwise. <p> If {@code ignoreCase} is {@code true} then a case insensitive compare is done on the value. @param name the name of the header to find @param value the value of the header to find @param ignoreCase {@code true} then a case insensitive compare is run to compare values. otherwise a case sensitive compare is run to compare values.
public DefaultHeaders<K, V, T> copy() { DefaultHeaders<K, V, T> copy = new DefaultHeaders<K, V, T>( hashingStrategy, valueConverter, nameValidator, entries.length); copy.addImpl(this); return copy; }
Returns a deep copy of this instance.
public static String ipv6toStr(byte[] src) { assert src.length == 16; StringBuilder sb = new StringBuilder(39); ipv6toStr(sb, src, 0, 8); return sb.toString(); }
Converts numeric IPv6 to standard (non-compressed) format.
protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { if (!closed) { ctx.fireExceptionCaught(ReadTimeoutException.INSTANCE); ctx.close(); closed = true; } }
Is called when a read timeout was detected.
public static ChannelUDT channelUDT(final Channel channel) { // bytes if (channel instanceof NioUdtByteAcceptorChannel) { return ((NioUdtByteAcceptorChannel) channel).javaChannel(); } if (channel instanceof NioUdtByteRendezvousChannel) { return ((NioUdtByteRendezvousChannel) channel).javaChannel(); } if (channel instanceof NioUdtByteConnectorChannel) { return ((NioUdtByteConnectorChannel) channel).javaChannel(); } // message if (channel instanceof NioUdtMessageAcceptorChannel) { return ((NioUdtMessageAcceptorChannel) channel).javaChannel(); } if (channel instanceof NioUdtMessageRendezvousChannel) { return ((NioUdtMessageRendezvousChannel) channel).javaChannel(); } if (channel instanceof NioUdtMessageConnectorChannel) { return ((NioUdtMessageConnectorChannel) channel).javaChannel(); } return null; }
Expose underlying {@link ChannelUDT} for debugging and monitoring. <p> @return underlying {@link ChannelUDT} or null, if parameter is not {@link UdtChannel}
static ServerSocketChannelUDT newAcceptorChannelUDT( final TypeUDT type) { try { return SelectorProviderUDT.from(type).openServerSocketChannel(); } catch (final IOException e) { throw new ChannelException("failed to open a server socket channel", e); } }
Convenience factory for {@link KindUDT#ACCEPTOR} channels.
static SocketChannelUDT newConnectorChannelUDT(final TypeUDT type) { try { return SelectorProviderUDT.from(type).openSocketChannel(); } catch (final IOException e) { throw new ChannelException("failed to open a socket channel", e); } }
Convenience factory for {@link KindUDT#CONNECTOR} channels.
static RendezvousChannelUDT newRendezvousChannelUDT( final TypeUDT type) { try { return SelectorProviderUDT.from(type).openRendezvousChannel(); } catch (final IOException e) { throw new ChannelException("failed to open a rendezvous channel", e); } }
Convenience factory for {@link KindUDT#RENDEZVOUS} channels.
public static SocketUDT socketUDT(final Channel channel) { final ChannelUDT channelUDT = channelUDT(channel); if (channelUDT == null) { return null; } else { return channelUDT.socketUDT(); } }
Expose underlying {@link SocketUDT} for debugging and monitoring. <p> @return underlying {@link SocketUDT} or null, if parameter is not {@link UdtChannel}
@SuppressWarnings("unchecked") @Override public T newChannel() { switch (kind) { case ACCEPTOR: switch (type) { case DATAGRAM: return (T) new NioUdtMessageAcceptorChannel(); case STREAM: return (T) new NioUdtByteAcceptorChannel(); default: throw new IllegalStateException("wrong type=" + type); } case CONNECTOR: switch (type) { case DATAGRAM: return (T) new NioUdtMessageConnectorChannel(); case STREAM: return (T) new NioUdtByteConnectorChannel(); default: throw new IllegalStateException("wrong type=" + type); } case RENDEZVOUS: switch (type) { case DATAGRAM: return (T) new NioUdtMessageRendezvousChannel(); case STREAM: return (T) new NioUdtByteRendezvousChannel(); default: throw new IllegalStateException("wrong type=" + type); } default: throw new IllegalStateException("wrong kind=" + kind); } }
Produce new {@link UdtChannel} based on factory {@link #kind()} and {@link #type()}
public String path() { if (path == null) { path = decodeComponent(uri, 0, pathEndIdx(), charset, true); } return path; }
Returns the decoded path string of the URI.
public Map<String, List<String>> parameters() { if (params == null) { params = decodeParams(uri, pathEndIdx(), charset, maxParams); } return params; }
Returns the decoded key-value parameter pairs of the URI.
public String rawQuery() { int start = pathEndIdx() + 1; return start < uri.length() ? uri.substring(start) : EMPTY_STRING; }
Returns raw query string of the URI.
protected IdleStateEvent newIdleStateEvent(IdleState state, boolean first) { switch (state) { case ALL_IDLE: return first ? IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT : IdleStateEvent.ALL_IDLE_STATE_EVENT; case READER_IDLE: return first ? IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT : IdleStateEvent.READER_IDLE_STATE_EVENT; case WRITER_IDLE: return first ? IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT : IdleStateEvent.WRITER_IDLE_STATE_EVENT; default: throw new IllegalArgumentException("Unhandled: state=" + state + ", first=" + first); } }
Returns a {@link IdleStateEvent}.
private boolean hasOutputChanged(ChannelHandlerContext ctx, boolean first) { if (observeOutput) { // We can take this shortcut if the ChannelPromises that got passed into write() // appear to complete. It indicates "change" on message level and we simply assume // that there's change happening on byte level. If the user doesn't observe channel // writability events then they'll eventually OOME and there's clearly a different // problem and idleness is least of their concerns. if (lastChangeCheckTimeStamp != lastWriteTime) { lastChangeCheckTimeStamp = lastWriteTime; // But this applies only if it's the non-first call. if (!first) { return true; } } Channel channel = ctx.channel(); Unsafe unsafe = channel.unsafe(); ChannelOutboundBuffer buf = unsafe.outboundBuffer(); if (buf != null) { int messageHashCode = System.identityHashCode(buf.current()); long pendingWriteBytes = buf.totalPendingWriteBytes(); if (messageHashCode != lastMessageHashCode || pendingWriteBytes != lastPendingWriteBytes) { lastMessageHashCode = messageHashCode; lastPendingWriteBytes = pendingWriteBytes; if (!first) { return true; } } long flushProgress = buf.currentProgress(); if (flushProgress != lastFlushProgress) { lastFlushProgress = flushProgress; if (!first) { return true; } } } } return false; }
Returns {@code true} if and only if the {@link IdleStateHandler} was constructed with {@link #observeOutput} enabled and there has been an observed change in the {@link ChannelOutboundBuffer} between two consecutive calls of this method. https://github.com/netty/netty/issues/6150
static int getUnsignedShort(ByteBuf buf, int offset) { return (buf.getByte(offset) & 0xFF) << 8 | buf.getByte(offset + 1) & 0xFF; }
Reads a big-endian unsigned short integer from the buffer.
static int getUnsignedMedium(ByteBuf buf, int offset) { return (buf.getByte(offset) & 0xFF) << 16 | (buf.getByte(offset + 1) & 0xFF) << 8 | buf.getByte(offset + 2) & 0xFF; }
Reads a big-endian unsigned medium integer from the buffer.
static int getUnsignedInt(ByteBuf buf, int offset) { return (buf.getByte(offset) & 0x7F) << 24 | (buf.getByte(offset + 1) & 0xFF) << 16 | (buf.getByte(offset + 2) & 0xFF) << 8 | buf.getByte(offset + 3) & 0xFF; }
Reads a big-endian (31-bit) integer from the buffer.
static int getSignedInt(ByteBuf buf, int offset) { return (buf.getByte(offset) & 0xFF) << 24 | (buf.getByte(offset + 1) & 0xFF) << 16 | (buf.getByte(offset + 2) & 0xFF) << 8 | buf.getByte(offset + 3) & 0xFF; }
Reads a big-endian signed integer from the buffer.
static void validateHeaderName(CharSequence name) { if (name == null) { throw new NullPointerException("name"); } if (name.length() == 0) { throw new IllegalArgumentException( "name cannot be length zero"); } // Since name may only contain ascii characters, for valid names // name.length() returns the number of bytes when UTF-8 encoded. if (name.length() > SPDY_MAX_NV_LENGTH) { throw new IllegalArgumentException( "name exceeds allowable length: " + name); } for (int i = 0; i < name.length(); i ++) { char c = name.charAt(i); if (c == 0) { throw new IllegalArgumentException( "name contains null character: " + name); } if (c >= 'A' && c <= 'Z') { throw new IllegalArgumentException("name must be all lower case."); } if (c > 127) { throw new IllegalArgumentException( "name contains non-ascii character: " + name); } } }
Validate a SPDY header name.
static void validateHeaderValue(CharSequence value) { if (value == null) { throw new NullPointerException("value"); } for (int i = 0; i < value.length(); i ++) { char c = value.charAt(i); if (c == 0) { throw new IllegalArgumentException( "value contains null character: " + value); } } }
Validate a SPDY header value. Does not validate max length.
boolean allocateTiny(PoolArena<?> area, PooledByteBuf<?> buf, int reqCapacity, int normCapacity) { return allocate(cacheForTiny(area, normCapacity), buf, reqCapacity); }
Try to allocate a tiny buffer out of the cache. Returns {@code true} if successful {@code false} otherwise
boolean allocateSmall(PoolArena<?> area, PooledByteBuf<?> buf, int reqCapacity, int normCapacity) { return allocate(cacheForSmall(area, normCapacity), buf, reqCapacity); }
Try to allocate a small buffer out of the cache. Returns {@code true} if successful {@code false} otherwise
boolean allocateNormal(PoolArena<?> area, PooledByteBuf<?> buf, int reqCapacity, int normCapacity) { return allocate(cacheForNormal(area, normCapacity), buf, reqCapacity); }
Try to allocate a small buffer out of the cache. Returns {@code true} if successful {@code false} otherwise
@SuppressWarnings({ "unchecked", "rawtypes" }) boolean add(PoolArena<?> area, PoolChunk chunk, ByteBuffer nioBuffer, long handle, int normCapacity, SizeClass sizeClass) { MemoryRegionCache<?> cache = cache(area, normCapacity, sizeClass); if (cache == null) { return false; } return cache.add(chunk, nioBuffer, handle); }
Add {@link PoolChunk} and {@code handle} to the cache if there is enough room. Returns {@code true} if it fit into the cache {@code false} otherwise.
void free(boolean finalizer) { // As free() may be called either by the finalizer or by FastThreadLocal.onRemoval(...) we need to ensure // we only call this one time. if (freed.compareAndSet(false, true)) { int numFreed = free(tinySubPageDirectCaches, finalizer) + free(smallSubPageDirectCaches, finalizer) + free(normalDirectCaches, finalizer) + free(tinySubPageHeapCaches, finalizer) + free(smallSubPageHeapCaches, finalizer) + free(normalHeapCaches, finalizer); if (numFreed > 0 && logger.isDebugEnabled()) { logger.debug("Freed {} thread-local buffer(s) from thread: {}", numFreed, Thread.currentThread().getName()); } if (directArena != null) { directArena.numThreadCaches.getAndDecrement(); } if (heapArena != null) { heapArena.numThreadCaches.getAndDecrement(); } } }
Should be called if the Thread that uses this cache is about to exist to release resources out of the cache
public CorsConfigBuilder exposeHeaders(final CharSequence... headers) { for (CharSequence header: headers) { exposeHeaders.add(header.toString()); } return this; }
Specifies the headers to be exposed to calling clients. During a simple CORS request, only certain response headers are made available by the browser, for example using: <pre> xhr.getResponseHeader(HttpHeaderNames.CONTENT_TYPE); </pre> The headers that are available by default are: <ul> <li>Cache-Control</li> <li>Content-Language</li> <li>Content-Type</li> <li>Expires</li> <li>Last-Modified</li> <li>Pragma</li> </ul> To expose other headers they need to be specified which is what this method enables by adding the headers to the CORS 'Access-Control-Expose-Headers' response header. @param headers the values to be added to the 'Access-Control-Expose-Headers' response header @return {@link CorsConfigBuilder} to support method chaining.
public CorsConfigBuilder allowedRequestHeaders(final CharSequence... headers) { for (CharSequence header: headers) { requestHeaders.add(header.toString()); } return this; }
Specifies the if headers that should be returned in the CORS 'Access-Control-Allow-Headers' response header. If a client specifies headers on the request, for example by calling: <pre> xhr.setRequestHeader('My-Custom-Header', "SomeValue"); </pre> the server will receive the above header name in the 'Access-Control-Request-Headers' of the preflight request. The server will then decide if it allows this header to be sent for the real request (remember that a preflight is not the real request but a request asking the server if it allow a request). @param headers the headers to be added to the preflight 'Access-Control-Allow-Headers' response header. @return {@link CorsConfigBuilder} to support method chaining.
public CorsConfigBuilder preflightResponseHeader(final CharSequence name, final Object... values) { if (values.length == 1) { preflightHeaders.put(name, new ConstantValueGenerator(values[0])); } else { preflightResponseHeader(name, Arrays.asList(values)); } return this; }
Returns HTTP response headers that should be added to a CORS preflight response. An intermediary like a load balancer might require that a CORS preflight request have certain headers set. This enables such headers to be added. @param name the name of the HTTP header. @param values the values for the HTTP header. @return {@link CorsConfigBuilder} to support method chaining.
public <T> CorsConfigBuilder preflightResponseHeader(final CharSequence name, final Iterable<T> value) { preflightHeaders.put(name, new ConstantValueGenerator(value)); return this; }
Returns HTTP response headers that should be added to a CORS preflight response. An intermediary like a load balancer might require that a CORS preflight request have certain headers set. This enables such headers to be added. @param name the name of the HTTP header. @param value the values for the HTTP header. @param <T> the type of values that the Iterable contains. @return {@link CorsConfigBuilder} to support method chaining.
public <T> CorsConfigBuilder preflightResponseHeader(final CharSequence name, final Callable<T> valueGenerator) { preflightHeaders.put(name, valueGenerator); return this; }
Returns HTTP response headers that should be added to a CORS preflight response. An intermediary like a load balancer might require that a CORS preflight request have certain headers set. This enables such headers to be added. Some values must be dynamically created when the HTTP response is created, for example the 'Date' response header. This can be accomplished by using a Callable which will have its 'call' method invoked when the HTTP response is created. @param name the name of the HTTP header. @param valueGenerator a Callable which will be invoked at HTTP response creation. @param <T> the type of the value that the Callable can return. @return {@link CorsConfigBuilder} to support method chaining.
public CorsConfig build() { if (preflightHeaders.isEmpty() && !noPreflightHeaders) { preflightHeaders.put(HttpHeaderNames.DATE, DateValueGenerator.INSTANCE); preflightHeaders.put(HttpHeaderNames.CONTENT_LENGTH, new ConstantValueGenerator("0")); } return new CorsConfig(this); }
Builds a {@link CorsConfig} with settings specified by previous method calls. @return {@link CorsConfig} the configured CorsConfig instance.
protected void cancelScheduledTasks() { assert inEventLoop(); PriorityQueue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; if (isNullOrEmpty(scheduledTaskQueue)) { return; } final ScheduledFutureTask<?>[] scheduledTasks = scheduledTaskQueue.toArray(new ScheduledFutureTask<?>[0]); for (ScheduledFutureTask<?> task: scheduledTasks) { task.cancelWithoutRemove(false); } scheduledTaskQueue.clearIgnoringIndexes(); }
Cancel all scheduled tasks. This method MUST be called only when {@link #inEventLoop()} is {@code true}.
protected final Runnable pollScheduledTask(long nanoTime) { assert inEventLoop(); Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); if (scheduledTask == null) { return null; } if (scheduledTask.deadlineNanos() <= nanoTime) { scheduledTaskQueue.remove(); return scheduledTask; } return null; }
Return the {@link Runnable} which is ready to be executed with the given {@code nanoTime}. You should use {@link #nanoTime()} to retrieve the correct {@code nanoTime}.
protected final long nextScheduledTaskNano() { Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); if (scheduledTask == null) { return -1; } return Math.max(0, scheduledTask.deadlineNanos() - nanoTime()); }
Return the nanoseconds when the next scheduled task is ready to be run or {@code -1} if no task is scheduled.
protected final boolean hasScheduledTasks() { Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); return scheduledTask != null && scheduledTask.deadlineNanos() <= nanoTime(); }
Returns {@code true} if a scheduled task is ready for processing.
public static ChannelMatcher compose(ChannelMatcher... matchers) { if (matchers.length < 1) { throw new IllegalArgumentException("matchers must at least contain one element"); } if (matchers.length == 1) { return matchers[0]; } return new CompositeMatcher(matchers); }
Return a composite of the given {@link ChannelMatcher}s. This means all {@link ChannelMatcher} must return {@code true} to match.
@Override public boolean cancel(boolean mayInterruptIfRunning) { boolean canceled = super.cancel(mayInterruptIfRunning); if (canceled) { ((AbstractScheduledEventExecutor) executor()).removeScheduled(this); } return canceled; }
{@inheritDoc} @param mayInterruptIfRunning this value has no effect in this implementation.
private static Integer sysctlGetInt(String sysctlKey) throws IOException { Process process = new ProcessBuilder("sysctl", sysctlKey).start(); try { InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { String line = br.readLine(); if (line.startsWith(sysctlKey)) { for (int i = line.length() - 1; i > sysctlKey.length(); --i) { if (!Character.isDigit(line.charAt(i))) { return Integer.valueOf(line.substring(i + 1, line.length())); } } } return null; } finally { br.close(); } } finally { if (process != null) { process.destroy(); } } }
This will execute <a href ="https://www.freebsd.org/cgi/man.cgi?sysctl(8)">sysctl</a> with the {@code sysctlKey} which is expected to return the numeric value for for {@code sysctlKey}. @param sysctlKey The key which the return value corresponds to. @return The <a href ="https://www.freebsd.org/cgi/man.cgi?sysctl(8)">sysctl</a> value for {@code sysctlKey}.
public static byte[] createByteArrayFromIpAddressString(String ipAddressString) { if (isValidIpV4Address(ipAddressString)) { return validIpV4ToBytes(ipAddressString); } if (isValidIpV6Address(ipAddressString)) { if (ipAddressString.charAt(0) == '[') { ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1); } int percentPos = ipAddressString.indexOf('%'); if (percentPos >= 0) { ipAddressString = ipAddressString.substring(0, percentPos); } return getIPv6ByName(ipAddressString, true); } return null; }
Creates an byte[] based on an ipAddressString. No error handling is performed here.
static byte[] validIpV4ToBytes(String ip) { int i; return new byte[] { ipv4WordToByte(ip, 0, i = ip.indexOf('.', 1)), ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)), ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)), ipv4WordToByte(ip, i + 1, ip.length()) }; }
visible for tests
public static String intToIpAddress(int i) { StringBuilder buf = new StringBuilder(15); buf.append(i >> 24 & 0xff); buf.append('.'); buf.append(i >> 16 & 0xff); buf.append('.'); buf.append(i >> 8 & 0xff); buf.append('.'); buf.append(i & 0xff); return buf.toString(); }
Converts a 32-bit integer into an IPv4 address.
public static String bytesToIpAddress(byte[] bytes, int offset, int length) { switch (length) { case 4: { return new StringBuilder(15) .append(bytes[offset] & 0xff) .append('.') .append(bytes[offset + 1] & 0xff) .append('.') .append(bytes[offset + 2] & 0xff) .append('.') .append(bytes[offset + 3] & 0xff).toString(); } case 16: return toAddressString(bytes, offset, false); default: throw new IllegalArgumentException("length: " + length + " (expected: 4 or 16)"); } }
Converts 4-byte or 16-byte data into an IPv4 or IPv6 string respectively. @throws IllegalArgumentException if {@code length} is not {@code 4} nor {@code 16}
public static Inet6Address getByName(CharSequence ip, boolean ipv4Mapped) { byte[] bytes = getIPv6ByName(ip, ipv4Mapped); if (bytes == null) { return null; } try { return Inet6Address.getByAddress(null, bytes, -1); } catch (UnknownHostException e) { throw new RuntimeException(e); // Should never happen } }
Returns the {@link Inet6Address} representation of a {@link CharSequence} IP address. <p> The {@code ipv4Mapped} parameter specifies how IPv4 addresses should be treated. "IPv4 mapped" format as defined in <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> is supported. @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address} @param ipv4Mapped <ul> <li>{@code true} To allow IPv4 mapped inputs to be translated into {@link Inet6Address}</li> <li>{@code false} Consider IPv4 mapped addresses as invalid.</li> </ul> @return {@link Inet6Address} representation of the {@code ip} or {@code null} if not a valid IP address.
private static byte[] getIPv6ByName(CharSequence ip, boolean ipv4Mapped) { final byte[] bytes = new byte[IPV6_BYTE_COUNT]; final int ipLength = ip.length(); int compressBegin = 0; int compressLength = 0; int currentIndex = 0; int value = 0; int begin = -1; int i = 0; int ipv6Separators = 0; int ipv4Separators = 0; int tmp; boolean needsShift = false; for (; i < ipLength; ++i) { final char c = ip.charAt(i); switch (c) { case ':': ++ipv6Separators; if (i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR || ipv4Separators > 0 || ipv6Separators > IPV6_MAX_SEPARATORS || currentIndex + 1 >= bytes.length) { return null; } value <<= (IPV6_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2; if (compressLength > 0) { compressLength -= 2; } // The value integer holds at most 4 bytes from right (most significant) to left (least significant). // The following bit shifting is used to extract and re-order the individual bytes to achieve a // left (most significant) to right (least significant) ordering. bytes[currentIndex++] = (byte) (((value & 0xf) << 4) | ((value >> 4) & 0xf)); bytes[currentIndex++] = (byte) ((((value >> 8) & 0xf) << 4) | ((value >> 12) & 0xf)); tmp = i + 1; if (tmp < ipLength && ip.charAt(tmp) == ':') { ++tmp; if (compressBegin != 0 || (tmp < ipLength && ip.charAt(tmp) == ':')) { return null; } ++ipv6Separators; needsShift = ipv6Separators == 2 && value == 0; compressBegin = currentIndex; compressLength = bytes.length - compressBegin - 2; ++i; } value = 0; begin = -1; break; case '.': ++ipv4Separators; tmp = i - begin; // tmp is the length of the current segment. if (tmp > IPV4_MAX_CHAR_BETWEEN_SEPARATOR || begin < 0 || ipv4Separators > IPV4_SEPARATORS || (ipv6Separators > 0 && (currentIndex + compressLength < 12)) || i + 1 >= ipLength || currentIndex >= bytes.length || ipv4Separators == 1 && // We also parse pure IPv4 addresses as IPv4-Mapped for ease of use. ((!ipv4Mapped || currentIndex != 0 && !isValidIPv4Mapped(bytes, currentIndex, compressBegin, compressLength)) || (tmp == 3 && (!isValidNumericChar(ip.charAt(i - 1)) || !isValidNumericChar(ip.charAt(i - 2)) || !isValidNumericChar(ip.charAt(i - 3))) || tmp == 2 && (!isValidNumericChar(ip.charAt(i - 1)) || !isValidNumericChar(ip.charAt(i - 2))) || tmp == 1 && !isValidNumericChar(ip.charAt(i - 1))))) { return null; } value <<= (IPV4_MAX_CHAR_BETWEEN_SEPARATOR - tmp) << 2; // The value integer holds at most 3 bytes from right (most significant) to left (least significant). // The following bit shifting is to restructure the bytes to be left (most significant) to // right (least significant) while also accounting for each IPv4 digit is base 10. begin = (value & 0xf) * 100 + ((value >> 4) & 0xf) * 10 + ((value >> 8) & 0xf); if (begin < 0 || begin > 255) { return null; } bytes[currentIndex++] = (byte) begin; value = 0; begin = -1; break; default: if (!isValidHexChar(c) || (ipv4Separators > 0 && !isValidNumericChar(c))) { return null; } if (begin < 0) { begin = i; } else if (i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR) { return null; } // The value is treated as a sort of array of numbers because we are dealing with // at most 4 consecutive bytes we can use bit shifting to accomplish this. // The most significant byte will be encountered first, and reside in the right most // position of the following integer value += StringUtil.decodeHexNibble(c) << ((i - begin) << 2); break; } } final boolean isCompressed = compressBegin > 0; // Finish up last set of data that was accumulated in the loop (or before the loop) if (ipv4Separators > 0) { if (begin > 0 && i - begin > IPV4_MAX_CHAR_BETWEEN_SEPARATOR || ipv4Separators != IPV4_SEPARATORS || currentIndex >= bytes.length) { return null; } if (ipv6Separators == 0) { compressLength = 12; } else if (ipv6Separators >= IPV6_MIN_SEPARATORS && (!isCompressed && (ipv6Separators == 6 && ip.charAt(0) != ':') || isCompressed && (ipv6Separators < IPV6_MAX_SEPARATORS && (ip.charAt(0) != ':' || compressBegin <= 2)))) { compressLength -= 2; } else { return null; } value <<= (IPV4_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2; // The value integer holds at most 3 bytes from right (most significant) to left (least significant). // The following bit shifting is to restructure the bytes to be left (most significant) to // right (least significant) while also accounting for each IPv4 digit is base 10. begin = (value & 0xf) * 100 + ((value >> 4) & 0xf) * 10 + ((value >> 8) & 0xf); if (begin < 0 || begin > 255) { return null; } bytes[currentIndex++] = (byte) begin; } else { tmp = ipLength - 1; if (begin > 0 && i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR || ipv6Separators < IPV6_MIN_SEPARATORS || !isCompressed && (ipv6Separators + 1 != IPV6_MAX_SEPARATORS || ip.charAt(0) == ':' || ip.charAt(tmp) == ':') || isCompressed && (ipv6Separators > IPV6_MAX_SEPARATORS || (ipv6Separators == IPV6_MAX_SEPARATORS && (compressBegin <= 2 && ip.charAt(0) != ':' || compressBegin >= 14 && ip.charAt(tmp) != ':'))) || currentIndex + 1 >= bytes.length || begin < 0 && ip.charAt(tmp - 1) != ':' || compressBegin > 2 && ip.charAt(0) == ':') { return null; } if (begin >= 0 && i - begin <= IPV6_MAX_CHAR_BETWEEN_SEPARATOR) { value <<= (IPV6_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2; } // The value integer holds at most 4 bytes from right (most significant) to left (least significant). // The following bit shifting is used to extract and re-order the individual bytes to achieve a // left (most significant) to right (least significant) ordering. bytes[currentIndex++] = (byte) (((value & 0xf) << 4) | ((value >> 4) & 0xf)); bytes[currentIndex++] = (byte) ((((value >> 8) & 0xf) << 4) | ((value >> 12) & 0xf)); } i = currentIndex + compressLength; if (needsShift || i >= bytes.length) { // Right shift array if (i >= bytes.length) { ++compressBegin; } for (i = currentIndex; i < bytes.length; ++i) { for (begin = bytes.length - 1; begin >= compressBegin; --begin) { bytes[begin] = bytes[begin - 1]; } bytes[begin] = 0; ++compressBegin; } } else { // Selectively move elements for (i = 0; i < compressLength; ++i) { begin = i + compressBegin; currentIndex = begin + compressLength; if (currentIndex < bytes.length) { bytes[currentIndex] = bytes[begin]; bytes[begin] = 0; } else { break; } } } if (ipv4Separators > 0) { // We only support IPv4-Mapped addresses [1] because IPv4-Compatible addresses are deprecated [2]. // [1] https://tools.ietf.org/html/rfc4291#section-2.5.5.2 // [2] https://tools.ietf.org/html/rfc4291#section-2.5.5.1 bytes[10] = bytes[11] = (byte) 0xff; } return bytes; }
Returns the byte array representation of a {@link CharSequence} IP address. <p> The {@code ipv4Mapped} parameter specifies how IPv4 addresses should be treated. "IPv4 mapped" format as defined in <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> is supported. @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address} @param ipv4Mapped <ul> <li>{@code true} To allow IPv4 mapped inputs to be translated into {@link Inet6Address}</li> <li>{@code false} Consider IPv4 mapped addresses as invalid.</li> </ul> @return byte array representation of the {@code ip} or {@code null} if not a valid IP address.
public static String toSocketAddressString(InetSocketAddress addr) { String port = String.valueOf(addr.getPort()); final StringBuilder sb; if (addr.isUnresolved()) { String hostname = getHostname(addr); sb = newSocketAddressStringBuilder(hostname, port, !isValidIpV6Address(hostname)); } else { InetAddress address = addr.getAddress(); String hostString = toAddressString(address); sb = newSocketAddressStringBuilder(hostString, port, address instanceof Inet4Address); } return sb.append(':').append(port).toString(); }
Returns the {@link String} representation of an {@link InetSocketAddress}. <p> The output does not include Scope ID. @param addr {@link InetSocketAddress} to be converted to an address string @return {@code String} containing the text-formatted IP address
public static String toSocketAddressString(String host, int port) { String portStr = String.valueOf(port); return newSocketAddressStringBuilder( host, portStr, !isValidIpV6Address(host)).append(':').append(portStr).toString(); }
Returns the {@link String} representation of a host port combo.
public static String toAddressString(InetAddress ip, boolean ipv4Mapped) { if (ip instanceof Inet4Address) { return ip.getHostAddress(); } if (!(ip instanceof Inet6Address)) { throw new IllegalArgumentException("Unhandled type: " + ip); } return toAddressString(ip.getAddress(), 0, ipv4Mapped); }
Returns the {@link String} representation of an {@link InetAddress}. <ul> <li>Inet4Address results are identical to {@link InetAddress#getHostAddress()}</li> <li>Inet6Address results adhere to <a href="http://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a> if {@code ipv4Mapped} is false. If {@code ipv4Mapped} is true then "IPv4 mapped" format from <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> will be supported. The compressed result will always obey the compression rules defined in <a href="http://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li> </ul> <p> The output does not include Scope ID. @param ip {@link InetAddress} to be converted to an address string @param ipv4Mapped <ul> <li>{@code true} to stray from strict rfc 5952 and support the "IPv4 mapped" format defined in <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> while still following the updated guidelines in <a href="http://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li> <li>{@code false} to strictly follow rfc 5952</li> </ul> @return {@code String} containing the text-formatted IP address
public static String getHostname(InetSocketAddress addr) { return PlatformDependent.javaVersion() >= 7 ? addr.getHostString() : addr.getHostName(); }
Returns {@link InetSocketAddress#getHostString()} if Java >= 7, or {@link InetSocketAddress#getHostName()} otherwise. @param addr The address @return the host string
@Deprecated public final long sslCtxPointer() { Lock readerLock = ctxLock.readLock(); readerLock.lock(); try { return SSLContext.getSslCtx(ctx); } finally { readerLock.unlock(); } }
Returns the pointer to the {@code SSL_CTX} object for this {@link ReferenceCountedOpenSslContext}. Be aware that it is freed as soon as the {@link #release()} method is called. At this point {@code 0} will be returned. @deprecated this method is considered unsafe as the returned pointer may be released later. Dont use it!
@UnstableApi public final void setPrivateKeyMethod(OpenSslPrivateKeyMethod method) { ObjectUtil.checkNotNull(method, "method"); Lock writerLock = ctxLock.writeLock(); writerLock.lock(); try { SSLContext.setPrivateKeyMethod(ctx, new PrivateKeyMethod(engineMap, method)); } finally { writerLock.unlock(); } }
Set the {@link OpenSslPrivateKeyMethod} to use. This allows to offload private-key operations if needed. This method is currently only supported when {@code BoringSSL} is used. @param method method to use.
private void destroy() { Lock writerLock = ctxLock.writeLock(); writerLock.lock(); try { if (ctx != 0) { if (enableOcsp) { SSLContext.disableOcsp(ctx); } SSLContext.free(ctx); ctx = 0; OpenSslSessionContext context = sessionContext(); if (context != null) { context.destroy(); } } } finally { writerLock.unlock(); } }
producing a segfault.
@SuppressWarnings("deprecation") static OpenSslApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config) { if (config == null) { return NONE_PROTOCOL_NEGOTIATOR; } switch (config.protocol()) { case NONE: return NONE_PROTOCOL_NEGOTIATOR; case ALPN: case NPN: case NPN_AND_ALPN: switch (config.selectedListenerFailureBehavior()) { case CHOOSE_MY_LAST_PROTOCOL: case ACCEPT: switch (config.selectorFailureBehavior()) { case CHOOSE_MY_LAST_PROTOCOL: case NO_ADVERTISE: return new OpenSslDefaultApplicationProtocolNegotiator( config); default: throw new UnsupportedOperationException( new StringBuilder("OpenSSL provider does not support ") .append(config.selectorFailureBehavior()) .append(" behavior").toString()); } default: throw new UnsupportedOperationException( new StringBuilder("OpenSSL provider does not support ") .append(config.selectedListenerFailureBehavior()) .append(" behavior").toString()); } default: throw new Error(); } }
Translate a {@link ApplicationProtocolConfig} object to a {@link OpenSslApplicationProtocolNegotiator} object. @param config The configuration which defines the translation @return The results of the translation
static long toBIO(ByteBufAllocator allocator, PrivateKey key) throws Exception { if (key == null) { return 0; } PemEncoded pem = PemPrivateKey.toPEM(allocator, true, key); try { return toBIO(allocator, pem.retain()); } finally { pem.release(); } }
Return the pointer to a <a href="https://www.openssl.org/docs/crypto/BIO_get_mem_ptr.html">in-memory BIO</a> or {@code 0} if the {@code key} is {@code null}. The BIO contains the content of the {@code key}.
static long toBIO(ByteBufAllocator allocator, X509Certificate... certChain) throws Exception { if (certChain == null) { return 0; } if (certChain.length == 0) { throw new IllegalArgumentException("certChain can't be empty"); } PemEncoded pem = PemX509Certificate.toPEM(allocator, true, certChain); try { return toBIO(allocator, pem.retain()); } finally { pem.release(); } }
Return the pointer to a <a href="https://www.openssl.org/docs/crypto/BIO_get_mem_ptr.html">in-memory BIO</a> or {@code 0} if the {@code certChain} is {@code null}. The BIO contains the content of the {@code certChain}.
static OpenSslKeyMaterialProvider providerFor(KeyManagerFactory factory, String password) { if (factory instanceof OpenSslX509KeyManagerFactory) { return ((OpenSslX509KeyManagerFactory) factory).newProvider(); } X509KeyManager keyManager = chooseX509KeyManager(factory.getKeyManagers()); if (factory instanceof OpenSslCachingX509KeyManagerFactory) { // The user explicit used OpenSslCachingX509KeyManagerFactory which signals us that its fine to cache. return new OpenSslCachingKeyMaterialProvider(keyManager, password); } // We can not be sure if the material may change at runtime so we will not cache it. return new OpenSslKeyMaterialProvider(keyManager, password); }
Returns the {@link OpenSslKeyMaterialProvider} that should be used for OpenSSL. Depending on the given {@link KeyManagerFactory} this may cache the {@link OpenSslKeyMaterial} for better performance if it can ensure that the same material is always returned for the same alias.
public static String stackTraceToString(Throwable cause) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(out); cause.printStackTrace(pout); pout.flush(); try { return new String(out.toByteArray()); } finally { try { out.close(); } catch (IOException ignore) { // ignore as should never happen } } }
Gets the stack trace from a Throwable as a String. @param cause the {@link Throwable} to be examined @return the stack trace as generated by {@link Throwable#printStackTrace(java.io.PrintWriter)} method.
public void addMessage(Object msg, int size, ChannelPromise promise) { Entry entry = Entry.newInstance(msg, size, total(msg), promise); if (tailEntry == null) { flushedEntry = null; } else { Entry tail = tailEntry; tail.next = entry; } tailEntry = entry; if (unflushedEntry == null) { unflushedEntry = entry; } // increment pending bytes after adding message to the unflushed arrays. // See https://github.com/netty/netty/issues/1619 incrementPendingOutboundBytes(entry.pendingSize, false); }
Add given message to this {@link ChannelOutboundBuffer}. The given {@link ChannelPromise} will be notified once the message was written.
public void addFlush() { // There is no need to process all entries if there was already a flush before and no new messages // where added in the meantime. // // See https://github.com/netty/netty/issues/2577 Entry entry = unflushedEntry; if (entry != null) { if (flushedEntry == null) { // there is no flushedEntry yet, so start with the entry flushedEntry = entry; } do { flushed ++; if (!entry.promise.setUncancellable()) { // Was cancelled so make sure we free up memory and notify about the freed bytes int pending = entry.cancel(); decrementPendingOutboundBytes(pending, false, true); } entry = entry.next; } while (entry != null); // All flushed so reset unflushedEntry unflushedEntry = null; } }
Add a flush to this {@link ChannelOutboundBuffer}. This means all previous added messages are marked as flushed and so you will be able to handle them.
public Object current() { Entry entry = flushedEntry; if (entry == null) { return null; } return entry.msg; }
Return the current message to write or {@code null} if nothing was flushed before and so is ready to be written.
public void progress(long amount) { Entry e = flushedEntry; assert e != null; ChannelPromise p = e.promise; long progress = e.progress + amount; e.progress = progress; if (p instanceof ChannelProgressivePromise) { ((ChannelProgressivePromise) p).tryProgress(progress, e.total); } }
Notify the {@link ChannelPromise} of the current message about writing progress.
public boolean remove() { Entry e = flushedEntry; if (e == null) { clearNioBuffers(); return false; } Object msg = e.msg; ChannelPromise promise = e.promise; int size = e.pendingSize; removeEntry(e); if (!e.cancelled) { // only release message, notify and decrement if it was not canceled before. ReferenceCountUtil.safeRelease(msg); safeSuccess(promise); decrementPendingOutboundBytes(size, false, true); } // recycle the entry e.recycle(); return true; }
Will remove the current message, mark its {@link ChannelPromise} as success and return {@code true}. If no flushed message exists at the time this method is called it will return {@code false} to signal that no more messages are ready to be handled.
public void removeBytes(long writtenBytes) { for (;;) { Object msg = current(); if (!(msg instanceof ByteBuf)) { assert writtenBytes == 0; break; } final ByteBuf buf = (ByteBuf) msg; final int readerIndex = buf.readerIndex(); final int readableBytes = buf.writerIndex() - readerIndex; if (readableBytes <= writtenBytes) { if (writtenBytes != 0) { progress(readableBytes); writtenBytes -= readableBytes; } remove(); } else { // readableBytes > writtenBytes if (writtenBytes != 0) { buf.readerIndex(readerIndex + (int) writtenBytes); progress(writtenBytes); } break; } } clearNioBuffers(); }
Removes the fully written entries and update the reader index of the partially written entry. This operation assumes all messages in this buffer is {@link ByteBuf}.
private void clearNioBuffers() { int count = nioBufferCount; if (count > 0) { nioBufferCount = 0; Arrays.fill(NIO_BUFFERS.get(), 0, count, null); } }
See https://github.com/netty/netty/issues/3837
public ByteBuffer[] nioBuffers(int maxCount, long maxBytes) { assert maxCount > 0; assert maxBytes > 0; long nioBufferSize = 0; int nioBufferCount = 0; final InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); ByteBuffer[] nioBuffers = NIO_BUFFERS.get(threadLocalMap); Entry entry = flushedEntry; while (isFlushedEntry(entry) && entry.msg instanceof ByteBuf) { if (!entry.cancelled) { ByteBuf buf = (ByteBuf) entry.msg; final int readerIndex = buf.readerIndex(); final int readableBytes = buf.writerIndex() - readerIndex; if (readableBytes > 0) { if (maxBytes - readableBytes < nioBufferSize && nioBufferCount != 0) { // If the nioBufferSize + readableBytes will overflow maxBytes, and there is at least one entry // we stop populate the ByteBuffer array. This is done for 2 reasons: // 1. bsd/osx don't allow to write more bytes then Integer.MAX_VALUE with one writev(...) call // and so will return 'EINVAL', which will raise an IOException. On Linux it may work depending // on the architecture and kernel but to be safe we also enforce the limit here. // 2. There is no sense in putting more data in the array than is likely to be accepted by the // OS. // // See also: // - https://www.freebsd.org/cgi/man.cgi?query=write&sektion=2 // - http://linux.die.net/man/2/writev break; } nioBufferSize += readableBytes; int count = entry.count; if (count == -1) { //noinspection ConstantValueVariableUse entry.count = count = buf.nioBufferCount(); } int neededSpace = min(maxCount, nioBufferCount + count); if (neededSpace > nioBuffers.length) { nioBuffers = expandNioBufferArray(nioBuffers, neededSpace, nioBufferCount); NIO_BUFFERS.set(threadLocalMap, nioBuffers); } if (count == 1) { ByteBuffer nioBuf = entry.buf; if (nioBuf == null) { // cache ByteBuffer as it may need to create a new ByteBuffer instance if its a // derived buffer entry.buf = nioBuf = buf.internalNioBuffer(readerIndex, readableBytes); } nioBuffers[nioBufferCount++] = nioBuf; } else { // The code exists in an extra method to ensure the method is not too big to inline as this // branch is not very likely to get hit very frequently. nioBufferCount = nioBuffers(entry, buf, nioBuffers, nioBufferCount, maxCount); } if (nioBufferCount == maxCount) { break; } } } entry = entry.next; } this.nioBufferCount = nioBufferCount; this.nioBufferSize = nioBufferSize; return nioBuffers; }
Returns an array of direct NIO buffers if the currently pending messages are made of {@link ByteBuf} only. {@link #nioBufferCount()} and {@link #nioBufferSize()} will return the number of NIO buffers in the returned array and the total number of readable bytes of the NIO buffers respectively. <p> Note that the returned array is reused and thus should not escape {@link AbstractChannel#doWrite(ChannelOutboundBuffer)}. Refer to {@link NioSocketChannel#doWrite(ChannelOutboundBuffer)} for an example. </p> @param maxCount The maximum amount of buffers that will be added to the return value. @param maxBytes A hint toward the maximum number of bytes to include as part of the return value. Note that this value maybe exceeded because we make a best effort to include at least 1 {@link ByteBuffer} in the return value to ensure write progress is made.
public void forEachFlushedMessage(MessageProcessor processor) throws Exception { if (processor == null) { throw new NullPointerException("processor"); } Entry entry = flushedEntry; if (entry == null) { return; } do { if (!entry.cancelled) { if (!processor.processMessage(entry.msg)) { return; } } entry = entry.next; } while (isFlushedEntry(entry)); }
Call {@link MessageProcessor#processMessage(Object)} for each flushed message in this {@link ChannelOutboundBuffer} until {@link MessageProcessor#processMessage(Object)} returns {@code false} or there are no more flushed messages to process.
public String applicationProtocol() { SSLEngine engine = engine(); if (!(engine instanceof ApplicationProtocolAccessor)) { return null; } return ((ApplicationProtocolAccessor) engine).getNegotiatedApplicationProtocol(); }
Returns the name of the current application-level protocol. @return the protocol name or {@code null} if application-level protocol has not been negotiated
public ChannelFuture closeOutbound(final ChannelPromise promise) { final ChannelHandlerContext ctx = this.ctx; if (ctx.executor().inEventLoop()) { closeOutbound0(promise); } else { ctx.executor().execute(new Runnable() { @Override public void run() { closeOutbound0(promise); } }); } return promise; }
Sends an SSL {@code close_notify} message to the specified channel and destroys the underlying {@link SSLEngine}. This will <strong>not</strong> close the underlying {@link Channel}. If you want to also close the {@link Channel} use {@link Channel#close()} or {@link ChannelHandlerContext#close()}
private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException { ByteBuf out = null; ChannelPromise promise = null; ByteBufAllocator alloc = ctx.alloc(); boolean needUnwrap = false; ByteBuf buf = null; try { final int wrapDataSize = this.wrapDataSize; // Only continue to loop if the handler was not removed in the meantime. // See https://github.com/netty/netty/issues/5860 outer: while (!ctx.isRemoved()) { promise = ctx.newPromise(); buf = wrapDataSize > 0 ? pendingUnencryptedWrites.remove(alloc, wrapDataSize, promise) : pendingUnencryptedWrites.removeFirst(promise); if (buf == null) { break; } if (out == null) { out = allocateOutNetBuf(ctx, buf.readableBytes(), buf.nioBufferCount()); } SSLEngineResult result = wrap(alloc, engine, buf, out); if (result.getStatus() == Status.CLOSED) { buf.release(); buf = null; promise.tryFailure(SSLENGINE_CLOSED); promise = null; // SSLEngine has been closed already. // Any further write attempts should be denied. pendingUnencryptedWrites.releaseAndFailAll(ctx, SSLENGINE_CLOSED); return; } else { if (buf.isReadable()) { pendingUnencryptedWrites.addFirst(buf, promise); // When we add the buffer/promise pair back we need to be sure we don't complete the promise // later in finishWrap. We only complete the promise if the buffer is completely consumed. promise = null; } else { buf.release(); } buf = null; switch (result.getHandshakeStatus()) { case NEED_TASK: if (!runDelegatedTasks(inUnwrap)) { // We scheduled a task on the delegatingTaskExecutor, so stop processing as we will // resume once the task completes. break outer; } break; case FINISHED: setHandshakeSuccess(); // deliberate fall-through case NOT_HANDSHAKING: setHandshakeSuccessIfStillHandshaking(); // deliberate fall-through case NEED_WRAP: finishWrap(ctx, out, promise, inUnwrap, false); promise = null; out = null; break; case NEED_UNWRAP: needUnwrap = true; return; default: throw new IllegalStateException( "Unknown handshake status: " + result.getHandshakeStatus()); } } } } finally { // Ownership of buffer was not transferred, release it. if (buf != null) { buf.release(); } finishWrap(ctx, out, promise, inUnwrap, needUnwrap); } }
This method will not call setHandshakeFailure(...) !
private boolean wrapNonAppData(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException { ByteBuf out = null; ByteBufAllocator alloc = ctx.alloc(); try { // Only continue to loop if the handler was not removed in the meantime. // See https://github.com/netty/netty/issues/5860 outer: while (!ctx.isRemoved()) { if (out == null) { // As this is called for the handshake we have no real idea how big the buffer needs to be. // That said 2048 should give us enough room to include everything like ALPN / NPN data. // If this is not enough we will increase the buffer in wrap(...). out = allocateOutNetBuf(ctx, 2048, 1); } SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out); if (result.bytesProduced() > 0) { ctx.write(out); if (inUnwrap) { needsFlush = true; } out = null; } HandshakeStatus status = result.getHandshakeStatus(); switch (status) { case FINISHED: setHandshakeSuccess(); return false; case NEED_TASK: if (!runDelegatedTasks(inUnwrap)) { // We scheduled a task on the delegatingTaskExecutor, so stop processing as we will // resume once the task completes. break outer; } break; case NEED_UNWRAP: if (inUnwrap) { // If we asked for a wrap, the engine requested an unwrap, and we are in unwrap there is // no use in trying to call wrap again because we have already attempted (or will after we // return) to feed more data to the engine. return false; } unwrapNonAppData(ctx); break; case NEED_WRAP: break; case NOT_HANDSHAKING: setHandshakeSuccessIfStillHandshaking(); // Workaround for TLS False Start problem reported at: // https://github.com/netty/netty/issues/1108#issuecomment-14266970 if (!inUnwrap) { unwrapNonAppData(ctx); } return true; default: throw new IllegalStateException("Unknown handshake status: " + result.getHandshakeStatus()); } // Check if did not produce any bytes and if so break out of the loop, but only if we did not process // a task as last action. It's fine to not produce any data as part of executing a task. if (result.bytesProduced() == 0 && status != HandshakeStatus.NEED_TASK) { break; } // It should not consume empty buffers when it is not handshaking // Fix for Android, where it was encrypting empty buffers even when not handshaking if (result.bytesConsumed() == 0 && result.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) { break; } } } finally { if (out != null) { out.release(); } } return false; }
This method will not call {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean, boolean, boolean)} or {@link #setHandshakeFailure(ChannelHandlerContext, Throwable)}. @return {@code true} if this method ends on {@link SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING}.
private boolean ignoreException(Throwable t) { if (!(t instanceof SSLException) && t instanceof IOException && sslClosePromise.isDone()) { String message = t.getMessage(); // first try to match connection reset / broke peer based on the regex. This is the fastest way // but may fail on different jdk impls or OS's if (message != null && IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) { return true; } // Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not StackTraceElement[] elements = t.getStackTrace(); for (StackTraceElement element: elements) { String classname = element.getClassName(); String methodname = element.getMethodName(); // skip all classes that belong to the io.netty package if (classname.startsWith("io.netty.")) { continue; } // check if the method name is read if not skip it if (!"read".equals(methodname)) { continue; } // This will also match against SocketInputStream which is used by openjdk 7 and maybe // also others if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) { return true; } try { // No match by now.. Try to load the class via classloader and inspect it. // This is mainly done as other JDK implementations may differ in name of // the impl. Class<?> clazz = PlatformDependent.getClassLoader(getClass()).loadClass(classname); if (SocketChannel.class.isAssignableFrom(clazz) || DatagramChannel.class.isAssignableFrom(clazz)) { return true; } // also match against SctpChannel via String matching as it may not present. if (PlatformDependent.javaVersion() >= 7 && "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) { return true; } } catch (Throwable cause) { logger.debug("Unexpected exception while loading class {} classname {}", getClass(), classname, cause); } } } return false; }
Checks if the given {@link Throwable} can be ignore and just "swallowed" When an ssl connection is closed a close_notify message is sent. After that the peer also sends close_notify however, it's not mandatory to receive the close_notify. The party who sent the initial close_notify can close the connection immediately then the peer will get connection reset error.
public static boolean isEncrypted(ByteBuf buffer) { if (buffer.readableBytes() < SslUtils.SSL_RECORD_HEADER_LENGTH) { throw new IllegalArgumentException( "buffer must have at least " + SslUtils.SSL_RECORD_HEADER_LENGTH + " readable bytes"); } return getEncryptedPacketLength(buffer, buffer.readerIndex()) != SslUtils.NOT_ENCRYPTED; }
Returns {@code true} if the given {@link ByteBuf} is encrypted. Be aware that this method will not increase the readerIndex of the given {@link ByteBuf}. @param buffer The {@link ByteBuf} to read from. Be aware that it must have at least 5 bytes to read, otherwise it will throw an {@link IllegalArgumentException}. @return encrypted {@code true} if the {@link ByteBuf} is encrypted, {@code false} otherwise. @throws IllegalArgumentException Is thrown if the given {@link ByteBuf} has not at least 5 bytes to read.
private int unwrap( ChannelHandlerContext ctx, ByteBuf packet, int offset, int length) throws SSLException { final int originalLength = length; boolean wrapLater = false; boolean notifyClosure = false; int overflowReadableBytes = -1; ByteBuf decodeOut = allocate(ctx, length); try { // Only continue to loop if the handler was not removed in the meantime. // See https://github.com/netty/netty/issues/5860 unwrapLoop: while (!ctx.isRemoved()) { final SSLEngineResult result = engineType.unwrap(this, packet, offset, length, decodeOut); final Status status = result.getStatus(); final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); final int produced = result.bytesProduced(); final int consumed = result.bytesConsumed(); // Update indexes for the next iteration offset += consumed; length -= consumed; switch (status) { case BUFFER_OVERFLOW: final int readableBytes = decodeOut.readableBytes(); final int previousOverflowReadableBytes = overflowReadableBytes; overflowReadableBytes = readableBytes; int bufferSize = engine.getSession().getApplicationBufferSize() - readableBytes; if (readableBytes > 0) { firedChannelRead = true; ctx.fireChannelRead(decodeOut); // This buffer was handled, null it out. decodeOut = null; if (bufferSize <= 0) { // It may happen that readableBytes >= engine.getSession().getApplicationBufferSize() // while there is still more to unwrap, in this case we will just allocate a new buffer // with the capacity of engine.getSession().getApplicationBufferSize() and call unwrap // again. bufferSize = engine.getSession().getApplicationBufferSize(); } } else { // This buffer was handled, null it out. decodeOut.release(); decodeOut = null; } if (readableBytes == 0 && previousOverflowReadableBytes == 0) { // If there is two consecutive loops where we overflow and are not able to consume any data, // assume the amount of data exceeds the maximum amount for the engine and bail throw new IllegalStateException("Two consecutive overflows but no content was consumed. " + SSLSession.class.getSimpleName() + " getApplicationBufferSize: " + engine.getSession().getApplicationBufferSize() + " maybe too small."); } // Allocate a new buffer which can hold all the rest data and loop again. // TODO: We may want to reconsider how we calculate the length here as we may // have more then one ssl message to decode. decodeOut = allocate(ctx, engineType.calculatePendingData(this, bufferSize)); continue; case CLOSED: // notify about the CLOSED state of the SSLEngine. See #137 notifyClosure = true; overflowReadableBytes = -1; break; default: overflowReadableBytes = -1; break; } switch (handshakeStatus) { case NEED_UNWRAP: break; case NEED_WRAP: // If the wrap operation transitions the status to NOT_HANDSHAKING and there is no more data to // unwrap then the next call to unwrap will not produce any data. We can avoid the potentially // costly unwrap operation and break out of the loop. if (wrapNonAppData(ctx, true) && length == 0) { break unwrapLoop; } break; case NEED_TASK: if (!runDelegatedTasks(true)) { // We scheduled a task on the delegatingTaskExecutor, so stop processing as we will // resume once the task completes. // // We break out of the loop only and do NOT return here as we still may need to notify // about the closure of the SSLEngine. // wrapLater = false; break unwrapLoop; } break; case FINISHED: setHandshakeSuccess(); wrapLater = true; // We 'break' here and NOT 'continue' as android API version 21 has a bug where they consume // data from the buffer but NOT correctly set the SSLEngineResult.bytesConsumed(). // Because of this it will raise an exception on the next iteration of the for loop on android // API version 21. Just doing a break will work here as produced and consumed will both be 0 // and so we break out of the complete for (;;) loop and so call decode(...) again later on. // On other platforms this will have no negative effect as we will just continue with the // for (;;) loop if something was either consumed or produced. // // See: // - https://github.com/netty/netty/issues/4116 // - https://code.google.com/p/android/issues/detail?id=198639&thanks=198639&ts=1452501203 break; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking()) { wrapLater = true; continue; } // If we are not handshaking and there is no more data to unwrap then the next call to unwrap // will not produce any data. We can avoid the potentially costly unwrap operation and break // out of the loop. if (length == 0) { break unwrapLoop; } break; default: throw new IllegalStateException("unknown handshake status: " + handshakeStatus); } if (status == Status.BUFFER_UNDERFLOW || // If we processed NEED_TASK we should try again even we did not consume or produce anything. handshakeStatus != HandshakeStatus.NEED_TASK && consumed == 0 && produced == 0) { if (handshakeStatus == HandshakeStatus.NEED_UNWRAP) { // The underlying engine is starving so we need to feed it with more data. // See https://github.com/netty/netty/pull/5039 readIfNeeded(ctx); } break; } } if (flushedBeforeHandshake && handshakePromise.isDone()) { // We need to call wrap(...) in case there was a flush done before the handshake completed to ensure // we do not stale. // // See https://github.com/netty/netty/pull/2437 flushedBeforeHandshake = false; wrapLater = true; } if (wrapLater) { wrap(ctx, true); } if (notifyClosure) { notifyClosePromise(null); } } finally { if (decodeOut != null) { if (decodeOut.isReadable()) { firedChannelRead = true; ctx.fireChannelRead(decodeOut); } else { decodeOut.release(); } } } return originalLength - length; }
Unwraps inbound SSL records.
private boolean runDelegatedTasks(boolean inUnwrap) { if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE || inEventLoop(delegatedTaskExecutor)) { // We should run the task directly in the EventExecutor thread and not offload at all. runAllDelegatedTasks(engine); return true; } else { executeDelegatedTasks(inUnwrap); return false; } }
Will either run the delegated task directly calling {@link Runnable#run()} and return {@code true} or will offload the delegated task using {@link Executor#execute(Runnable)} and return {@code false}. If the task is offloaded it will take care to resume its work on the {@link EventExecutor} once there are no more tasks to process.
private void setHandshakeSuccess() { handshakePromise.trySuccess(ctx.channel()); if (logger.isDebugEnabled()) { logger.debug("{} HANDSHAKEN: {}", ctx.channel(), engine.getSession().getCipherSuite()); } ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS); if (readDuringHandshake && !ctx.channel().config().isAutoRead()) { readDuringHandshake = false; ctx.read(); } }
Notify all the handshake futures about the successfully handshake
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) { setHandshakeFailure(ctx, cause, true, true, false); }
Notify all the handshake futures about the failure during the handshake.
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound, boolean notify, boolean alwaysFlushAndClose) { try { // Release all resources such as internal buffers that SSLEngine // is managing. outboundClosed = true; engine.closeOutbound(); if (closeInbound) { try { engine.closeInbound(); } catch (SSLException e) { if (logger.isDebugEnabled()) { // only log in debug mode as it most likely harmless and latest chrome still trigger // this all the time. // // See https://github.com/netty/netty/issues/1340 String msg = e.getMessage(); if (msg == null || !(msg.contains("possible truncation attack") || msg.contains("closing inbound before receiving peer's close_notify"))) { logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e); } } } } if (handshakePromise.tryFailure(cause) || alwaysFlushAndClose) { SslUtils.handleHandshakeFailure(ctx, cause, notify); } } finally { // Ensure we remove and fail all pending writes in all cases and so release memory quickly. releaseAndFailAll(cause); } }
Notify all the handshake futures about the failure during the handshake.
public Future<Channel> renegotiate() { ChannelHandlerContext ctx = this.ctx; if (ctx == null) { throw new IllegalStateException(); } return renegotiate(ctx.executor().<Channel>newPromise()); }
Performs TLS renegotiation.
public Future<Channel> renegotiate(final Promise<Channel> promise) { if (promise == null) { throw new NullPointerException("promise"); } ChannelHandlerContext ctx = this.ctx; if (ctx == null) { throw new IllegalStateException(); } EventExecutor executor = ctx.executor(); if (!executor.inEventLoop()) { executor.execute(new Runnable() { @Override public void run() { renegotiateOnEventLoop(promise); } }); return promise; } renegotiateOnEventLoop(promise); return promise; }
Performs TLS renegotiation.
private void handshake() { if (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) { // Not all SSLEngine implementations support calling beginHandshake multiple times while a handshake // is in progress. See https://github.com/netty/netty/issues/4718. return; } else { if (handshakePromise.isDone()) { // If the handshake is done already lets just return directly as there is no need to trigger it again. // This can happen if the handshake(...) was triggered before we called channelActive(...) by a // flush() that was triggered by a ChannelFutureListener that was added to the ChannelFuture returned // from the connect(...) method. In this case we will see the flush() happen before we had a chance to // call fireChannelActive() on the pipeline. return; } } // Begin handshake. final ChannelHandlerContext ctx = this.ctx; try { engine.beginHandshake(); wrapNonAppData(ctx, false); } catch (Throwable e) { setHandshakeFailure(ctx, e); } finally { forceFlush(ctx); } }
Performs TLS (re)negotiation.
private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) { ByteBufAllocator alloc = ctx.alloc(); if (engineType.wantsDirectBuffer) { return alloc.directBuffer(capacity); } else { return alloc.buffer(capacity); } }
Always prefer a direct buffer when it's pooled, so that we reduce the number of memory copies in {@link OpenSslEngine}.
private ByteBuf allocateOutNetBuf(ChannelHandlerContext ctx, int pendingBytes, int numComponents) { return allocate(ctx, engineType.calculateWrapBufferCapacity(this, pendingBytes, numComponents)); }
Allocates an outbound network buffer for {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} which can encrypt the specified amount of pending bytes.
@Override public List<InterfaceHttpData> getBodyHttpDatas(String name) { checkDestroyed(); if (!isLastChunk) { throw new NotEnoughDataDecoderException(); } return bodyMapHttpData.get(name); }
This getMethod returns a List of all HttpDatas with the given name from body.<br> If chunked, all chunks must have been offered using offer() getMethod. If not, NotEnoughDataDecoderException will be raised. @return All Body HttpDatas with the given name (ignore case) @throws NotEnoughDataDecoderException need more chunks
@Override public InterfaceHttpData getBodyHttpData(String name) { checkDestroyed(); if (!isLastChunk) { throw new NotEnoughDataDecoderException(); } List<InterfaceHttpData> list = bodyMapHttpData.get(name); if (list != null) { return list.get(0); } return null; }
This getMethod returns the first InterfaceHttpData with the given name from body.<br> If chunked, all chunks must have been offered using offer() getMethod. If not, NotEnoughDataDecoderException will be raised. @return The first Body InterfaceHttpData with the given name (ignore case) @throws NotEnoughDataDecoderException need more chunks
@Override public HttpPostStandardRequestDecoder offer(HttpContent content) { checkDestroyed(); // Maybe we should better not copy here for performance reasons but this will need // more care by the caller to release the content in a correct manner later // So maybe something to optimize on a later stage ByteBuf buf = content.content(); if (undecodedChunk == null) { undecodedChunk = buf.copy(); } else { undecodedChunk.writeBytes(buf); } if (content instanceof LastHttpContent) { isLastChunk = true; } parseBody(); if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) { undecodedChunk.discardReadBytes(); } return this; }
Initialized the internals from a new chunk @param content the new received chunk @throws ErrorDataDecoderException if there is a problem with the charset decoding or other errors
@Override public boolean hasNext() { checkDestroyed(); if (currentStatus == MultiPartStatus.EPILOGUE) { // OK except if end of list if (bodyListHttpDataRank >= bodyListHttpData.size()) { throw new EndOfDataDecoderException(); } } return !bodyListHttpData.isEmpty() && bodyListHttpDataRank < bodyListHttpData.size(); }
True if at current getStatus, there is an available decoded InterfaceHttpData from the Body. This getMethod works for chunked and not chunked request. @return True if at current getStatus, there is a decoded InterfaceHttpData @throws EndOfDataDecoderException No more data will be available
private void parseBody() { if (currentStatus == MultiPartStatus.PREEPILOGUE || currentStatus == MultiPartStatus.EPILOGUE) { if (isLastChunk) { currentStatus = MultiPartStatus.EPILOGUE; } return; } parseBodyAttributes(); }
This getMethod will parse as much as possible data and fill the list and map @throws ErrorDataDecoderException if there is a problem with the charset decoding or other errors
protected void addHttpData(InterfaceHttpData data) { if (data == null) { return; } List<InterfaceHttpData> datas = bodyMapHttpData.get(data.getName()); if (datas == null) { datas = new ArrayList<InterfaceHttpData>(1); bodyMapHttpData.put(data.getName(), datas); } datas.add(data); bodyListHttpData.add(data); }
Utility function to add a new decoded data
private void parseBodyAttributesStandard() { int firstpos = undecodedChunk.readerIndex(); int currentpos = firstpos; int equalpos; int ampersandpos; if (currentStatus == MultiPartStatus.NOTSTARTED) { currentStatus = MultiPartStatus.DISPOSITION; } boolean contRead = true; try { while (undecodedChunk.isReadable() && contRead) { char read = (char) undecodedChunk.readUnsignedByte(); currentpos++; switch (currentStatus) { case DISPOSITION:// search '=' if (read == '=') { currentStatus = MultiPartStatus.FIELD; equalpos = currentpos - 1; String key = decodeAttribute(undecodedChunk.toString(firstpos, equalpos - firstpos, charset), charset); currentAttribute = factory.createAttribute(request, key); firstpos = currentpos; } else if (read == '&') { // special empty FIELD currentStatus = MultiPartStatus.DISPOSITION; ampersandpos = currentpos - 1; String key = decodeAttribute( undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset); currentAttribute = factory.createAttribute(request, key); currentAttribute.setValue(""); // empty addHttpData(currentAttribute); currentAttribute = null; firstpos = currentpos; contRead = true; } break; case FIELD:// search '&' or end of line if (read == '&') { currentStatus = MultiPartStatus.DISPOSITION; ampersandpos = currentpos - 1; setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); firstpos = currentpos; contRead = true; } else if (read == HttpConstants.CR) { if (undecodedChunk.isReadable()) { read = (char) undecodedChunk.readUnsignedByte(); currentpos++; if (read == HttpConstants.LF) { currentStatus = MultiPartStatus.PREEPILOGUE; ampersandpos = currentpos - 2; setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); firstpos = currentpos; contRead = false; } else { // Error throw new ErrorDataDecoderException("Bad end of line"); } } else { currentpos--; } } else if (read == HttpConstants.LF) { currentStatus = MultiPartStatus.PREEPILOGUE; ampersandpos = currentpos - 1; setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); firstpos = currentpos; contRead = false; } break; default: // just stop contRead = false; } } if (isLastChunk && currentAttribute != null) { // special case ampersandpos = currentpos; if (ampersandpos > firstpos) { setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); } else if (!currentAttribute.isCompleted()) { setFinalBuffer(EMPTY_BUFFER); } firstpos = currentpos; currentStatus = MultiPartStatus.EPILOGUE; } else if (contRead && currentAttribute != null && currentStatus == MultiPartStatus.FIELD) { // reset index except if to continue in case of FIELD getStatus currentAttribute.addContent(undecodedChunk.copy(firstpos, currentpos - firstpos), false); firstpos = currentpos; } undecodedChunk.readerIndex(firstpos); } catch (ErrorDataDecoderException e) { // error while decoding undecodedChunk.readerIndex(firstpos); throw e; } catch (IOException e) { // error while decoding undecodedChunk.readerIndex(firstpos); throw new ErrorDataDecoderException(e); } }
This getMethod fill the map and list with as much Attribute as possible from Body in not Multipart mode. @throws ErrorDataDecoderException if there is a problem with the charset decoding or other errors
private void parseBodyAttributes() { if (!undecodedChunk.hasArray()) { parseBodyAttributesStandard(); return; } SeekAheadOptimize sao = new SeekAheadOptimize(undecodedChunk); int firstpos = undecodedChunk.readerIndex(); int currentpos = firstpos; int equalpos; int ampersandpos; if (currentStatus == MultiPartStatus.NOTSTARTED) { currentStatus = MultiPartStatus.DISPOSITION; } boolean contRead = true; try { loop: while (sao.pos < sao.limit) { char read = (char) (sao.bytes[sao.pos++] & 0xFF); currentpos++; switch (currentStatus) { case DISPOSITION:// search '=' if (read == '=') { currentStatus = MultiPartStatus.FIELD; equalpos = currentpos - 1; String key = decodeAttribute(undecodedChunk.toString(firstpos, equalpos - firstpos, charset), charset); currentAttribute = factory.createAttribute(request, key); firstpos = currentpos; } else if (read == '&') { // special empty FIELD currentStatus = MultiPartStatus.DISPOSITION; ampersandpos = currentpos - 1; String key = decodeAttribute( undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset); currentAttribute = factory.createAttribute(request, key); currentAttribute.setValue(""); // empty addHttpData(currentAttribute); currentAttribute = null; firstpos = currentpos; contRead = true; } break; case FIELD:// search '&' or end of line if (read == '&') { currentStatus = MultiPartStatus.DISPOSITION; ampersandpos = currentpos - 1; setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); firstpos = currentpos; contRead = true; } else if (read == HttpConstants.CR) { if (sao.pos < sao.limit) { read = (char) (sao.bytes[sao.pos++] & 0xFF); currentpos++; if (read == HttpConstants.LF) { currentStatus = MultiPartStatus.PREEPILOGUE; ampersandpos = currentpos - 2; sao.setReadPosition(0); setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); firstpos = currentpos; contRead = false; break loop; } else { // Error sao.setReadPosition(0); throw new ErrorDataDecoderException("Bad end of line"); } } else { if (sao.limit > 0) { currentpos--; } } } else if (read == HttpConstants.LF) { currentStatus = MultiPartStatus.PREEPILOGUE; ampersandpos = currentpos - 1; sao.setReadPosition(0); setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); firstpos = currentpos; contRead = false; break loop; } break; default: // just stop sao.setReadPosition(0); contRead = false; break loop; } } if (isLastChunk && currentAttribute != null) { // special case ampersandpos = currentpos; if (ampersandpos > firstpos) { setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos)); } else if (!currentAttribute.isCompleted()) { setFinalBuffer(EMPTY_BUFFER); } firstpos = currentpos; currentStatus = MultiPartStatus.EPILOGUE; } else if (contRead && currentAttribute != null && currentStatus == MultiPartStatus.FIELD) { // reset index except if to continue in case of FIELD getStatus currentAttribute.addContent(undecodedChunk.copy(firstpos, currentpos - firstpos), false); firstpos = currentpos; } undecodedChunk.readerIndex(firstpos); } catch (ErrorDataDecoderException e) { // error while decoding undecodedChunk.readerIndex(firstpos); throw e; } catch (IOException e) { // error while decoding undecodedChunk.readerIndex(firstpos); throw new ErrorDataDecoderException(e); } catch (IllegalArgumentException e) { // error while decoding undecodedChunk.readerIndex(firstpos); throw new ErrorDataDecoderException(e); } }
This getMethod fill the map and list with as much Attribute as possible from Body in not Multipart mode. @throws ErrorDataDecoderException if there is a problem with the charset decoding or other errors
private static String decodeAttribute(String s, Charset charset) { try { return QueryStringDecoder.decodeComponent(s, charset); } catch (IllegalArgumentException e) { throw new ErrorDataDecoderException("Bad string: '" + s + '\'', e); } }
Decode component @return the decoded component
@Override public void destroy() { // Release all data items, including those not yet pulled cleanFiles(); destroyed = true; if (undecodedChunk != null && undecodedChunk.refCnt() > 0) { undecodedChunk.release(); undecodedChunk = null; } }
Destroy the {@link HttpPostStandardRequestDecoder} and release all it resources. After this method was called it is not possible to operate on it anymore.
@Deprecated public void setTicketKeys(byte[] keys) { if (keys.length % SessionTicketKey.TICKET_KEY_SIZE != 0) { throw new IllegalArgumentException("keys.length % " + SessionTicketKey.TICKET_KEY_SIZE + " != 0"); } SessionTicketKey[] tickets = new SessionTicketKey[keys.length / SessionTicketKey.TICKET_KEY_SIZE]; for (int i = 0, a = 0; i < tickets.length; i++) { byte[] name = Arrays.copyOfRange(keys, a, SessionTicketKey.NAME_SIZE); a += SessionTicketKey.NAME_SIZE; byte[] hmacKey = Arrays.copyOfRange(keys, a, SessionTicketKey.HMAC_KEY_SIZE); i += SessionTicketKey.HMAC_KEY_SIZE; byte[] aesKey = Arrays.copyOfRange(keys, a, SessionTicketKey.AES_KEY_SIZE); a += SessionTicketKey.AES_KEY_SIZE; tickets[i] = new SessionTicketKey(name, hmacKey, aesKey); } Lock writerLock = context.ctxLock.writeLock(); writerLock.lock(); try { SSLContext.clearOptions(context.ctx, SSL.SSL_OP_NO_TICKET); SSLContext.setSessionTicketKeys(context.ctx, tickets); } finally { writerLock.unlock(); } }
Sets the SSL session ticket keys of this context. @deprecated use {@link #setTicketKeys(OpenSslSessionTicketKey...)}.
public void setTicketKeys(OpenSslSessionTicketKey... keys) { ObjectUtil.checkNotNull(keys, "keys"); SessionTicketKey[] ticketKeys = new SessionTicketKey[keys.length]; for (int i = 0; i < ticketKeys.length; i++) { ticketKeys[i] = keys[i].key; } Lock writerLock = context.ctxLock.writeLock(); writerLock.lock(); try { SSLContext.clearOptions(context.ctx, SSL.SSL_OP_NO_TICKET); SSLContext.setSessionTicketKeys(context.ctx, ticketKeys); } finally { writerLock.unlock(); } }
Sets the SSL session ticket keys of this context.
@Skip @Override public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception { ctx.bind(localAddress, promise); }
Calls {@link ChannelHandlerContext#bind(SocketAddress, ChannelPromise)} to forward to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. Sub-classes may override this method to change behavior.
@Skip @Override public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { ctx.disconnect(promise); }
Calls {@link ChannelHandlerContext#disconnect(ChannelPromise)} to forward to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. Sub-classes may override this method to change behavior.