|
| 1 | +/* |
| 2 | + * Copyright 2026 The Netty Project |
| 3 | + * |
| 4 | + * The Netty Project licenses this file to you under the Apache License, |
| 5 | + * version 2.0 (the "License"); you may not use this file except in compliance |
| 6 | + * with the License. You may obtain a copy of the License at: |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | + * License for the specific language governing permissions and limitations |
| 14 | + * under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import io.netty.bootstrap.Bootstrap; |
| 18 | +import io.netty.buffer.ByteBuf; |
| 19 | +import io.netty.buffer.Unpooled; |
| 20 | +import io.netty.channel.Channel; |
| 21 | +import io.netty.channel.ChannelHandler; |
| 22 | +import io.netty.channel.ChannelHandlerContext; |
| 23 | +import io.netty.channel.ChannelInboundHandlerAdapter; |
| 24 | +import io.netty.channel.ChannelInitializer; |
| 25 | +import io.netty.channel.EventLoopGroup; |
| 26 | +import io.netty.channel.MultiThreadIoEventLoopGroup; |
| 27 | +import io.netty.channel.nio.NioIoHandler; |
| 28 | +import io.netty.channel.socket.nio.NioDatagramChannel; |
| 29 | +import io.netty.handler.codec.quic.InsecureQuicTokenHandler; |
| 30 | +import io.netty.handler.codec.quic.Quic; |
| 31 | +import io.netty.handler.codec.quic.QuicChannel; |
| 32 | +import io.netty.handler.codec.quic.QuicClientCodecBuilder; |
| 33 | +import io.netty.handler.codec.quic.QuicServerCodecBuilder; |
| 34 | +import io.netty.handler.codec.quic.QuicSslContext; |
| 35 | +import io.netty.handler.codec.quic.QuicSslContextBuilder; |
| 36 | +import io.netty.handler.codec.quic.QuicStreamChannel; |
| 37 | +import io.netty.handler.codec.quic.QuicStreamType; |
| 38 | +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; |
| 39 | +import io.netty.util.CharsetUtil; |
| 40 | + |
| 41 | +import javax.net.ssl.KeyManagerFactory; |
| 42 | +import java.io.File; |
| 43 | +import java.io.FileInputStream; |
| 44 | +import java.io.InputStream; |
| 45 | +import java.net.InetAddress; |
| 46 | +import java.net.InetSocketAddress; |
| 47 | +import java.security.KeyStore; |
| 48 | +import java.util.concurrent.LinkedBlockingQueue; |
| 49 | +import java.util.concurrent.TimeUnit; |
| 50 | + |
| 51 | +/** |
| 52 | + * Checks that a Linux {@code libnetty_quiche*.so} built against glibc can be loaded, initialized |
| 53 | + * and actually <em>used</em> by the libc of the machine running this class. Written for |
| 54 | + * Alpine/musl, with a glibc run as the control. |
| 55 | + * |
| 56 | + * <p>The handshake level is the point of this class. musl does not fail a dlopen on a relocation |
| 57 | + * it cannot resolve -- it defers it and aborts at the first call instead -- so "the library |
| 58 | + * loaded" says very little about a library that carries a whole Rust standard library inside it. |
| 59 | + * The undefined glibc-only symbols that motivated {@code musl_compat.c} (the LFS64 family, |
| 60 | + * {@code __xstat64} and friends) sit in quiche's file and socket paths, which nothing before this |
| 61 | + * level touches. A run that stops at {@code init} would have reported PASS for every artifact |
| 62 | + * netty has ever released. |
| 63 | + * |
| 64 | + * <p>One level per JVM, chosen by the first argument, so a hard crash in an early level cannot |
| 65 | + * hide a later one. The historical aarch64 failure in netty-tcnative was a SIGSEGV inside |
| 66 | + * {@code JVM_LoadLibrary} rather than an exception, so the caller must also treat a JVM that dies |
| 67 | + * without printing a RESULT line as a failure -- see verify.sh. |
| 68 | + * |
| 69 | + * <p>Client and server both run in this one JVM over the loopback interface: a QUIC handshake |
| 70 | + * needs two peers, and putting them in two containers would test the container network rather |
| 71 | + * than the library. |
| 72 | + * |
| 73 | + * <p>Deliberately kept to Java 8 syntax and to the netty artifacts themselves. The server |
| 74 | + * certificate comes in as a PKCS#12 keystore built by keytool rather than from |
| 75 | + * {@code SelfSignedCertificate}, which needs either a BouncyCastle jar or |
| 76 | + * {@code --add-exports java.base/sun.security.x509} and would make the check fail for reasons |
| 77 | + * that have nothing to do with musl. |
| 78 | + */ |
| 79 | +public final class QuicMuslCheck { |
| 80 | + |
| 81 | + private static final String ALPN = "netty-musl-check"; |
| 82 | + private static final String PAYLOAD = "PING"; |
| 83 | + private static final long TIMEOUT_SECONDS = 30; |
| 84 | + |
| 85 | + private static boolean failed; |
| 86 | + |
| 87 | + public static void main(String[] args) { |
| 88 | + if (args.length < 2) { |
| 89 | + System.err.println("usage: QuicMuslCheck <load|init|handshake> <path-to-.so> [keystore.p12] [password]"); |
| 90 | + System.exit(2); |
| 91 | + } |
| 92 | + String level = args[0]; |
| 93 | + String soPath = args[1]; |
| 94 | + |
| 95 | + try { |
| 96 | + // Every level needs the library loaded; the load itself is level "load". |
| 97 | + load(soPath); |
| 98 | + if (!"load".equals(level)) { |
| 99 | + init(); |
| 100 | + if ("handshake".equals(level)) { |
| 101 | + if (args.length < 4) { |
| 102 | + throw new IllegalStateException("the handshake level needs a keystore and a password"); |
| 103 | + } |
| 104 | + handshake(args[2], args[3]); |
| 105 | + } |
| 106 | + } |
| 107 | + } catch (Throwable t) { |
| 108 | + // A missing symbol surfaces here as the musl loader's own text, e.g. |
| 109 | + // "Error relocating <lib>: __xstat64: symbol not found". |
| 110 | + result(level, false, rootMessage(t)); |
| 111 | + } |
| 112 | + System.exit(failed ? 1 : 0); |
| 113 | + } |
| 114 | + |
| 115 | + /** |
| 116 | + * Loads the .so straight off disk, before netty gets a chance to unpack its own copy. This is |
| 117 | + * the level that catches an unresolvable DT_NEEDED, which on musl is a hard dlopen failure |
| 118 | + * rather than a deferred one. |
| 119 | + * |
| 120 | + * <p>Not a pure dlopen, and cannot be made into one: the library's {@code JNI_OnLoad} calls |
| 121 | + * FindClass, so a successful dlopen continues straight into netty's own class and library |
| 122 | + * loading. Reading a failure here therefore means looking at which file the message names -- |
| 123 | + * this one, or the temporary copy {@code NativeLibraryLoader} unpacks out of the jar. |
| 124 | + */ |
| 125 | + private static void load(String soPath) { |
| 126 | + File so = new File(soPath); |
| 127 | + if (!so.isFile()) { |
| 128 | + throw new IllegalStateException("not a file: " + soPath); |
| 129 | + } |
| 130 | + System.load(so.getAbsolutePath()); |
| 131 | + result("load", true, "System.load ok: " + so.getName()); |
| 132 | + } |
| 133 | + |
| 134 | + private static void init() { |
| 135 | + // Loads netty's own copy out of the jar and runs the static initializer, which calls into |
| 136 | + // quiche for the version string. |
| 137 | + Quic.ensureAvailability(); |
| 138 | + result("init", true, "Quic.isAvailable()=" + Quic.isAvailable()); |
| 139 | + } |
| 140 | + |
| 141 | + private static void handshake(String keystorePath, String password) throws Exception { |
| 142 | + EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()); |
| 143 | + Channel serverChannel = null; |
| 144 | + Channel clientChannel = null; |
| 145 | + try { |
| 146 | + InetAddress loopback = InetAddress.getLoopbackAddress(); |
| 147 | + serverChannel = new Bootstrap() |
| 148 | + .group(group) |
| 149 | + .channel(NioDatagramChannel.class) |
| 150 | + .handler(newServerCodec(keystorePath, password)) |
| 151 | + .bind(new InetSocketAddress(loopback, 0)).sync().channel(); |
| 152 | + int port = ((InetSocketAddress) serverChannel.localAddress()).getPort(); |
| 153 | + result("handshake", true, "server bound on " + loopback.getHostAddress() + ':' + port); |
| 154 | + |
| 155 | + QuicSslContext clientSslContext = QuicSslContextBuilder.forClient() |
| 156 | + .trustManager(InsecureTrustManagerFactory.INSTANCE) |
| 157 | + .applicationProtocols(ALPN) |
| 158 | + .build(); |
| 159 | + ChannelHandler clientCodec = new QuicClientCodecBuilder() |
| 160 | + .sslContext(clientSslContext) |
| 161 | + .maxIdleTimeout(5000, TimeUnit.MILLISECONDS) |
| 162 | + .initialMaxData(1000000) |
| 163 | + .initialMaxStreamDataBidirectionalLocal(100000) |
| 164 | + .build(); |
| 165 | + clientChannel = new Bootstrap() |
| 166 | + .group(group) |
| 167 | + .channel(NioDatagramChannel.class) |
| 168 | + .handler(clientCodec) |
| 169 | + .bind(new InetSocketAddress(loopback, 0)).sync().channel(); |
| 170 | + |
| 171 | + QuicChannel quicChannel = QuicChannel.newBootstrap(clientChannel) |
| 172 | + .streamHandler(new ChannelInboundHandlerAdapter()) |
| 173 | + .remoteAddress(new InetSocketAddress(loopback, port)) |
| 174 | + .connect() |
| 175 | + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); |
| 176 | + result("handshake", true, "connected, alpn=" + ALPN); |
| 177 | + |
| 178 | + // A queue rather than a latch plus a field: it carries the echoed bytes and the |
| 179 | + // "stream closed with nothing" case in one place, and poll() gives the timeout. |
| 180 | + LinkedBlockingQueue<String> echoed = new LinkedBlockingQueue<String>(); |
| 181 | + QuicStreamChannel stream = quicChannel.createStream( |
| 182 | + QuicStreamType.BIDIRECTIONAL, new EchoCollector(echoed)).sync().getNow(); |
| 183 | + stream.writeAndFlush(Unpooled.copiedBuffer(PAYLOAD, CharsetUtil.US_ASCII)) |
| 184 | + .addListener(QuicStreamChannel.SHUTDOWN_OUTPUT); |
| 185 | + |
| 186 | + String received = echoed.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); |
| 187 | + if (received == null) { |
| 188 | + throw new IllegalStateException("no echo within " + TIMEOUT_SECONDS + "s"); |
| 189 | + } |
| 190 | + if (!PAYLOAD.equals(received)) { |
| 191 | + throw new IllegalStateException("echo mismatch: expected '" + PAYLOAD |
| 192 | + + "' but got '" + received + '\''); |
| 193 | + } |
| 194 | + result("handshake", true, "bidirectional stream echoed " + received.length() + " bytes"); |
| 195 | + |
| 196 | + quicChannel.close().sync(); |
| 197 | + } finally { |
| 198 | + if (clientChannel != null) { |
| 199 | + clientChannel.close().sync(); |
| 200 | + } |
| 201 | + if (serverChannel != null) { |
| 202 | + serverChannel.close().sync(); |
| 203 | + } |
| 204 | + group.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync(); |
| 205 | + } |
| 206 | + } |
| 207 | + |
| 208 | + private static ChannelHandler newServerCodec(String keystorePath, String password) throws Exception { |
| 209 | + KeyStore keyStore = KeyStore.getInstance("PKCS12"); |
| 210 | + InputStream in = new FileInputStream(keystorePath); |
| 211 | + try { |
| 212 | + keyStore.load(in, password.toCharArray()); |
| 213 | + } finally { |
| 214 | + in.close(); |
| 215 | + } |
| 216 | + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
| 217 | + kmf.init(keyStore, password.toCharArray()); |
| 218 | + |
| 219 | + QuicSslContext sslContext = QuicSslContextBuilder.forServer(kmf, password) |
| 220 | + .applicationProtocols(ALPN) |
| 221 | + .build(); |
| 222 | + return new QuicServerCodecBuilder() |
| 223 | + .sslContext(sslContext) |
| 224 | + .maxIdleTimeout(5000, TimeUnit.MILLISECONDS) |
| 225 | + .initialMaxData(1000000) |
| 226 | + .initialMaxStreamDataBidirectionalLocal(100000) |
| 227 | + .initialMaxStreamDataBidirectionalRemote(100000) |
| 228 | + .initialMaxStreamsBidirectional(10) |
| 229 | + .tokenHandler(InsecureQuicTokenHandler.INSTANCE) |
| 230 | + .handler(new SharableNoopHandler()) |
| 231 | + .streamHandler(new ChannelInitializer<QuicStreamChannel>() { |
| 232 | + @Override |
| 233 | + protected void initChannel(QuicStreamChannel ch) { |
| 234 | + ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { |
| 235 | + @Override |
| 236 | + public void channelRead(ChannelHandlerContext ctx, Object msg) { |
| 237 | + // Echo straight back and send the FIN with it. The payload is a |
| 238 | + // handful of bytes, so it cannot arrive split. |
| 239 | + ctx.writeAndFlush(msg).addListener(QuicStreamChannel.SHUTDOWN_OUTPUT); |
| 240 | + } |
| 241 | + }); |
| 242 | + } |
| 243 | + }) |
| 244 | + .build(); |
| 245 | + } |
| 246 | + |
| 247 | + /** Collects the echoed bytes and hands them over once the peer has sent its FIN. */ |
| 248 | + private static final class EchoCollector extends ChannelInboundHandlerAdapter { |
| 249 | + |
| 250 | + private final LinkedBlockingQueue<String> out; |
| 251 | + private final StringBuilder received = new StringBuilder(); |
| 252 | + |
| 253 | + EchoCollector(LinkedBlockingQueue<String> out) { |
| 254 | + this.out = out; |
| 255 | + } |
| 256 | + |
| 257 | + @Override |
| 258 | + public void channelRead(ChannelHandlerContext ctx, Object msg) { |
| 259 | + ByteBuf buf = (ByteBuf) msg; |
| 260 | + try { |
| 261 | + received.append(buf.toString(CharsetUtil.US_ASCII)); |
| 262 | + } finally { |
| 263 | + buf.release(); |
| 264 | + } |
| 265 | + } |
| 266 | + |
| 267 | + @Override |
| 268 | + public void channelInactive(ChannelHandlerContext ctx) { |
| 269 | + out.offer(received.toString()); |
| 270 | + } |
| 271 | + |
| 272 | + @Override |
| 273 | + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { |
| 274 | + out.offer("exception: " + cause); |
| 275 | + ctx.close(); |
| 276 | + } |
| 277 | + } |
| 278 | + |
| 279 | + /** The server needs one connection-level handler instance across every connection. */ |
| 280 | + private static final class SharableNoopHandler extends ChannelInboundHandlerAdapter { |
| 281 | + @Override |
| 282 | + public boolean isSharable() { |
| 283 | + return true; |
| 284 | + } |
| 285 | + } |
| 286 | + |
| 287 | + private static void result(String level, boolean pass, String detail) { |
| 288 | + if (!pass) { |
| 289 | + failed = true; |
| 290 | + } |
| 291 | + System.out.println("RESULT\t" + level + '\t' + (pass ? "PASS" : "FAIL") + '\t' + detail); |
| 292 | + } |
| 293 | + |
| 294 | + /** Walks to the deepest cause and flattens it onto one line. */ |
| 295 | + private static String rootMessage(Throwable t) { |
| 296 | + Throwable root = t; |
| 297 | + while (root.getCause() != null && root.getCause() != root) { |
| 298 | + root = root.getCause(); |
| 299 | + } |
| 300 | + String msg = root.getMessage(); |
| 301 | + if (msg == null || msg.isEmpty()) { |
| 302 | + msg = root.toString(); |
| 303 | + } |
| 304 | + return root.getClass().getSimpleName() + ": " + msg.replace('\n', ' ').replace('\r', ' '); |
| 305 | + } |
| 306 | + |
| 307 | + private QuicMuslCheck() { |
| 308 | + } |
| 309 | +} |