|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.apache.thrift.transport; |
| 21 | + |
| 22 | +import java.io.IOException; |
| 23 | +import java.nio.ByteBuffer; |
| 24 | +import java.nio.channels.SelectionKey; |
| 25 | +import java.nio.channels.Selector; |
| 26 | +import javax.net.ssl.SSLContext; |
| 27 | +import javax.net.ssl.SSLEngine; |
| 28 | +import javax.net.ssl.SSLEngineResult; |
| 29 | +import javax.net.ssl.SSLEngineResult.HandshakeStatus; |
| 30 | +import javax.net.ssl.SSLException; |
| 31 | +import org.slf4j.Logger; |
| 32 | +import org.slf4j.LoggerFactory; |
| 33 | + |
| 34 | +/** Transport for use with async ssl client. */ |
| 35 | +public class TNonblockingSSLSocket extends TNonblockingSocket implements SocketAddressProvider { |
| 36 | + |
| 37 | + private static final Logger LOGGER = |
| 38 | + LoggerFactory.getLogger(TNonblockingSSLSocket.class.getName()); |
| 39 | + |
| 40 | + private final SSLEngine sslEngine_; |
| 41 | + |
| 42 | + private final ByteBuffer appUnwrap; |
| 43 | + private final ByteBuffer netUnwrap; |
| 44 | + |
| 45 | + private final ByteBuffer appWrap; |
| 46 | + private final ByteBuffer netWrap; |
| 47 | + |
| 48 | + private ByteBuffer decodedBytes; |
| 49 | + |
| 50 | + private boolean isHandshakeCompleted; |
| 51 | + |
| 52 | + private SelectionKey selectionKey; |
| 53 | + |
| 54 | + protected TNonblockingSSLSocket(String host, int port, int timeout, SSLContext sslContext) |
| 55 | + throws IOException, TTransportException { |
| 56 | + super(host, port, timeout); |
| 57 | + sslEngine_ = sslContext.createSSLEngine(host, port); |
| 58 | + sslEngine_.setUseClientMode(true); |
| 59 | + |
| 60 | + int appBufferSize = sslEngine_.getSession().getApplicationBufferSize(); |
| 61 | + int netBufferSize = sslEngine_.getSession().getPacketBufferSize(); |
| 62 | + appUnwrap = ByteBuffer.allocate(appBufferSize); |
| 63 | + netUnwrap = ByteBuffer.allocate(netBufferSize); |
| 64 | + appWrap = ByteBuffer.allocate(appBufferSize); |
| 65 | + netWrap = ByteBuffer.allocate(netBufferSize); |
| 66 | + decodedBytes = ByteBuffer.allocate(appBufferSize); |
| 67 | + decodedBytes.flip(); |
| 68 | + isHandshakeCompleted = false; |
| 69 | + } |
| 70 | + |
| 71 | + /** {@inheritDoc} */ |
| 72 | + @Override |
| 73 | + public SelectionKey registerSelector(Selector selector, int interests) throws IOException { |
| 74 | + selectionKey = super.registerSelector(selector, interests); |
| 75 | + return selectionKey; |
| 76 | + } |
| 77 | + |
| 78 | + /** {@inheritDoc} */ |
| 79 | + @Override |
| 80 | + public boolean isOpen() { |
| 81 | + // isConnected() does not return false after close(), but isOpen() does |
| 82 | + return super.isOpen() && isHandshakeCompleted; |
| 83 | + } |
| 84 | + |
| 85 | + /** {@inheritDoc} */ |
| 86 | + @Override |
| 87 | + public void open() throws TTransportException { |
| 88 | + throw new RuntimeException("open() is not implemented for TNonblockingSSLSocket"); |
| 89 | + } |
| 90 | + |
| 91 | + /** {@inheritDoc} */ |
| 92 | + @Override |
| 93 | + public synchronized int read(ByteBuffer buffer) throws TTransportException { |
| 94 | + int numBytes = buffer.limit(); |
| 95 | + while (decodedBytes.remaining() < numBytes) { |
| 96 | + try { |
| 97 | + if (doUnwrap() == -1) { |
| 98 | + throw new IOException("Unable to read " + numBytes + " bytes"); |
| 99 | + } |
| 100 | + } catch (IOException exc) { |
| 101 | + throw new TTransportException(TTransportException.UNKNOWN, exc.getMessage()); |
| 102 | + } |
| 103 | + if (appUnwrap.position() > 0) { |
| 104 | + int t; |
| 105 | + appUnwrap.flip(); |
| 106 | + if (decodedBytes.position() > 0) decodedBytes.flip(); |
| 107 | + t = appUnwrap.limit() + decodedBytes.limit(); |
| 108 | + byte[] tmpBuffer = new byte[t]; |
| 109 | + decodedBytes.get(tmpBuffer, 0, decodedBytes.remaining()); |
| 110 | + appUnwrap.get(tmpBuffer, 0, appUnwrap.remaining()); |
| 111 | + if (appUnwrap.position() > 0) { |
| 112 | + appUnwrap.clear(); |
| 113 | + appUnwrap.flip(); |
| 114 | + appUnwrap.compact(); |
| 115 | + } |
| 116 | + decodedBytes = ByteBuffer.wrap(tmpBuffer); |
| 117 | + } |
| 118 | + } |
| 119 | + byte[] b = new byte[numBytes]; |
| 120 | + decodedBytes.get(b, 0, numBytes); |
| 121 | + if (decodedBytes.position() > 0) { |
| 122 | + decodedBytes.compact(); |
| 123 | + decodedBytes.flip(); |
| 124 | + } |
| 125 | + buffer.put(b); |
| 126 | + selectionKey.interestOps(SelectionKey.OP_WRITE); |
| 127 | + return numBytes; |
| 128 | + } |
| 129 | + |
| 130 | + /** {@inheritDoc} */ |
| 131 | + @Override |
| 132 | + public synchronized int write(ByteBuffer buffer) throws TTransportException { |
| 133 | + int numBytes = 0; |
| 134 | + |
| 135 | + if (buffer.position() > 0) buffer.flip(); |
| 136 | + |
| 137 | + int nTransfer; |
| 138 | + int num; |
| 139 | + while (buffer.remaining() != 0) { |
| 140 | + nTransfer = Math.min(appWrap.remaining(), buffer.remaining()); |
| 141 | + if (nTransfer > 0) { |
| 142 | + appWrap.put(buffer.array(), buffer.arrayOffset() + buffer.position(), nTransfer); |
| 143 | + buffer.position(buffer.position() + nTransfer); |
| 144 | + } |
| 145 | + |
| 146 | + try { |
| 147 | + num = doWrap(); |
| 148 | + } catch (IOException iox) { |
| 149 | + throw new TTransportException(TTransportException.UNKNOWN, iox); |
| 150 | + } |
| 151 | + if (num < 0) { |
| 152 | + LOGGER.error("Failed while writing. Probably server is down"); |
| 153 | + return -1; |
| 154 | + } |
| 155 | + numBytes += num; |
| 156 | + } |
| 157 | + return numBytes; |
| 158 | + } |
| 159 | + |
| 160 | + /** {@inheritDoc} */ |
| 161 | + @Override |
| 162 | + public void close() { |
| 163 | + sslEngine_.closeOutbound(); |
| 164 | + super.close(); |
| 165 | + } |
| 166 | + |
| 167 | + /** {@inheritDoc} */ |
| 168 | + @Override |
| 169 | + public boolean startConnect() throws IOException { |
| 170 | + if (this.isOpen()) { |
| 171 | + return true; |
| 172 | + } |
| 173 | + sslEngine_.beginHandshake(); |
| 174 | + return super.startConnect() && doHandShake(); |
| 175 | + } |
| 176 | + |
| 177 | + /** {@inheritDoc} */ |
| 178 | + @Override |
| 179 | + public boolean finishConnect() throws IOException { |
| 180 | + return super.finishConnect() && doHandShake(); |
| 181 | + } |
| 182 | + |
| 183 | + private synchronized boolean doHandShake() throws IOException { |
| 184 | + LOGGER.debug("Handshake is started"); |
| 185 | + while (true) { |
| 186 | + HandshakeStatus hs = sslEngine_.getHandshakeStatus(); |
| 187 | + switch (hs) { |
| 188 | + case NEED_UNWRAP: |
| 189 | + if (doUnwrap() == -1) { |
| 190 | + LOGGER.error("Unexpected. Handshake failed abruptly during unwrap"); |
| 191 | + return false; |
| 192 | + } |
| 193 | + break; |
| 194 | + case NEED_WRAP: |
| 195 | + if (doWrap() == -1) { |
| 196 | + LOGGER.error("Unexpected. Handshake failed abruptly during wrap"); |
| 197 | + return false; |
| 198 | + } |
| 199 | + break; |
| 200 | + case NEED_TASK: |
| 201 | + if (!doTask()) { |
| 202 | + LOGGER.error("Unexpected. Handshake failed abruptly during task"); |
| 203 | + return false; |
| 204 | + } |
| 205 | + break; |
| 206 | + case FINISHED: |
| 207 | + case NOT_HANDSHAKING: |
| 208 | + isHandshakeCompleted = true; |
| 209 | + return true; |
| 210 | + default: |
| 211 | + LOGGER.error("Unknown handshake status. Handshake failed"); |
| 212 | + return false; |
| 213 | + } |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + private synchronized boolean doTask() { |
| 218 | + Runnable runnable; |
| 219 | + while ((runnable = sslEngine_.getDelegatedTask()) != null) { |
| 220 | + runnable.run(); |
| 221 | + } |
| 222 | + HandshakeStatus hs = sslEngine_.getHandshakeStatus(); |
| 223 | + return hs != HandshakeStatus.NEED_TASK; |
| 224 | + } |
| 225 | + |
| 226 | + private synchronized int doUnwrap() throws IOException { |
| 227 | + int num = getSocketChannel().read(netUnwrap); |
| 228 | + if (num < 0) { |
| 229 | + LOGGER.error("Failed during read operation. Probably server is down"); |
| 230 | + return -1; |
| 231 | + } |
| 232 | + SSLEngineResult unwrapResult; |
| 233 | + |
| 234 | + try { |
| 235 | + netUnwrap.flip(); |
| 236 | + unwrapResult = sslEngine_.unwrap(netUnwrap, appUnwrap); |
| 237 | + netUnwrap.compact(); |
| 238 | + } catch (SSLException ex) { |
| 239 | + LOGGER.error(ex.getMessage()); |
| 240 | + throw ex; |
| 241 | + } |
| 242 | + |
| 243 | + switch (unwrapResult.getStatus()) { |
| 244 | + case OK: |
| 245 | + if (appUnwrap.position() > 0) { |
| 246 | + appUnwrap.flip(); |
| 247 | + appUnwrap.compact(); |
| 248 | + } |
| 249 | + break; |
| 250 | + case CLOSED: |
| 251 | + return -1; |
| 252 | + case BUFFER_OVERFLOW: |
| 253 | + throw new IllegalStateException("Failed to unwrap"); |
| 254 | + case BUFFER_UNDERFLOW: |
| 255 | + break; |
| 256 | + } |
| 257 | + return num; |
| 258 | + } |
| 259 | + |
| 260 | + private synchronized int doWrap() throws IOException { |
| 261 | + int num = 0; |
| 262 | + SSLEngineResult wrapResult; |
| 263 | + try { |
| 264 | + appWrap.flip(); |
| 265 | + wrapResult = sslEngine_.wrap(appWrap, netWrap); |
| 266 | + appWrap.compact(); |
| 267 | + } catch (SSLException exc) { |
| 268 | + LOGGER.error(exc.getMessage()); |
| 269 | + throw exc; |
| 270 | + } |
| 271 | + |
| 272 | + switch (wrapResult.getStatus()) { |
| 273 | + case OK: |
| 274 | + if (netWrap.position() > 0) { |
| 275 | + netWrap.flip(); |
| 276 | + num = getSocketChannel().write(netWrap); |
| 277 | + netWrap.compact(); |
| 278 | + } |
| 279 | + break; |
| 280 | + case BUFFER_UNDERFLOW: |
| 281 | + // try again later |
| 282 | + break; |
| 283 | + case BUFFER_OVERFLOW: |
| 284 | + throw new IllegalStateException("Failed to wrap"); |
| 285 | + case CLOSED: |
| 286 | + LOGGER.error("SSL session is closed"); |
| 287 | + return -1; |
| 288 | + } |
| 289 | + return num; |
| 290 | + } |
| 291 | +} |
0 commit comments