code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public static AsciiString cached(String string) { AsciiString asciiString = new AsciiString(string); asciiString.string = string; return asciiString; }
Returns an {@link AsciiString} containing the given string and retains/caches the input string for later use in {@link #toString()}. Used for the constants (which already stored in the JVM's string table) and in cases where the guaranteed use of the {@link #toString()} method.
public static boolean contains(CharSequence a, CharSequence b) { return contains(a, b, DefaultCharEqualityComparator.INSTANCE); }
Determine if {@code a} contains {@code b} in a case sensitive manner.
public static boolean containsIgnoreCase(CharSequence a, CharSequence b) { return contains(a, b, AsciiCaseInsensitiveCharEqualityComparator.INSTANCE); }
Determine if {@code a} contains {@code b} in a case insensitive manner.
public static boolean contentEqualsIgnoreCase(CharSequence a, CharSequence b) { if (a == null || b == null) { return a == b; } if (a.getClass() == AsciiString.class) { return ((AsciiString) a).contentEqualsIgnoreCase(b); } if (b.getClass() == AsciiString.class) { return ((AsciiString) b).contentEqualsIgnoreCase(a); } if (a.length() != b.length()) { return false; } for (int i = 0; i < a.length(); ++i) { if (!equalsIgnoreCase(a.charAt(i), b.charAt(i))) { return false; } } return true; }
Returns {@code true} if both {@link CharSequence}'s are equals when ignore the case. This only supports 8-bit ASCII.
public static boolean containsContentEqualsIgnoreCase(Collection<CharSequence> collection, CharSequence value) { for (CharSequence v : collection) { if (contentEqualsIgnoreCase(value, v)) { return true; } } return false; }
Determine if {@code collection} contains {@code value} and using {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)} to compare values. @param collection The collection to look for and equivalent element as {@code value}. @param value The value to look for in {@code collection}. @return {@code true} if {@code collection} contains {@code value} according to {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)}. {@code false} otherwise. @see #contentEqualsIgnoreCase(CharSequence, CharSequence)
public static boolean containsAllContentEqualsIgnoreCase(Collection<CharSequence> a, Collection<CharSequence> b) { for (CharSequence v : b) { if (!containsContentEqualsIgnoreCase(a, v)) { return false; } } return true; }
Determine if {@code a} contains all of the values in {@code b} using {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)} to compare values. @param a The collection under test. @param b The values to test for. @return {@code true} if {@code a} contains all of the values in {@code b} using {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)} to compare values. {@code false} otherwise. @see #contentEqualsIgnoreCase(CharSequence, CharSequence)
public static boolean contentEquals(CharSequence a, CharSequence b) { if (a == null || b == null) { return a == b; } if (a.getClass() == AsciiString.class) { return ((AsciiString) a).contentEquals(b); } if (b.getClass() == AsciiString.class) { return ((AsciiString) b).contentEquals(a); } if (a.length() != b.length()) { return false; } for (int i = 0; i < a.length(); ++i) { if (a.charAt(i) != b.charAt(i)) { return false; } } return true; }
Returns {@code true} if the content of both {@link CharSequence}'s are equals. This only supports 8-bit ASCII.
public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int csStart, final CharSequence string, final int start, final int length) { if (cs == null || string == null) { return false; } if (cs instanceof String && string instanceof String) { return ((String) cs).regionMatches(ignoreCase, csStart, (String) string, start, length); } if (cs instanceof AsciiString) { return ((AsciiString) cs).regionMatches(ignoreCase, csStart, string, start, length); } return regionMatchesCharSequences(cs, csStart, string, start, length, ignoreCase ? GeneralCaseInsensitiveCharEqualityComparator.INSTANCE : DefaultCharEqualityComparator.INSTANCE); }
This methods make regionMatches operation correctly for any chars in strings @param cs the {@code CharSequence} to be processed @param ignoreCase specifies if case should be ignored. @param csStart the starting offset in the {@code cs} CharSequence @param string the {@code CharSequence} to compare. @param start the starting offset in the specified {@code string}. @param length the number of characters to compare. @return {@code true} if the ranges of characters are equal, {@code false} otherwise.
public static int indexOfIgnoreCaseAscii(final CharSequence str, final CharSequence searchStr, int startPos) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } if (startPos < 0) { startPos = 0; } int searchStrLen = searchStr.length(); final int endLimit = str.length() - searchStrLen + 1; if (startPos > endLimit) { return INDEX_NOT_FOUND; } if (searchStrLen == 0) { return startPos; } for (int i = startPos; i < endLimit; i++) { if (regionMatchesAscii(str, true, i, searchStr, 0, searchStrLen)) { return i; } } return INDEX_NOT_FOUND; }
<p>Case in-sensitive find of the first index within a CharSequence from the specified position. This method optimized and works correctly for ASCII CharSequences only</p> <p>A {@code null} CharSequence will return {@code -1}. A negative start position is treated as zero. An empty ("") search CharSequence always matches. A start position greater than the string length only matches an empty search CharSequence.</p> <pre> AsciiString.indexOfIgnoreCase(null, *, *) = -1 AsciiString.indexOfIgnoreCase(*, null, *) = -1 AsciiString.indexOfIgnoreCase("", "", 0) = 0 AsciiString.indexOfIgnoreCase("aabaabaa", "A", 0) = 0 AsciiString.indexOfIgnoreCase("aabaabaa", "B", 0) = 2 AsciiString.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1 AsciiString.indexOfIgnoreCase("aabaabaa", "B", 3) = 5 AsciiString.indexOfIgnoreCase("aabaabaa", "B", 9) = -1 AsciiString.indexOfIgnoreCase("aabaabaa", "B", -1) = 2 AsciiString.indexOfIgnoreCase("aabaabaa", "", 2) = 2 AsciiString.indexOfIgnoreCase("abc", "", 9) = -1 </pre> @param str the CharSequence to check, may be null @param searchStr the CharSequence to find, may be null @param startPos the start position, negative treated as zero @return the first index of the search CharSequence (always &ge; startPos), -1 if no match or {@code null} string input
public static int indexOf(final CharSequence cs, final char searchChar, int start) { if (cs instanceof String) { return ((String) cs).indexOf(searchChar, start); } else if (cs instanceof AsciiString) { return ((AsciiString) cs).indexOf(searchChar, start); } if (cs == null) { return INDEX_NOT_FOUND; } final int sz = cs.length(); for (int i = start < 0 ? 0 : start; i < sz; i++) { if (cs.charAt(i) == searchChar) { return i; } } return INDEX_NOT_FOUND; }
-----------------------------------------------------------------------
@SuppressWarnings("unchecked") public static <T> T retain(T msg) { if (msg instanceof ReferenceCounted) { return (T) ((ReferenceCounted) msg).retain(); } return msg; }
Try to call {@link ReferenceCounted#retain()} if the specified message implements {@link ReferenceCounted}. If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing.
@SuppressWarnings("unchecked") public static <T> T touch(T msg) { if (msg instanceof ReferenceCounted) { return (T) ((ReferenceCounted) msg).touch(); } return msg; }
Tries to call {@link ReferenceCounted#touch()} if the specified message implements {@link ReferenceCounted}. If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing.
@SuppressWarnings("unchecked") public static <T> T touch(T msg, Object hint) { if (msg instanceof ReferenceCounted) { return (T) ((ReferenceCounted) msg).touch(hint); } return msg; }
Tries to call {@link ReferenceCounted#touch(Object)} if the specified message implements {@link ReferenceCounted}. If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing.
public static boolean release(Object msg, int decrement) { if (msg instanceof ReferenceCounted) { return ((ReferenceCounted) msg).release(decrement); } return false; }
Try to call {@link ReferenceCounted#release(int)} if the specified message implements {@link ReferenceCounted}. If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing.
public static void safeRelease(Object msg) { try { release(msg); } catch (Throwable t) { logger.warn("Failed to release a message: {}", msg, t); } }
Try to call {@link ReferenceCounted#release()} if the specified message implements {@link ReferenceCounted}. If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. Unlike {@link #release(Object)} this method catches an exception raised by {@link ReferenceCounted#release()} and logs it, rather than rethrowing it to the caller. It is usually recommended to use {@link #release(Object)} instead, unless you absolutely need to swallow an exception.
public static void safeRelease(Object msg, int decrement) { try { release(msg, decrement); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to release a message: {} (decrement: {})", msg, decrement, t); } } }
Try to call {@link ReferenceCounted#release(int)} if the specified message implements {@link ReferenceCounted}. If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. Unlike {@link #release(Object)} this method catches an exception raised by {@link ReferenceCounted#release(int)} and logs it, rather than rethrowing it to the caller. It is usually recommended to use {@link #release(Object, int)} instead, unless you absolutely need to swallow an exception.
@Deprecated public static <T> T releaseLater(T msg, int decrement) { if (msg instanceof ReferenceCounted) { ThreadDeathWatcher.watch(Thread.currentThread(), new ReleasingTask((ReferenceCounted) msg, decrement)); } return msg; }
Schedules the specified object to be released when the caller thread terminates. Note that this operation is intended to simplify reference counting of ephemeral objects during unit tests. Do not use it beyond the intended use case. @deprecated this may introduce a lot of memory usage so it is generally preferable to manually release objects.
static DnsServerAddressStreamProvider parseSilently() { try { UnixResolverDnsServerAddressStreamProvider nameServerCache = new UnixResolverDnsServerAddressStreamProvider(ETC_RESOLV_CONF_FILE, ETC_RESOLVER_DIR); return nameServerCache.mayOverrideNameServers() ? nameServerCache : DefaultDnsServerAddressStreamProvider.INSTANCE; } catch (Exception e) { logger.debug("failed to parse {} and/or {}", ETC_RESOLV_CONF_FILE, ETC_RESOLVER_DIR, e); return DefaultDnsServerAddressStreamProvider.INSTANCE; } }
Attempt to parse {@code /etc/resolv.conf} and files in the {@code /etc/resolver} directory by default. A failure to parse will return {@link DefaultDnsServerAddressStreamProvider}.
static int parseEtcResolverFirstNdots(File etcResolvConf) throws IOException { FileReader fr = new FileReader(etcResolvConf); BufferedReader br = null; try { br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { if (line.startsWith(OPTIONS_ROW_LABEL)) { int i = line.indexOf(NDOTS_LABEL); if (i >= 0) { i += NDOTS_LABEL.length(); final int j = line.indexOf(' ', i); return Integer.parseInt(line.substring(i, j < 0 ? line.length() : j)); } break; } } } finally { if (br == null) { fr.close(); } else { br.close(); } } return DEFAULT_NDOTS; }
Parse a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a> and return the value corresponding to the first ndots in an options configuration. @param etcResolvConf a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a>. @return the value corresponding to the first ndots in an options configuration, or {@link #DEFAULT_NDOTS} if not found. @throws IOException If a failure occurs parsing the file.
static List<String> parseEtcResolverSearchDomains(File etcResolvConf) throws IOException { String localDomain = null; List<String> searchDomains = new ArrayList<String>(); FileReader fr = new FileReader(etcResolvConf); BufferedReader br = null; try { br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { if (localDomain == null && line.startsWith(DOMAIN_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, DOMAIN_ROW_LABEL.length()); if (i >= 0) { localDomain = line.substring(i); } } else if (line.startsWith(SEARCH_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, SEARCH_ROW_LABEL.length()); if (i >= 0) { // May contain more then one entry, either seperated by whitespace or tab. // See https://linux.die.net/man/5/resolver String[] domains = SEARCH_DOMAIN_PATTERN.split(line.substring(i)); Collections.addAll(searchDomains, domains); } } } } finally { if (br == null) { fr.close(); } else { br.close(); } } // return what was on the 'domain' line only if there were no 'search' lines return localDomain != null && searchDomains.isEmpty() ? Collections.singletonList(localDomain) : searchDomains; }
Parse a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a> and return the list of search domains found in it or an empty list if not found. @param etcResolvConf a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a>. @return List of search domains. @throws IOException If a failure occurs parsing the file.
static List<HpackHeader> createHeaders(int numHeaders, int nameLength, int valueLength, boolean limitToAscii) { List<HpackHeader> hpackHeaders = new ArrayList<HpackHeader>(numHeaders); for (int i = 0; i < numHeaders; ++i) { byte[] name = randomBytes(new byte[nameLength], limitToAscii); byte[] value = randomBytes(new byte[valueLength], limitToAscii); hpackHeaders.add(new HpackHeader(name, value)); } return hpackHeaders; }
Creates a number of random headers with the given name/value lengths.
public void windowUpdateRatio(float ratio) { assert ctx == null || ctx.executor().inEventLoop(); checkValidRatio(ratio); windowUpdateRatio = ratio; }
The window update ratio is used to determine when a window update must be sent. If the ratio of bytes processed since the last update has meet or exceeded this ratio then a window update will be sent. This is the global window update ratio that will be used for new streams. @param ratio the ratio to use when checking if a {@code WINDOW_UPDATE} is determined necessary for new streams. @throws IllegalArgumentException If the ratio is out of bounds (0, 1).
public void windowUpdateRatio(Http2Stream stream, float ratio) throws Http2Exception { assert ctx != null && ctx.executor().inEventLoop(); checkValidRatio(ratio); FlowState state = state(stream); state.windowUpdateRatio(ratio); state.writeWindowUpdateIfNeeded(); }
The window update ratio is used to determine when a window update must be sent. If the ratio of bytes processed since the last update has meet or exceeded this ratio then a window update will be sent. This window update ratio will only be applied to {@code streamId}. <p> Note it is the responsibly of the caller to ensure that the the initial {@code SETTINGS} frame is sent before this is called. It would be considered a {@link Http2Error#PROTOCOL_ERROR} if a {@code WINDOW_UPDATE} was generated by this method before the initial {@code SETTINGS} frame is sent. @param stream the stream for which {@code ratio} applies to. @param ratio the ratio to use when checking if a {@code WINDOW_UPDATE} is determined necessary. @throws Http2Exception If a protocol-error occurs while generating {@code WINDOW_UPDATE} frames
public void configure(long newWriteLimit, long newReadLimit) { writeLimit = newWriteLimit; readLimit = newReadLimit; if (trafficCounter != null) { trafficCounter.resetAccounting(TrafficCounter.milliSecondFromNano()); } }
Change the underlying limitations. <p>Note the change will be taken as best effort, meaning that all already scheduled traffics will not be changed, but only applied to new traffics.</p> <p>So the expected usage of this method is to be used not too often, accordingly to the traffic shaping configuration.</p> @param newWriteLimit The new write limit (in bytes) @param newReadLimit The new read limit (in bytes)
public void setWriteLimit(long writeLimit) { this.writeLimit = writeLimit; if (trafficCounter != null) { trafficCounter.resetAccounting(TrafficCounter.milliSecondFromNano()); } }
<p>Note the change will be taken as best effort, meaning that all already scheduled traffics will not be changed, but only applied to new traffics.</p> <p>So the expected usage of this method is to be used not too often, accordingly to the traffic shaping configuration.</p> @param writeLimit the writeLimit to set
public void setReadLimit(long readLimit) { this.readLimit = readLimit; if (trafficCounter != null) { trafficCounter.resetAccounting(TrafficCounter.milliSecondFromNano()); } }
<p>Note the change will be taken as best effort, meaning that all already scheduled traffics will not be changed, but only applied to new traffics.</p> <p>So the expected usage of this method is to be used not too often, accordingly to the traffic shaping configuration.</p> @param readLimit the readLimit to set
void releaseReadSuspended(ChannelHandlerContext ctx) { Channel channel = ctx.channel(); channel.attr(READ_SUSPENDED).set(false); channel.config().setAutoRead(true); }
Release the Read suspension
void checkWriteSuspend(ChannelHandlerContext ctx, long delay, long queueSize) { if (queueSize > maxWriteSize || delay > maxWriteDelay) { setUserDefinedWritability(ctx, false); } }
Check the writability according to delay and size for the channel. Set if necessary setUserDefinedWritability status. @param delay the computed delay @param queueSize the current queueSize
protected long calculateSize(Object msg) { if (msg instanceof ByteBuf) { return ((ByteBuf) msg).readableBytes(); } if (msg instanceof ByteBufHolder) { return ((ByteBufHolder) msg).content().readableBytes(); } return -1; }
Calculate the size of the given {@link Object}. This implementation supports {@link ByteBuf} and {@link ByteBufHolder}. Sub-classes may override this. @param msg the msg for which the size should be calculated. @return size the size of the msg or {@code -1} if unknown.
public DomainMappingBuilder<V> add(String hostname, V output) { builder.add(hostname, output); return this; }
Adds a mapping that maps the specified (optionally wildcard) host name to the specified output value. Null values are forbidden for both hostnames and values. <p> <a href="http://en.wikipedia.org/wiki/Wildcard_DNS_record">DNS wildcard</a> is supported as hostname. For example, you can use {@code *.netty.io} to match {@code netty.io} and {@code downloads.netty.io}. </p> @param hostname the host name (optionally wildcard) @param output the output value that will be returned by {@link DomainNameMapping#map(String)} when the specified host name matches the specified input host name
@Deprecated public static String encode(String name, String value) { return io.netty.handler.codec.http.cookie.ClientCookieEncoder.LAX.encode(name, value); }
Encodes the specified cookie into a Cookie header value. @param name the cookie name @param value the cookie value @return a Rfc6265 style Cookie header value
static String toJavaName(String opensslName) { if (opensslName == null) { return null; } Matcher matcher = PATTERN.matcher(opensslName); if (matcher.matches()) { String group1 = matcher.group(1); if (group1 != null) { return group1.toUpperCase(Locale.ROOT) + "with" + matcher.group(2).toUpperCase(Locale.ROOT); } if (matcher.group(3) != null) { return matcher.group(4).toUpperCase(Locale.ROOT) + "with" + matcher.group(3).toUpperCase(Locale.ROOT); } if (matcher.group(5) != null) { return matcher.group(6).toUpperCase(Locale.ROOT) + "with" + matcher.group(5).toUpperCase(Locale.ROOT); } } return null; }
Converts an OpenSSL algorithm name to a Java algorithm name and return it, or return {@code null} if the conversation failed because the format is not known.
@Override public void trace(String format, Object arg) { if (logger.isTraceEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); logger.trace(ft.getMessage(), ft.getThrowable()); } }
Delegates to the {@link Log#trace(Object)} method of the underlying {@link Log} instance. <p> However, this form avoids superfluous object creation when the logger is disabled for level TRACE. </p> @param format the format string @param arg the argument
@Override public void debug(String format, Object arg) { if (logger.isDebugEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); logger.debug(ft.getMessage(), ft.getThrowable()); } }
Delegates to the {@link Log#debug(Object)} method of the underlying {@link Log} instance. <p> However, this form avoids superfluous object creation when the logger is disabled for level DEBUG. </p> @param format the format string @param arg the argument
@Override public void info(String format, Object arg) { if (logger.isInfoEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); logger.info(ft.getMessage(), ft.getThrowable()); } }
Delegates to the {@link Log#info(Object)} method of the underlying {@link Log} instance. <p> However, this form avoids superfluous object creation when the logger is disabled for level INFO. </p> @param format the format string @param arg the argument
@Override public void warn(String format, Object arg) { if (logger.isWarnEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); logger.warn(ft.getMessage(), ft.getThrowable()); } }
Delegates to the {@link Log#warn(Object)} method of the underlying {@link Log} instance. <p> However, this form avoids superfluous object creation when the logger is disabled for level WARN. </p> @param format the format string @param arg the argument
@Override public void error(String format, Object... arguments) { if (logger.isErrorEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); logger.error(ft.getMessage(), ft.getThrowable()); } }
Delegates to the {@link Log#error(Object)} method of the underlying {@link Log} instance. <p> However, this form avoids superfluous object creation when the logger is disabled for level ERROR. </p> @param format the format string @param arguments a list of 3 or more arguments
static HAProxyMessage decodeHeader(ByteBuf header) { if (header == null) { throw new NullPointerException("header"); } if (header.readableBytes() < 16) { throw new HAProxyProtocolException( "incomplete header: " + header.readableBytes() + " bytes (expected: 16+ bytes)"); } // Per spec, the 13th byte is the protocol version and command byte header.skipBytes(12); final byte verCmdByte = header.readByte(); HAProxyProtocolVersion ver; try { ver = HAProxyProtocolVersion.valueOf(verCmdByte); } catch (IllegalArgumentException e) { throw new HAProxyProtocolException(e); } if (ver != HAProxyProtocolVersion.V2) { throw new HAProxyProtocolException("version 1 unsupported: 0x" + Integer.toHexString(verCmdByte)); } HAProxyCommand cmd; try { cmd = HAProxyCommand.valueOf(verCmdByte); } catch (IllegalArgumentException e) { throw new HAProxyProtocolException(e); } if (cmd == HAProxyCommand.LOCAL) { return V2_LOCAL_MSG; } // Per spec, the 14th byte is the protocol and address family byte HAProxyProxiedProtocol protAndFam; try { protAndFam = HAProxyProxiedProtocol.valueOf(header.readByte()); } catch (IllegalArgumentException e) { throw new HAProxyProtocolException(e); } if (protAndFam == HAProxyProxiedProtocol.UNKNOWN) { return V2_UNKNOWN_MSG; } int addressInfoLen = header.readUnsignedShort(); String srcAddress; String dstAddress; int addressLen; int srcPort = 0; int dstPort = 0; AddressFamily addressFamily = protAndFam.addressFamily(); if (addressFamily == AddressFamily.AF_UNIX) { // unix sockets require 216 bytes for address information if (addressInfoLen < 216 || header.readableBytes() < 216) { throw new HAProxyProtocolException( "incomplete UNIX socket address information: " + Math.min(addressInfoLen, header.readableBytes()) + " bytes (expected: 216+ bytes)"); } int startIdx = header.readerIndex(); int addressEnd = header.forEachByte(startIdx, 108, ByteProcessor.FIND_NUL); if (addressEnd == -1) { addressLen = 108; } else { addressLen = addressEnd - startIdx; } srcAddress = header.toString(startIdx, addressLen, CharsetUtil.US_ASCII); startIdx += 108; addressEnd = header.forEachByte(startIdx, 108, ByteProcessor.FIND_NUL); if (addressEnd == -1) { addressLen = 108; } else { addressLen = addressEnd - startIdx; } dstAddress = header.toString(startIdx, addressLen, CharsetUtil.US_ASCII); // AF_UNIX defines that exactly 108 bytes are reserved for the address. The previous methods // did not increase the reader index although we already consumed the information. header.readerIndex(startIdx + 108); } else { if (addressFamily == AddressFamily.AF_IPv4) { // IPv4 requires 12 bytes for address information if (addressInfoLen < 12 || header.readableBytes() < 12) { throw new HAProxyProtocolException( "incomplete IPv4 address information: " + Math.min(addressInfoLen, header.readableBytes()) + " bytes (expected: 12+ bytes)"); } addressLen = 4; } else if (addressFamily == AddressFamily.AF_IPv6) { // IPv6 requires 36 bytes for address information if (addressInfoLen < 36 || header.readableBytes() < 36) { throw new HAProxyProtocolException( "incomplete IPv6 address information: " + Math.min(addressInfoLen, header.readableBytes()) + " bytes (expected: 36+ bytes)"); } addressLen = 16; } else { throw new HAProxyProtocolException( "unable to parse address information (unknown address family: " + addressFamily + ')'); } // Per spec, the src address begins at the 17th byte srcAddress = ipBytesToString(header, addressLen); dstAddress = ipBytesToString(header, addressLen); srcPort = header.readUnsignedShort(); dstPort = header.readUnsignedShort(); } final List<HAProxyTLV> tlvs = readTlvs(header); return new HAProxyMessage(ver, cmd, protAndFam, srcAddress, dstAddress, srcPort, dstPort, tlvs); }
Decodes a version 2, binary proxy protocol header. @param header a version 2 proxy protocol header @return {@link HAProxyMessage} instance @throws HAProxyProtocolException if any portion of the header is invalid
static HAProxyMessage decodeHeader(String header) { if (header == null) { throw new HAProxyProtocolException("header"); } String[] parts = header.split(" "); int numParts = parts.length; if (numParts < 2) { throw new HAProxyProtocolException( "invalid header: " + header + " (expected: 'PROXY' and proxied protocol values)"); } if (!"PROXY".equals(parts[0])) { throw new HAProxyProtocolException("unknown identifier: " + parts[0]); } HAProxyProxiedProtocol protAndFam; try { protAndFam = HAProxyProxiedProtocol.valueOf(parts[1]); } catch (IllegalArgumentException e) { throw new HAProxyProtocolException(e); } if (protAndFam != HAProxyProxiedProtocol.TCP4 && protAndFam != HAProxyProxiedProtocol.TCP6 && protAndFam != HAProxyProxiedProtocol.UNKNOWN) { throw new HAProxyProtocolException("unsupported v1 proxied protocol: " + parts[1]); } if (protAndFam == HAProxyProxiedProtocol.UNKNOWN) { return V1_UNKNOWN_MSG; } if (numParts != 6) { throw new HAProxyProtocolException("invalid TCP4/6 header: " + header + " (expected: 6 parts)"); } return new HAProxyMessage( HAProxyProtocolVersion.V1, HAProxyCommand.PROXY, protAndFam, parts[2], parts[3], parts[4], parts[5]); }
Decodes a version 1, human-readable proxy protocol header. @param header a version 1 proxy protocol header @return {@link HAProxyMessage} instance @throws HAProxyProtocolException if any portion of the header is invalid
private static String ipBytesToString(ByteBuf header, int addressLen) { StringBuilder sb = new StringBuilder(); if (addressLen == 4) { sb.append(header.readByte() & 0xff); sb.append('.'); sb.append(header.readByte() & 0xff); sb.append('.'); sb.append(header.readByte() & 0xff); sb.append('.'); sb.append(header.readByte() & 0xff); } else { sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); sb.append(Integer.toHexString(header.readUnsignedShort())); } return sb.toString(); }
Convert ip address bytes to string representation @param header buffer containing ip address bytes @param addressLen number of bytes to read (4 bytes for IPv4, 16 bytes for IPv6) @return string representation of the ip address
private static int portStringToInt(String value) { int port; try { port = Integer.parseInt(value); } catch (NumberFormatException e) { throw new HAProxyProtocolException("invalid port: " + value, e); } if (port <= 0 || port > 65535) { throw new HAProxyProtocolException("invalid port: " + value + " (expected: 1 ~ 65535)"); } return port; }
Convert port to integer @param value the port @return port as an integer @throws HAProxyProtocolException if port is not a valid integer
private static void checkAddress(String address, AddressFamily addrFamily) { if (addrFamily == null) { throw new NullPointerException("addrFamily"); } switch (addrFamily) { case AF_UNSPEC: if (address != null) { throw new HAProxyProtocolException("unable to validate an AF_UNSPEC address: " + address); } return; case AF_UNIX: return; } if (address == null) { throw new NullPointerException("address"); } switch (addrFamily) { case AF_IPv4: if (!NetUtil.isValidIpV4Address(address)) { throw new HAProxyProtocolException("invalid IPv4 address: " + address); } break; case AF_IPv6: if (!NetUtil.isValidIpV6Address(address)) { throw new HAProxyProtocolException("invalid IPv6 address: " + address); } break; default: throw new Error(); } }
Validate an address (IPv4, IPv6, Unix Socket) @param address human-readable address @param addrFamily the {@link AddressFamily} to check the address against @throws HAProxyProtocolException if the address is invalid
protected static void safeExecute(Runnable task) { try { task.run(); } catch (Throwable t) { logger.warn("A task raised an exception. Task: {}", task, t); } }
Try to execute the given {@link Runnable} and just log if it throws a {@link Throwable}.
public static HttpResponseStatus parseStatus(CharSequence status) throws Http2Exception { HttpResponseStatus result; try { result = parseLine(status); if (result == HttpResponseStatus.SWITCHING_PROTOCOLS) { throw connectionError(PROTOCOL_ERROR, "Invalid HTTP/2 status code '%d'", result.code()); } } catch (Http2Exception e) { throw e; } catch (Throwable t) { throw connectionError(PROTOCOL_ERROR, t, "Unrecognized HTTP status code '%s' encountered in translation to HTTP/1.x", status); } return result; }
Apply HTTP/2 rules while translating status code to {@link HttpResponseStatus} @param status The status from an HTTP/2 frame @return The HTTP/1.x status @throws Http2Exception If there is a problem translating from HTTP/2 to HTTP/1.x
public static FullHttpResponse toFullHttpResponse(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc, boolean validateHttpHeaders) throws Http2Exception { HttpResponseStatus status = parseStatus(http2Headers.status()); // HTTP/2 does not define a way to carry the version or reason phrase that is included in an // HTTP/1.1 status line. FullHttpResponse msg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, alloc.buffer(), validateHttpHeaders); try { addHttp2ToHttpHeaders(streamId, http2Headers, msg, false); } catch (Http2Exception e) { msg.release(); throw e; } catch (Throwable t) { msg.release(); throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } return msg; }
Create a new object to contain the response data @param streamId The stream associated with the response @param http2Headers The initial set of HTTP/2 headers to create the response with @param alloc The {@link ByteBufAllocator} to use to generate the content of the message @param validateHttpHeaders <ul> <li>{@code true} to validate HTTP headers in the http-codec</li> <li>{@code false} not to validate HTTP headers in the http-codec</li> </ul> @return A new response object which represents headers/data @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
public static FullHttpRequest toFullHttpRequest(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc, boolean validateHttpHeaders) throws Http2Exception { // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line. final CharSequence method = checkNotNull(http2Headers.method(), "method header cannot be null in conversion to HTTP/1.x"); final CharSequence path = checkNotNull(http2Headers.path(), "path header cannot be null in conversion to HTTP/1.x"); FullHttpRequest msg = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method .toString()), path.toString(), alloc.buffer(), validateHttpHeaders); try { addHttp2ToHttpHeaders(streamId, http2Headers, msg, false); } catch (Http2Exception e) { msg.release(); throw e; } catch (Throwable t) { msg.release(); throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } return msg; }
Create a new object to contain the request data @param streamId The stream associated with the request @param http2Headers The initial set of HTTP/2 headers to create the request with @param alloc The {@link ByteBufAllocator} to use to generate the content of the message @param validateHttpHeaders <ul> <li>{@code true} to validate HTTP headers in the http-codec</li> <li>{@code false} not to validate HTTP headers in the http-codec</li> </ul> @return A new request object which represents headers/data @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
public static HttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders) throws Http2Exception { // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line. final CharSequence method = checkNotNull(http2Headers.method(), "method header cannot be null in conversion to HTTP/1.x"); final CharSequence path = checkNotNull(http2Headers.path(), "path header cannot be null in conversion to HTTP/1.x"); HttpRequest msg = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method.toString()), path.toString(), validateHttpHeaders); try { addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true); } catch (Http2Exception e) { throw e; } catch (Throwable t) { throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } return msg; }
Create a new object to contain the request data. @param streamId The stream associated with the request @param http2Headers The initial set of HTTP/2 headers to create the request with @param validateHttpHeaders <ul> <li>{@code true} to validate HTTP headers in the http-codec</li> <li>{@code false} not to validate HTTP headers in the http-codec</li> </ul> @return A new request object which represents headers for a chunked request @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
public static HttpResponse toHttpResponse(final int streamId, final Http2Headers http2Headers, final boolean validateHttpHeaders) throws Http2Exception { final HttpResponseStatus status = parseStatus(http2Headers.status()); // HTTP/2 does not define a way to carry the version or reason phrase that is included in an // HTTP/1.1 status line. final HttpResponse msg = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, validateHttpHeaders); try { addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true); } catch (final Http2Exception e) { throw e; } catch (final Throwable t) { throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } return msg; }
Create a new object to contain the response data. @param streamId The stream associated with the response @param http2Headers The initial set of HTTP/2 headers to create the response with @param validateHttpHeaders <ul> <li>{@code true} to validate HTTP headers in the http-codec</li> <li>{@code false} not to validate HTTP headers in the http-codec</li> </ul> @return A new response object which represents headers for a chunked response @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, HttpHeaders, HttpVersion, boolean, boolean)}
public static void addHttp2ToHttpHeaders(int streamId, Http2Headers sourceHeaders, FullHttpMessage destinationMessage, boolean addToTrailer) throws Http2Exception { addHttp2ToHttpHeaders(streamId, sourceHeaders, addToTrailer ? destinationMessage.trailingHeaders() : destinationMessage.headers(), destinationMessage.protocolVersion(), addToTrailer, destinationMessage instanceof HttpRequest); }
Translate and add HTTP/2 headers to HTTP/1.x headers. @param streamId The stream associated with {@code sourceHeaders}. @param sourceHeaders The HTTP/2 headers to convert. @param destinationMessage The object which will contain the resulting HTTP/1.x headers. @param addToTrailer {@code true} to add to trailing headers. {@code false} to add to initial headers. @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x. @see #addHttp2ToHttpHeaders(int, Http2Headers, HttpHeaders, HttpVersion, boolean, boolean)
public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders, HttpHeaders outputHeaders, HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception { Http2ToHttpHeaderTranslator translator = new Http2ToHttpHeaderTranslator(streamId, outputHeaders, isRequest); try { for (Entry<CharSequence, CharSequence> entry : inputHeaders) { translator.translate(entry); } } catch (Http2Exception ex) { throw ex; } catch (Throwable t) { throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } outputHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING); outputHeaders.remove(HttpHeaderNames.TRAILER); if (!isTrailer) { outputHeaders.setInt(ExtensionHeaderNames.STREAM_ID.text(), streamId); HttpUtil.setKeepAlive(outputHeaders, httpVersion, true); } }
Translate and add HTTP/2 headers to HTTP/1.x headers. @param streamId The stream associated with {@code sourceHeaders}. @param inputHeaders The HTTP/2 headers to convert. @param outputHeaders The object which will contain the resulting HTTP/1.x headers.. @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as when doing the conversion. @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailing headers. {@code false} otherwise. @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message. {@code false} for response message. @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) { HttpHeaders inHeaders = in.headers(); final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size()); if (in instanceof HttpRequest) { HttpRequest request = (HttpRequest) in; URI requestTargetUri = URI.create(request.uri()); out.path(toHttp2Path(requestTargetUri)); out.method(request.method().asciiName()); setHttp2Scheme(inHeaders, requestTargetUri, out); if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) { // Attempt to take from HOST header before taking from the request-line String host = inHeaders.getAsString(HttpHeaderNames.HOST); setHttp2Authority((host == null || host.isEmpty()) ? requestTargetUri.getAuthority() : host, out); } } else if (in instanceof HttpResponse) { HttpResponse response = (HttpResponse) in; out.status(response.status().codeAsText()); } // Add the HTTP headers which have not been consumed above toHttp2Headers(inHeaders, out); return out; }
Converts the given HTTP/1.x headers into HTTP/2 headers. The following headers are only used if they can not be found in from the {@code HOST} header or the {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a> <ul> <li>{@link ExtensionHeaderNames#SCHEME}</li> </ul> {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry, Http2Headers out) { if (indexOf(entry.getValue(), ',', 0) == -1) { if (contentEqualsIgnoreCase(trim(entry.getValue()), TRAILERS)) { out.add(TE, TRAILERS); } } else { List<CharSequence> teValues = unescapeCsvFields(entry.getValue()); for (CharSequence teValue : teValues) { if (contentEqualsIgnoreCase(trim(teValue), TRAILERS)) { out.add(TE, TRAILERS); break; } } } }
Filter the {@link HttpHeaderNames#TE} header according to the <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>. @param entry An entry whose name is {@link HttpHeaderNames#TE}. @param out the resulting HTTP/2 headers.
static void setHttp2Authority(String authority, Http2Headers out) { // The authority MUST NOT include the deprecated "userinfo" subcomponent if (authority != null) { if (authority.isEmpty()) { out.authority(EMPTY_STRING); } else { int start = authority.indexOf('@') + 1; int length = authority.length() - start; if (length == 0) { throw new IllegalArgumentException("authority: " + authority); } out.authority(new AsciiString(authority, start, length)); } } }
package-private for testing only
static int majorVersion(final String javaSpecVersion) { final String[] components = javaSpecVersion.split("\\."); final int[] version = new int[components.length]; for (int i = 0; i < components.length; i++) { version[i] = Integer.parseInt(components[i]); } if (version[0] == 1) { assert version[1] >= 6; return version[1]; } else { return version[0]; } }
Package-private for testing only
public static boolean isOutOfBounds(int index, int length, int capacity) { return (index | length | (index + length) | (capacity - (index + length))) < 0; }
Determine if the requested {@code index} and {@code length} will fit within {@code capacity}. @param index The starting index. @param length The length which will be utilized (starting from {@code index}). @param capacity The capacity that {@code index + length} is allowed to be within. @return {@code true} if the requested {@code index} and {@code length} will fit within {@code capacity}. {@code false} if this would result in an index out of bounds exception.
@Override protected FullHttpRequest newHandshakeRequest() { // Make keys int spaces1 = WebSocketUtil.randomNumber(1, 12); int spaces2 = WebSocketUtil.randomNumber(1, 12); int max1 = Integer.MAX_VALUE / spaces1; int max2 = Integer.MAX_VALUE / spaces2; int number1 = WebSocketUtil.randomNumber(0, max1); int number2 = WebSocketUtil.randomNumber(0, max2); int product1 = number1 * spaces1; int product2 = number2 * spaces2; String key1 = Integer.toString(product1); String key2 = Integer.toString(product2); key1 = insertRandomCharacters(key1); key2 = insertRandomCharacters(key2); key1 = insertSpaces(key1, spaces1); key2 = insertSpaces(key2, spaces2); byte[] key3 = WebSocketUtil.randomBytes(8); ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(number1); byte[] number1Array = buffer.array(); buffer = ByteBuffer.allocate(4); buffer.putInt(number2); byte[] number2Array = buffer.array(); byte[] challenge = new byte[16]; System.arraycopy(number1Array, 0, challenge, 0, 4); System.arraycopy(number2Array, 0, challenge, 4, 4); System.arraycopy(key3, 0, challenge, 8, 8); expectedChallengeResponseBytes = Unpooled.wrappedBuffer(WebSocketUtil.md5(challenge)); // Get path URI wsURL = uri(); String path = rawPath(wsURL); // Format request FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); HttpHeaders headers = request.headers(); if (customHeaders != null) { headers.add(customHeaders); } headers.set(HttpHeaderNames.UPGRADE, WEBSOCKET) .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE) .set(HttpHeaderNames.HOST, websocketHostValue(wsURL)) .set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL)) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, key1) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, key2); String expectedSubprotocol = expectedSubprotocol(); if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); } // Set Content-Length to workaround some known defect. // See also: http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html headers.set(HttpHeaderNames.CONTENT_LENGTH, key3.length); request.content().writeBytes(key3); return request; }
<p> Sends the opening request to the server: </p> <pre> GET /demo HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: example.com Origin: http://example.com Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5 Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 ^n:ds[4U </pre>
@Override protected void verify(FullHttpResponse response) { if (!response.status().equals(HttpResponseStatus.SWITCHING_PROTOCOLS)) { throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status()); } HttpHeaders headers = response.headers(); CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE); if (!WEBSOCKET.contentEqualsIgnoreCase(upgrade)) { throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade); } if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) { throw new WebSocketHandshakeException("Invalid handshake response connection: " + headers.get(HttpHeaderNames.CONNECTION)); } ByteBuf challenge = response.content(); if (!challenge.equals(expectedChallengeResponseBytes)) { throw new WebSocketHandshakeException("Invalid challenge"); } }
<p> Process server response: </p> <pre> HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Origin: http://example.com Sec-WebSocket-Location: ws://example.com/demo Sec-WebSocket-Protocol: sample 8jKS'y:G*Co,Wxa- </pre> @param response HTTP response returned from the server for the request sent by beginOpeningHandshake00(). @throws WebSocketHandshakeException
public static DnsResponseCode valueOf(int responseCode) { switch (responseCode) { case 0: return NOERROR; case 1: return FORMERR; case 2: return SERVFAIL; case 3: return NXDOMAIN; case 4: return NOTIMP; case 5: return REFUSED; case 6: return YXDOMAIN; case 7: return YXRRSET; case 8: return NXRRSET; case 9: return NOTAUTH; case 10: return NOTZONE; case 16: return BADVERS_OR_BADSIG; case 17: return BADKEY; case 18: return BADTIME; case 19: return BADMODE; case 20: return BADNAME; case 21: return BADALG; default: return new DnsResponseCode(responseCode); } }
Returns the {@link DnsResponseCode} that corresponds with the given {@code responseCode}. @param responseCode the DNS RCODE @return the corresponding {@link DnsResponseCode}
private static void setExtendedParentPointers(final int[] array) { final int length = array.length; array[0] += array[1]; for (int headNode = 0, tailNode = 1, topNode = 2; tailNode < length - 1; tailNode++) { int temp; if (topNode >= length || array[headNode] < array[topNode]) { temp = array[headNode]; array[headNode++] = tailNode; } else { temp = array[topNode++]; } if (topNode >= length || (headNode < tailNode && array[headNode] < array[topNode])) { temp += array[headNode]; array[headNode++] = tailNode + length; } else { temp += array[topNode++]; } array[tailNode] = temp; } }
Fills the code array with extended parent pointers. @param array The code length array
private static int findNodesToRelocate(final int[] array, final int maximumLength) { int currentNode = array.length - 2; for (int currentDepth = 1; currentDepth < maximumLength - 1 && currentNode > 1; currentDepth++) { currentNode = first(array, currentNode - 1, 0); } return currentNode; }
Finds the number of nodes to relocate in order to achieve a given code length limit. @param array The code length array @param maximumLength The maximum bit length for the generated codes @return The number of nodes to relocate
private static void allocateNodeLengths(final int[] array) { int firstNode = array.length - 2; int nextNode = array.length - 1; for (int currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) { final int lastNode = firstNode; firstNode = first(array, lastNode - 1, 0); for (int i = availableNodes - (lastNode - firstNode); i > 0; i--) { array[nextNode--] = currentDepth; } availableNodes = (lastNode - firstNode) << 1; } }
A final allocation pass with no code length limit. @param array The code length array
private static void allocateNodeLengthsWithRelocation(final int[] array, final int nodesToMove, final int insertDepth) { int firstNode = array.length - 2; int nextNode = array.length - 1; int currentDepth = insertDepth == 1 ? 2 : 1; int nodesLeftToMove = insertDepth == 1 ? nodesToMove - 2 : nodesToMove; for (int availableNodes = currentDepth << 1; availableNodes > 0; currentDepth++) { final int lastNode = firstNode; firstNode = firstNode <= nodesToMove ? firstNode : first(array, lastNode - 1, nodesToMove); int offset = 0; if (currentDepth >= insertDepth) { offset = Math.min(nodesLeftToMove, 1 << (currentDepth - insertDepth)); } else if (currentDepth == insertDepth - 1) { offset = 1; if (array[firstNode] == lastNode) { firstNode++; } } for (int i = availableNodes - (lastNode - firstNode + offset); i > 0; i--) { array[nextNode--] = currentDepth; } nodesLeftToMove -= offset; availableNodes = (lastNode - firstNode + offset) << 1; } }
A final allocation pass that relocates nodes in order to achieve a maximum code length limit. @param array The code length array @param nodesToMove The number of internal nodes to be relocated @param insertDepth The depth at which to insert relocated nodes
static void allocateHuffmanCodeLengths(final int[] array, final int maximumLength) { switch (array.length) { case 2: array[1] = 1; // fall through case 1: array[0] = 1; return; } /* Pass 1 : Set extended parent pointers */ setExtendedParentPointers(array); /* Pass 2 : Find number of nodes to relocate in order to achieve maximum code length */ int nodesToRelocate = findNodesToRelocate(array, maximumLength); /* Pass 3 : Generate code lengths */ if (array[0] % array.length >= nodesToRelocate) { allocateNodeLengths(array); } else { int insertDepth = maximumLength - (32 - Integer.numberOfLeadingZeros(nodesToRelocate - 1)); allocateNodeLengthsWithRelocation(array, nodesToRelocate, insertDepth); } }
Allocates Canonical Huffman code lengths in place based on a sorted frequency array. @param array On input, a sorted array of symbol frequencies; On output, an array of Canonical Huffman code lengths @param maximumLength The maximum code length. Must be at least {@code ceil(log2(array.length))}
public int statusCode() { ByteBuf binaryData = content(); if (binaryData == null || binaryData.capacity() == 0) { return -1; } binaryData.readerIndex(0); int statusCode = binaryData.readShort(); binaryData.readerIndex(0); return statusCode; }
Returns the closing status code as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a>. If a getStatus code is set, -1 is returned.
public String reasonText() { ByteBuf binaryData = content(); if (binaryData == null || binaryData.capacity() <= 2) { return ""; } binaryData.readerIndex(2); String reasonText = binaryData.toString(CharsetUtil.UTF_8); binaryData.readerIndex(0); return reasonText; }
Returns the reason text as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a> If a reason text is not supplied, an empty string is returned.
public void close() throws IOException { for (;;) { int state = this.state; if (isClosed(state)) { return; } // Once a close operation happens, the channel is considered shutdown. if (casState(state, state | STATE_ALL_MASK)) { break; } } int res = close(fd); if (res < 0) { throw newIOException("close", res); } }
Close the file descriptor.
public static FileDescriptor from(String path) throws IOException { checkNotNull(path, "path"); int res = open(path); if (res < 0) { throw newIOException("open", res); } return new FileDescriptor(res); }
Open a new {@link FileDescriptor} for the given path.
@Override public synchronized void start() { if (monitorActive) { return; } lastTime.set(milliSecondFromNano()); long localCheckInterval = checkInterval.get(); if (localCheckInterval > 0) { monitorActive = true; monitor = new MixedTrafficMonitoringTask((GlobalChannelTrafficShapingHandler) trafficShapingHandler, this); scheduledFuture = executor.schedule(monitor, localCheckInterval, TimeUnit.MILLISECONDS); } }
Start the monitoring process.
public static Http2Exception getEmbeddedHttp2Exception(Throwable cause) { while (cause != null) { if (cause instanceof Http2Exception) { return (Http2Exception) cause; } cause = cause.getCause(); } return null; }
Iteratively looks through the causality chain for the given exception and returns the first {@link Http2Exception} or {@code null} if none.
public static ByteBuf toByteBuf(ChannelHandlerContext ctx, Throwable cause) { if (cause == null || cause.getMessage() == null) { return Unpooled.EMPTY_BUFFER; } return ByteBufUtil.writeUtf8(ctx.alloc(), cause.getMessage()); }
Creates a buffer containing the error message from the given exception. If the cause is {@code null} returns an empty buffer.
public static void writeFrameHeader(ByteBuf out, int payloadLength, byte type, Http2Flags flags, int streamId) { out.ensureWritable(FRAME_HEADER_LENGTH + payloadLength); writeFrameHeaderInternal(out, payloadLength, type, flags, streamId); }
Writes an HTTP/2 frame header to the output buffer.
public static int streamableBytes(StreamByteDistributor.StreamState state) { return max(0, (int) min(state.pendingBytes(), state.windowSize())); }
Calculate the amount of bytes that can be sent by {@code state}. The lower bound is {@code 0}.
public static void headerListSizeExceeded(int streamId, long maxHeaderListSize, boolean onDecode) throws Http2Exception { throw headerListSizeError(streamId, PROTOCOL_ERROR, onDecode, "Header size exceeded max " + "allowed size (%d)", maxHeaderListSize); }
Results in a RST_STREAM being sent for {@code streamId} due to violating <a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">SETTINGS_MAX_HEADER_LIST_SIZE</a>. @param streamId The stream ID that was being processed when the exceptional condition occurred. @param maxHeaderListSize The max allowed size for a list of headers in bytes which was exceeded. @param onDecode {@code true} if the exception was encountered during decoder. {@code false} for encode. @throws Http2Exception a stream error.
@Override public boolean cancel(boolean mayInterruptIfRunning) { if (RESULT_UPDATER.compareAndSet(this, null, CANCELLATION_CAUSE_HOLDER)) { if (checkNotifyWaiters()) { notifyListeners(); } return true; } return false; }
{@inheritDoc} @param mayInterruptIfRunning this value has no effect in this implementation.
protected static void notifyListener( EventExecutor eventExecutor, final Future<?> future, final GenericFutureListener<?> listener) { checkNotNull(eventExecutor, "eventExecutor"); checkNotNull(future, "future"); checkNotNull(listener, "listener"); notifyListenerWithStackOverFlowProtection(eventExecutor, future, listener); }
Notify a listener that a future has completed. <p> This method has a fixed depth of {@link #MAX_LISTENER_STACK_DEPTH} that will limit recursion to prevent {@link StackOverflowError} and will stop notifying listeners added after this threshold is exceeded. @param eventExecutor the executor to use to notify the listener {@code listener}. @param future the future that is complete. @param listener the listener to notify.
private static void notifyListenerWithStackOverFlowProtection(final EventExecutor executor, final Future<?> future, final GenericFutureListener<?> listener) { if (executor.inEventLoop()) { final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); final int stackDepth = threadLocals.futureListenerStackDepth(); if (stackDepth < MAX_LISTENER_STACK_DEPTH) { threadLocals.setFutureListenerStackDepth(stackDepth + 1); try { notifyListener0(future, listener); } finally { threadLocals.setFutureListenerStackDepth(stackDepth); } return; } } safeExecute(executor, new Runnable() { @Override public void run() { notifyListener0(future, listener); } }); }
The logic in this method should be identical to {@link #notifyListeners()} but cannot share code because the listener(s) cannot be cached for an instance of {@link DefaultPromise} since the listener(s) may be changed and is protected by a synchronized operation.
@SuppressWarnings("unchecked") void notifyProgressiveListeners(final long progress, final long total) { final Object listeners = progressiveListeners(); if (listeners == null) { return; } final ProgressiveFuture<V> self = (ProgressiveFuture<V>) this; EventExecutor executor = executor(); if (executor.inEventLoop()) { if (listeners instanceof GenericProgressiveFutureListener[]) { notifyProgressiveListeners0( self, (GenericProgressiveFutureListener<?>[]) listeners, progress, total); } else { notifyProgressiveListener0( self, (GenericProgressiveFutureListener<ProgressiveFuture<V>>) listeners, progress, total); } } else { if (listeners instanceof GenericProgressiveFutureListener[]) { final GenericProgressiveFutureListener<?>[] array = (GenericProgressiveFutureListener<?>[]) listeners; safeExecute(executor, new Runnable() { @Override public void run() { notifyProgressiveListeners0(self, array, progress, total); } }); } else { final GenericProgressiveFutureListener<ProgressiveFuture<V>> l = (GenericProgressiveFutureListener<ProgressiveFuture<V>>) listeners; safeExecute(executor, new Runnable() { @Override public void run() { notifyProgressiveListener0(self, l, progress, total); } }); } } }
Notify all progressive listeners. <p> No attempt is made to ensure notification order if multiple calls are made to this method before the original invocation completes. <p> This will do an iteration over all listeners to get all of type {@link GenericProgressiveFutureListener}s. @param progress the new progress. @param total the total progress.
private synchronized Object progressiveListeners() { Object listeners = this.listeners; if (listeners == null) { // No listeners added return null; } if (listeners instanceof DefaultFutureListeners) { // Copy DefaultFutureListeners into an array of listeners. DefaultFutureListeners dfl = (DefaultFutureListeners) listeners; int progressiveSize = dfl.progressiveSize(); switch (progressiveSize) { case 0: return null; case 1: for (GenericFutureListener<?> l: dfl.listeners()) { if (l instanceof GenericProgressiveFutureListener) { return l; } } return null; } GenericFutureListener<?>[] array = dfl.listeners(); GenericProgressiveFutureListener<?>[] copy = new GenericProgressiveFutureListener[progressiveSize]; for (int i = 0, j = 0; j < progressiveSize; i ++) { GenericFutureListener<?> l = array[i]; if (l instanceof GenericProgressiveFutureListener) { copy[j ++] = (GenericProgressiveFutureListener<?>) l; } } return copy; } else if (listeners instanceof GenericProgressiveFutureListener) { return listeners; } else { // Only one listener was added and it's not a progressive listener. return null; } }
Returns a {@link GenericProgressiveFutureListener}, an array of {@link GenericProgressiveFutureListener}, or {@code null}.
protected final void init(I inboundHandler, O outboundHandler) { validate(inboundHandler, outboundHandler); this.inboundHandler = inboundHandler; this.outboundHandler = outboundHandler; }
Initialized this handler with the specified handlers. @throws IllegalStateException if this handler was not constructed via the default constructor or if this handler does not implement all required handler interfaces @throws IllegalArgumentException if the specified handlers cannot be combined into one due to a conflict in the type hierarchy
public static String substringAfter(String value, char delim) { int pos = value.indexOf(delim); if (pos >= 0) { return value.substring(pos + 1); } return null; }
Get the item after one char delim if the delim is found (else null). This operation is a simplified and optimized version of {@link String#split(String, int)}.
public static boolean commonSuffixOfLength(String s, String p, int len) { return s != null && p != null && len >= 0 && s.regionMatches(s.length() - len, p, p.length() - len, len); }
Checks if two strings have the same suffix of specified length @param s string @param p string @param len length of the common suffix @return true if both s and p are not null and both have the same suffix. Otherwise - false
public static String toHexStringPadded(byte[] src, int offset, int length) { return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString(); }
Converts the specified byte array into a hexadecimal value.
public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src) { return toHexStringPadded(dst, src, 0, src.length); }
Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src, int offset, int length) { final int end = offset + length; for (int i = offset; i < end; i++) { byteToHexStringPadded(dst, src[i]); } return dst; }
Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
public static <T extends Appendable> T byteToHexString(T buf, int value) { try { buf.append(byteToHexString(value)); } catch (IOException e) { PlatformDependent.throwException(e); } return buf; }
Converts the specified byte value into a hexadecimal integer and appends it to the specified buffer.
public static String toHexString(byte[] src, int offset, int length) { return toHexString(new StringBuilder(length << 1), src, offset, length).toString(); }
Converts the specified byte array into a hexadecimal value.
public static <T extends Appendable> T toHexString(T dst, byte[] src) { return toHexString(dst, src, 0, src.length); }
Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) { assert length >= 0; if (length == 0) { return dst; } final int end = offset + length; final int endMinusOne = end - 1; int i; // Skip preceding zeroes. for (i = offset; i < endMinusOne; i++) { if (src[i] != 0) { break; } } byteToHexString(dst, src[i++]); int remaining = end - i; toHexStringPadded(dst, src, i, remaining); return dst; }
Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
public static byte decodeHexByte(CharSequence s, int pos) { int hi = decodeHexNibble(s.charAt(pos)); int lo = decodeHexNibble(s.charAt(pos + 1)); if (hi == -1 || lo == -1) { throw new IllegalArgumentException(String.format( "invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s)); } return (byte) ((hi << 4) + lo); }
Decode a 2-digit hex byte from within a string.
public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) { if (length < 0 || (length & 1) != 0) { throw new IllegalArgumentException("length: " + length); } if (length == 0) { return EmptyArrays.EMPTY_BYTES; } byte[] bytes = new byte[length >>> 1]; for (int i = 0; i < length; i += 2) { bytes[i >>> 1] = decodeHexByte(hexDump, fromIndex + i); } return bytes; }
Decodes part of a string with <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> @param hexDump a {@link CharSequence} which contains the hex dump @param fromIndex start of hex dump in {@code hexDump} @param length hex string length
public static String simpleClassName(Class<?> clazz) { String className = checkNotNull(clazz, "clazz").getName(); final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); if (lastDotIdx > -1) { return className.substring(lastDotIdx + 1); } return className; }
Generates a simplified name from a {@link Class}. Similar to {@link Class#getSimpleName()}, but it works fine with anonymous classes.
public static CharSequence escapeCsv(CharSequence value, boolean trimWhiteSpace) { int length = checkNotNull(value, "value").length(); int start; int last; if (trimWhiteSpace) { start = indexOfFirstNonOwsChar(value, length); last = indexOfLastNonOwsChar(value, start, length); } else { start = 0; last = length - 1; } if (start > last) { return EMPTY_STRING; } int firstUnescapedSpecial = -1; boolean quoted = false; if (isDoubleQuote(value.charAt(start))) { quoted = isDoubleQuote(value.charAt(last)) && last > start; if (quoted) { start++; last--; } else { firstUnescapedSpecial = start; } } if (firstUnescapedSpecial < 0) { if (quoted) { for (int i = start; i <= last; i++) { if (isDoubleQuote(value.charAt(i))) { if (i == last || !isDoubleQuote(value.charAt(i + 1))) { firstUnescapedSpecial = i; break; } i++; } } } else { for (int i = start; i <= last; i++) { char c = value.charAt(i); if (c == LINE_FEED || c == CARRIAGE_RETURN || c == COMMA) { firstUnescapedSpecial = i; break; } if (isDoubleQuote(c)) { if (i == last || !isDoubleQuote(value.charAt(i + 1))) { firstUnescapedSpecial = i; break; } i++; } } } if (firstUnescapedSpecial < 0) { // Special characters is not found or all of them already escaped. // In the most cases returns a same string. New string will be instantiated (via StringBuilder) // only if it really needed. It's important to prevent GC extra load. return quoted? value.subSequence(start - 1, last + 2) : value.subSequence(start, last + 1); } } StringBuilder result = new StringBuilder(last - start + 1 + CSV_NUMBER_ESCAPE_CHARACTERS); result.append(DOUBLE_QUOTE).append(value, start, firstUnescapedSpecial); for (int i = firstUnescapedSpecial; i <= last; i++) { char c = value.charAt(i); if (isDoubleQuote(c)) { result.append(DOUBLE_QUOTE); if (i < last && isDoubleQuote(value.charAt(i + 1))) { i++; } } result.append(c); } return result.append(DOUBLE_QUOTE); }
Escapes the specified value, if necessary according to <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>. @param value The value which will be escaped according to <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a> @param trimWhiteSpace The value will first be trimmed of its optional white-space characters, according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a> @return {@link CharSequence} the escaped value if necessary, or the value unchanged
public static CharSequence unescapeCsv(CharSequence value) { int length = checkNotNull(value, "value").length(); if (length == 0) { return value; } int last = length - 1; boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length != 1; if (!quoted) { validateCsvFormat(value); return value; } StringBuilder unescaped = InternalThreadLocalMap.get().stringBuilder(); for (int i = 1; i < last; i++) { char current = value.charAt(i); if (current == DOUBLE_QUOTE) { if (isDoubleQuote(value.charAt(i + 1)) && (i + 1) != last) { // Followed by a double-quote but not the last character // Just skip the next double-quote i++; } else { // Not followed by a double-quote or the following double-quote is the last character throw newInvalidEscapedCsvFieldException(value, i); } } unescaped.append(current); } return unescaped.toString(); }
Unescapes the specified escaped CSV field, if necessary according to <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>. @param value The escaped CSV field which will be unescaped according to <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a> @return {@link CharSequence} the unescaped value if necessary, or the value unchanged
public static List<CharSequence> unescapeCsvFields(CharSequence value) { List<CharSequence> unescaped = new ArrayList<CharSequence>(2); StringBuilder current = InternalThreadLocalMap.get().stringBuilder(); boolean quoted = false; int last = value.length() - 1; for (int i = 0; i <= last; i++) { char c = value.charAt(i); if (quoted) { switch (c) { case DOUBLE_QUOTE: if (i == last) { // Add the last field and return unescaped.add(current.toString()); return unescaped; } char next = value.charAt(++i); if (next == DOUBLE_QUOTE) { // 2 double-quotes should be unescaped to one current.append(DOUBLE_QUOTE); break; } if (next == COMMA) { // This is the end of a field. Let's start to parse the next field. quoted = false; unescaped.add(current.toString()); current.setLength(0); break; } // double-quote followed by other character is invalid throw newInvalidEscapedCsvFieldException(value, i - 1); default: current.append(c); } } else { switch (c) { case COMMA: // Start to parse the next field unescaped.add(current.toString()); current.setLength(0); break; case DOUBLE_QUOTE: if (current.length() == 0) { quoted = true; break; } // double-quote appears without being enclosed with double-quotes // fall through case LINE_FEED: // fall through case CARRIAGE_RETURN: // special characters appears without being enclosed with double-quotes throw newInvalidEscapedCsvFieldException(value, i); default: current.append(c); } } } if (quoted) { throw newInvalidEscapedCsvFieldException(value, last); } unescaped.add(current.toString()); return unescaped; }
Unescapes the specified escaped CSV fields according to <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>. @param value A string with multiple CSV escaped fields which will be unescaped according to <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a> @return {@link List} the list of unescaped fields
private static void validateCsvFormat(CharSequence value) { int length = value.length(); for (int i = 0; i < length; i++) { switch (value.charAt(i)) { case DOUBLE_QUOTE: case LINE_FEED: case CARRIAGE_RETURN: case COMMA: // If value contains any special character, it should be enclosed with double-quotes throw newInvalidEscapedCsvFieldException(value, i); default: } } }
Validate if {@code value} is a valid csv field without double-quotes. @throws IllegalArgumentException if {@code value} needs to be encoded with double-quotes.
public static int indexOfNonWhiteSpace(CharSequence seq, int offset) { for (; offset < seq.length(); ++offset) { if (!Character.isWhitespace(seq.charAt(offset))) { return offset; } } return -1; }
Find the index of the first non-white space character in {@code s} starting at {@code offset}. @param seq The string to search. @param offset The offset to start searching at. @return the index of the first non-white space character or &lt;{@code 0} if none was found.
public static boolean endsWith(CharSequence s, char c) { int len = s.length(); return len > 0 && s.charAt(len - 1) == c; }
Determine if the string {@code s} ends with the char {@code c}. @param s the string to test @param c the tested char @return true if {@code s} ends with the char {@code c}
public static CharSequence trimOws(CharSequence value) { final int length = value.length(); if (length == 0) { return value; } int start = indexOfFirstNonOwsChar(value, length); int end = indexOfLastNonOwsChar(value, start, length); return start == 0 && end == length - 1 ? value : value.subSequence(start, end + 1); }
Trim optional white-space characters from the specified value, according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a>. @param value the value to trim @return {@link CharSequence} the trimmed value if necessary, or the value unchanged
private void sendInitialMessage(final ChannelHandlerContext ctx) throws Exception { final long connectTimeoutMillis = this.connectTimeoutMillis; if (connectTimeoutMillis > 0) { connectTimeoutFuture = ctx.executor().schedule(new Runnable() { @Override public void run() { if (!connectPromise.isDone()) { setConnectFailure(new ProxyConnectException(exceptionMessage("timeout"))); } } }, connectTimeoutMillis, TimeUnit.MILLISECONDS); } final Object initialMessage = newInitialMessage(ctx); if (initialMessage != null) { sendToProxyServer(initialMessage); } readIfNeeded(ctx); }
Sends the initial message to be sent to the proxy server. This method also starts a timeout task which marks the {@link #connectPromise} as failure if the connection attempt does not success within the timeout.
protected final String exceptionMessage(String msg) { if (msg == null) { msg = ""; } StringBuilder buf = new StringBuilder(128 + msg.length()) .append(protocol()) .append(", ") .append(authScheme()) .append(", ") .append(proxyAddress) .append(" => ") .append(destinationAddress); if (!msg.isEmpty()) { buf.append(", ").append(msg); } return buf.toString(); }
Decorates the specified exception message with the common information such as the current protocol, authentication scheme, proxy address, and destination address.