1 /*
   2  * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.net.ssl;
  27 
  28 import java.nio.ByteBuffer;
  29 import java.nio.ReadOnlyBufferException;
  30 import java.util.List;
  31 import java.util.function.BiFunction;
  32 
  33 
  34 /**
  35  * A class which enables secure communications using protocols such as
  36  * the Secure Sockets Layer (SSL) or
  37  * <A HREF="http://www.ietf.org/rfc/rfc2246.txt"> IETF RFC 2246 "Transport
  38  * Layer Security" (TLS) </A> protocols, but is transport independent.
  39  * <P>
  40  * The secure communications modes include: <UL>
  41  *
  42  *      <LI> <em>Integrity Protection</em>.  SSL/TLS/DTLS protects against
  43  *      modification of messages by an active wiretapper.
  44  *
  45  *      <LI> <em>Authentication</em>.  In most modes, SSL/TLS/DTLS provides
  46  *      peer authentication.  Servers are usually authenticated, and
  47  *      clients may be authenticated as requested by servers.
  48  *
  49  *      <LI> <em>Confidentiality (Privacy Protection)</em>.  In most
  50  *      modes, SSL/TLS/DTLS encrypts data being sent between client and
  51  *      server.  This protects the confidentiality of data, so that
  52  *      passive wiretappers won't see sensitive data such as financial
  53  *      information or personal information of many kinds.
  54  *
  55  *      </UL>
  56  *
  57  * These kinds of protection are specified by a "cipher suite", which
  58  * is a combination of cryptographic algorithms used by a given SSL
  59  * connection.  During the negotiation process, the two endpoints must
  60  * agree on a cipher suite that is available in both environments.  If
  61  * there is no such suite in common, no SSL connection can be
  62  * established, and no data can be exchanged.
  63  * <P>
  64  * The cipher suite used is established by a negotiation process called
  65  * "handshaking".  The goal of this process is to create or rejoin a
  66  * "session", which may protect many connections over time.  After
  67  * handshaking has completed, you can access session attributes by
  68  * using the {@link #getSession()} method.
  69  * <P>
  70  * The {@code SSLSocket} class provides much of the same security
  71  * functionality, but all of the inbound and outbound data is
  72  * automatically transported using the underlying {@link
  73  * java.net.Socket Socket}, which by design uses a blocking model.
  74  * While this is appropriate for many applications, this model does not
  75  * provide the scalability required by large servers.
  76  * <P>
  77  * The primary distinction of an {@code SSLEngine} is that it
  78  * operates on inbound and outbound byte streams, independent of the
  79  * transport mechanism.  It is the responsibility of the
  80  * {@code SSLEngine} user to arrange for reliable I/O transport to
  81  * the peer.  By separating the SSL/TLS/DTLS abstraction from the I/O
  82  * transport mechanism, the {@code SSLEngine} can be used for a
  83  * wide variety of I/O types, such as {@link
  84  * java.nio.channels.spi.AbstractSelectableChannel#configureBlocking(boolean)
  85  * non-blocking I/O (polling)}, {@link java.nio.channels.Selector
  86  * selectable non-blocking I/O}, {@link java.net.Socket Socket} and the
  87  * traditional Input/OutputStreams, local {@link java.nio.ByteBuffer
  88  * ByteBuffers} or byte arrays, <A
  89  * HREF="http://www.jcp.org/en/jsr/detail?id=203"> future asynchronous
  90  * I/O models </A>, and so on.
  91  * <P>
  92  * At a high level, the {@code SSLEngine} appears thus:
  93  *
  94  * <pre>
  95  *                   app data
  96  *
  97  *                |           ^
  98  *                |     |     |
  99  *                v     |     |
 100  *           +----+-----|-----+----+
 101  *           |          |          |
 102  *           |       SSL|Engine    |
 103  *   wrap()  |          |          |  unwrap()
 104  *           | OUTBOUND | INBOUND  |
 105  *           |          |          |
 106  *           +----+-----|-----+----+
 107  *                |     |     ^
 108  *                |     |     |
 109  *                v           |
 110  *
 111  *                   net data
 112  * </pre>
 113  * Application data (also known as plaintext or cleartext) is data which
 114  * is produced or consumed by an application.  Its counterpart is
 115  * network data, which consists of either handshaking and/or ciphertext
 116  * (encrypted) data, and destined to be transported via an I/O
 117  * mechanism.  Inbound data is data which has been received from the
 118  * peer, and outbound data is destined for the peer.
 119  * <P>
 120  * (In the context of an {@code SSLEngine}, the term "handshake
 121  * data" is taken to mean any data exchanged to establish and control a
 122  * secure connection.  Handshake data includes the SSL/TLS/DTLS messages
 123  * "alert", "change_cipher_spec," and "handshake.")
 124  * <P>
 125  * There are five distinct phases to an {@code SSLEngine}.
 126  *
 127  * <OL>
 128  *     <li> Creation - The {@code SSLEngine} has been created and
 129  *     initialized, but has not yet been used.  During this phase, an
 130  *     application may set any {@code SSLEngine}-specific settings
 131  *     (enabled cipher suites, whether the {@code SSLEngine} should
 132  *     handshake in client or server mode, and so on).  Once
 133  *     handshaking has begun, though, any new settings (except
 134  *     client/server mode, see below) will be used for
 135  *     the next handshake.
 136  *
 137  *     <li> Initial Handshake - The initial handshake is a procedure by
 138  *     which the two peers exchange communication parameters until an
 139  *     SSLSession is established.  Application data can not be sent during
 140  *     this phase.
 141  *
 142  *     <li> Application Data - Once the communication parameters have
 143  *     been established and the handshake is complete, application data
 144  *     may flow through the {@code SSLEngine}.  Outbound
 145  *     application messages are encrypted and integrity protected,
 146  *     and inbound messages reverse the process.
 147  *
 148  *     <li> Rehandshaking - Either side may request a renegotiation of
 149  *     the session at any time during the Application Data phase.  New
 150  *     handshaking data can be intermixed among the application data.
 151  *     Before starting the rehandshake phase, the application may
 152  *     reset the SSL/TLS/DTLS communication parameters such as the list of
 153  *     enabled ciphersuites and whether to use client authentication,
 154  *     but can not change between client/server modes.  As before, once
 155  *     handshaking has begun, any new {@code SSLEngine}
 156  *     configuration settings will not be used until the next
 157  *     handshake.
 158  *
 159  *     <li> Closure - When the connection is no longer needed, the client
 160  *     and the server applications should each close both sides of their
 161  *     respective connections.  For {@code SSLEngine} objects, an
 162  *     application should call {@link SSLEngine#closeOutbound()} and
 163  *     send any remaining messages to the peer.  Likewise, an application
 164  *     should receive any remaining messages from the peer before calling
 165  *     {@link SSLEngine#closeInbound()}.  The underlying transport mechanism
 166  *     can then be closed after both sides of the {@code SSLEngine} have
 167  *     been closed.  If the connection is not closed in an orderly manner
 168  *     (for example {@link SSLEngine#closeInbound()} is called before the
 169  *     peer's write closure notification has been received), exceptions
 170  *     will be raised to indicate that an error has occurred.  Once an
 171  *     engine is closed, it is not reusable: a new {@code SSLEngine}
 172  *     must be created.
 173  * </OL>
 174  * An {@code SSLEngine} is created by calling {@link
 175  * SSLContext#createSSLEngine()} from an initialized
 176  * {@code SSLContext}.  Any configuration
 177  * parameters should be set before making the first call to
 178  * {@code wrap()}, {@code unwrap()}, or
 179  * {@code beginHandshake()}.  These methods all trigger the
 180  * initial handshake.
 181  * <P>
 182  * Data moves through the engine by calling {@link #wrap(ByteBuffer,
 183  * ByteBuffer) wrap()} or {@link #unwrap(ByteBuffer, ByteBuffer)
 184  * unwrap()} on outbound or inbound data, respectively.  Depending on
 185  * the state of the {@code SSLEngine}, a {@code wrap()} call
 186  * may consume application data from the source buffer and may produce
 187  * network data in the destination buffer.  The outbound data
 188  * may contain application and/or handshake data.  A call to
 189  * {@code unwrap()} will examine the source buffer and may
 190  * advance the handshake if the data is handshaking information, or
 191  * may place application data in the destination buffer if the data
 192  * is application.  The state of the underlying SSL/TLS/DTLS algorithm
 193  * will determine when data is consumed and produced.
 194  * <P>
 195  * Calls to {@code wrap()} and {@code unwrap()} return an
 196  * {@code SSLEngineResult} which indicates the status of the
 197  * operation, and (optionally) how to interact with the engine to make
 198  * progress.
 199  * <P>
 200  * The {@code SSLEngine} produces/consumes complete SSL/TLS/DTLS
 201  * packets only, and does not store application data internally between
 202  * calls to {@code wrap()/unwrap()}.  Thus input and output
 203  * {@code ByteBuffer}s must be sized appropriately to hold the
 204  * maximum record that can be produced.  Calls to {@link
 205  * SSLSession#getPacketBufferSize()} and {@link
 206  * SSLSession#getApplicationBufferSize()} should be used to determine
 207  * the appropriate buffer sizes.  The size of the outbound application
 208  * data buffer generally does not matter.  If buffer conditions do not
 209  * allow for the proper consumption/production of data, the application
 210  * must determine (via {@link SSLEngineResult}) and correct the
 211  * problem, and then try the call again.
 212  * <P>
 213  * For example, {@code unwrap()} will return a {@link
 214  * SSLEngineResult.Status#BUFFER_OVERFLOW} result if the engine
 215  * determines that there is not enough destination buffer space available.
 216  * Applications should call {@link SSLSession#getApplicationBufferSize()}
 217  * and compare that value with the space available in the destination buffer,
 218  * enlarging the buffer if necessary.  Similarly, if {@code unwrap()}
 219  * were to return a {@link SSLEngineResult.Status#BUFFER_UNDERFLOW}, the
 220  * application should call {@link SSLSession#getPacketBufferSize()} to ensure
 221  * that the source buffer has enough room to hold a record (enlarging if
 222  * necessary), and then obtain more inbound data.
 223  *
 224  * <pre>{@code
 225  *   SSLEngineResult r = engine.unwrap(src, dst);
 226  *   switch (r.getStatus()) {
 227  *   BUFFER_OVERFLOW:
 228  *       // Could attempt to drain the dst buffer of any already obtained
 229  *       // data, but we'll just increase it to the size needed.
 230  *       int appSize = engine.getSession().getApplicationBufferSize();
 231  *       ByteBuffer b = ByteBuffer.allocate(appSize + dst.position());
 232  *       dst.flip();
 233  *       b.put(dst);
 234  *       dst = b;
 235  *       // retry the operation.
 236  *       break;
 237  *   BUFFER_UNDERFLOW:
 238  *       int netSize = engine.getSession().getPacketBufferSize();
 239  *       // Resize buffer if needed.
 240  *       if (netSize > src.capacity()) {
 241  *           ByteBuffer b = ByteBuffer.allocate(netSize);
 242  *           src.flip();
 243  *           b.put(src);
 244  *           src = b;
 245  *       }
 246  *       // Obtain more inbound network data for src,
 247  *       // then retry the operation.
 248  *       break;
 249  *   // other cases: CLOSED, OK.
 250  *   }
 251  * }</pre>
 252  *
 253  * <P>
 254  * Unlike {@code SSLSocket}, all methods of SSLEngine are
 255  * non-blocking.  {@code SSLEngine} implementations may
 256  * require the results of tasks that may take an extended period of
 257  * time to complete, or may even block.  For example, a TrustManager
 258  * may need to connect to a remote certificate validation service,
 259  * or a KeyManager might need to prompt a user to determine which
 260  * certificate to use as part of client authentication.  Additionally,
 261  * creating cryptographic signatures and verifying them can be slow,
 262  * seemingly blocking.
 263  * <P>
 264  * For any operation which may potentially block, the
 265  * {@code SSLEngine} will create a {@link java.lang.Runnable}
 266  * delegated task.  When {@code SSLEngineResult} indicates that a
 267  * delegated task result is needed, the application must call {@link
 268  * #getDelegatedTask()} to obtain an outstanding delegated task and
 269  * call its {@link java.lang.Runnable#run() run()} method (possibly using
 270  * a different thread depending on the compute strategy).  The
 271  * application should continue obtaining delegated tasks until no more
 272  * exist, and try the original operation again.
 273  * <P>
 274  * At the end of a communication session, applications should properly
 275  * close the SSL/TLS/DTLS link.  The SSL/TLS/DTLS protocols have closure
 276  * handshake messages, and these messages should be communicated to the
 277  * peer before releasing the {@code SSLEngine} and closing the
 278  * underlying transport mechanism.  A close can be initiated by one of:
 279  * an SSLException, an inbound closure handshake message, or one of the
 280  * close methods.  In all cases, closure handshake messages are
 281  * generated by the engine, and {@code wrap()} should be repeatedly
 282  * called until the resulting {@code SSLEngineResult}'s status
 283  * returns "CLOSED", or {@link #isOutboundDone()} returns true.  All
 284  * data obtained from the {@code wrap()} method should be sent to the
 285  * peer.
 286  * <P>
 287  * {@link #closeOutbound()} is used to signal the engine that the
 288  * application will not be sending any more data.
 289  * <P>
 290  * A peer will signal its intent to close by sending its own closure
 291  * handshake message.  After this message has been received and
 292  * processed by the local {@code SSLEngine}'s {@code unwrap()}
 293  * call, the application can detect the close by calling
 294  * {@code unwrap()} and looking for a {@code SSLEngineResult}
 295  * with status "CLOSED", or if {@link #isInboundDone()} returns true.
 296  * If for some reason the peer closes the communication link without
 297  * sending the proper SSL/TLS/DTLS closure message, the application can
 298  * detect the end-of-stream and can signal the engine via {@link
 299  * #closeInbound()} that there will no more inbound messages to
 300  * process.  Some applications might choose to require orderly shutdown
 301  * messages from a peer, in which case they can check that the closure
 302  * was generated by a handshake message and not by an end-of-stream
 303  * condition.
 304  * <P>
 305  * There are two groups of cipher suites which you will need to know
 306  * about when managing cipher suites:
 307  *
 308  * <UL>
 309  *      <LI> <em>Supported</em> cipher suites:  all the suites which are
 310  *      supported by the SSL implementation.  This list is reported
 311  *      using {@link #getSupportedCipherSuites()}.
 312  *
 313  *      <LI> <em>Enabled</em> cipher suites, which may be fewer than
 314  *      the full set of supported suites.  This group is set using the
 315  *      {@link #setEnabledCipherSuites(String [])} method, and
 316  *      queried using the {@link #getEnabledCipherSuites()} method.
 317  *      Initially, a default set of cipher suites will be enabled on a
 318  *      new engine that represents the minimum suggested
 319  *      configuration.
 320  * </UL>
 321  *
 322  * Implementation defaults require that only cipher suites which
 323  * authenticate servers and provide confidentiality be enabled by
 324  * default.  Only if both sides explicitly agree to unauthenticated
 325  * and/or non-private (unencrypted) communications will such a
 326  * cipher suite be selected.
 327  * <P>
 328  * Each SSL/TLS/DTLS connection must have one client and one server, thus
 329  * each endpoint must decide which role to assume.  This choice determines
 330  * who begins the handshaking process as well as which type of messages
 331  * should be sent by each party.  The method {@link
 332  * #setUseClientMode(boolean)} configures the mode.  Once the initial
 333  * handshaking has started, an {@code SSLEngine} can not switch
 334  * between client and server modes, even when performing renegotiations.
 335  * <P>
 336  * Applications might choose to process delegated tasks in different
 337  * threads.  When an {@code SSLEngine}
 338  * is created, the current {@link java.security.AccessControlContext}
 339  * is saved.  All future delegated tasks will be processed using this
 340  * context:  that is, all access control decisions will be made using the
 341  * context captured at engine creation.
 342  *
 343  * <HR>
 344  *
 345  * <B>Concurrency Notes</B>:
 346  * There are two concurrency issues to be aware of:
 347  *
 348  * <OL>
 349  *      <li>The {@code wrap()} and {@code unwrap()} methods
 350  *      may execute concurrently of each other.
 351  *
 352  *      <li> The SSL/TLS/DTLS protocols employ ordered packets.
 353  *      Applications must take care to ensure that generated packets
 354  *      are delivered in sequence.  If packets arrive
 355  *      out-of-order, unexpected or fatal results may occur.
 356  * <P>
 357  *      For example:
 358  *
 359  *      <pre>
 360  *              synchronized (outboundLock) {
 361  *                  sslEngine.wrap(src, dst);
 362  *                  outboundQueue.put(dst);
 363  *              }
 364  *      </pre>
 365  *
 366  *      As a corollary, two threads must not attempt to call the same method
 367  *      (either {@code wrap()} or {@code unwrap()}) concurrently,
 368  *      because there is no way to guarantee the eventual packet ordering.
 369  * </OL>
 370  *
 371  * @see SSLContext
 372  * @see SSLSocket
 373  * @see SSLServerSocket
 374  * @see SSLSession
 375  * @see java.net.Socket
 376  *
 377  * @since 1.5
 378  * @author Brad R. Wetmore
 379  */
 380 
 381 public abstract class SSLEngine {
 382 
 383     private String peerHost = null;
 384     private int peerPort = -1;
 385 
 386     /**
 387      * Constructor for an {@code SSLEngine} providing no hints
 388      * for an internal session reuse strategy.
 389      *
 390      * @see     SSLContext#createSSLEngine()
 391      * @see     SSLSessionContext
 392      */
 393     protected SSLEngine() {
 394     }
 395 
 396     /**
 397      * Constructor for an {@code SSLEngine}.
 398      * <P>
 399      * {@code SSLEngine} implementations may use the
 400      * {@code peerHost} and {@code peerPort} parameters as hints
 401      * for their internal session reuse strategy.
 402      * <P>
 403      * Some cipher suites (such as Kerberos) require remote hostname
 404      * information. Implementations of this class should use this
 405      * constructor to use Kerberos.
 406      * <P>
 407      * The parameters are not authenticated by the
 408      * {@code SSLEngine}.
 409      *
 410      * @param   peerHost the name of the peer host
 411      * @param   peerPort the port number of the peer
 412      * @see     SSLContext#createSSLEngine(String, int)
 413      * @see     SSLSessionContext
 414      */
 415     protected SSLEngine(String peerHost, int peerPort) {
 416         this.peerHost = peerHost;
 417         this.peerPort = peerPort;
 418     }
 419 
 420     /**
 421      * Returns the host name of the peer.
 422      * <P>
 423      * Note that the value is not authenticated, and should not be
 424      * relied upon.
 425      *
 426      * @return  the host name of the peer, or null if nothing is
 427      *          available.
 428      */
 429     public String getPeerHost() {
 430         return peerHost;
 431     }
 432 
 433     /**
 434      * Returns the port number of the peer.
 435      * <P>
 436      * Note that the value is not authenticated, and should not be
 437      * relied upon.
 438      *
 439      * @return  the port number of the peer, or -1 if nothing is
 440      *          available.
 441      */
 442     public int getPeerPort() {
 443         return peerPort;
 444     }
 445 
 446     /**
 447      * Attempts to encode a buffer of plaintext application data into
 448      * SSL/TLS/DTLS network data.
 449      * <P>
 450      * An invocation of this method behaves in exactly the same manner
 451      * as the invocation:
 452      * <blockquote><pre>
 453      * {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
 454      *     engine.wrap(new ByteBuffer [] { src }, 0, 1, dst);}
 455      * </pre></blockquote>
 456      *
 457      * @param   src
 458      *          a {@code ByteBuffer} containing outbound application data
 459      * @param   dst
 460      *          a {@code ByteBuffer} to hold outbound network data
 461      * @return  an {@code SSLEngineResult} describing the result
 462      *          of this operation.
 463      * @throws  SSLException
 464      *          A problem was encountered while processing the
 465      *          data that caused the {@code SSLEngine} to abort.
 466      *          See the class description for more information on
 467      *          engine closure.
 468      * @throws  ReadOnlyBufferException
 469      *          if the {@code dst} buffer is read-only.
 470      * @throws  IllegalArgumentException
 471      *          if either {@code src} or {@code dst}
 472      *          is null.
 473      * @throws  IllegalStateException if the client/server mode
 474      *          has not yet been set.
 475      * @see     #wrap(ByteBuffer [], int, int, ByteBuffer)
 476      */
 477     public SSLEngineResult wrap(ByteBuffer src,
 478             ByteBuffer dst) throws SSLException {
 479         return wrap(new ByteBuffer [] { src }, 0, 1, dst);
 480     }
 481 
 482     /**
 483      * Attempts to encode plaintext bytes from a sequence of data
 484      * buffers into SSL/TLS/DTLS network data.
 485      * <P>
 486      * An invocation of this method behaves in exactly the same manner
 487      * as the invocation:
 488      * <blockquote><pre>
 489      * {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
 490      *     engine.wrap(srcs, 0, srcs.length, dst);}
 491      * </pre></blockquote>
 492      *
 493      * @param   srcs
 494      *          an array of {@code ByteBuffers} containing the
 495      *          outbound application data
 496      * @param   dst
 497      *          a {@code ByteBuffer} to hold outbound network data
 498      * @return  an {@code SSLEngineResult} describing the result
 499      *          of this operation.
 500      * @throws  SSLException
 501      *          A problem was encountered while processing the
 502      *          data that caused the {@code SSLEngine} to abort.
 503      *          See the class description for more information on
 504      *          engine closure.
 505      * @throws  ReadOnlyBufferException
 506      *          if the {@code dst} buffer is read-only.
 507      * @throws  IllegalArgumentException
 508      *          if either {@code srcs} or {@code dst}
 509      *          is null, or if any element in {@code srcs} is null.
 510      * @throws  IllegalStateException if the client/server mode
 511      *          has not yet been set.
 512      * @see     #wrap(ByteBuffer [], int, int, ByteBuffer)
 513      */
 514     public SSLEngineResult wrap(ByteBuffer [] srcs,
 515             ByteBuffer dst) throws SSLException {
 516         if (srcs == null) {
 517             throw new IllegalArgumentException("src == null");
 518         }
 519         return wrap(srcs, 0, srcs.length, dst);
 520     }
 521 
 522 
 523     /**
 524      * Attempts to encode plaintext bytes from a subsequence of data
 525      * buffers into SSL/TLS/DTLS network data.  This <i>"gathering"</i>
 526      * operation encodes, in a single invocation, a sequence of bytes
 527      * from one or more of a given sequence of buffers.  Gathering
 528      * wraps are often useful when implementing network protocols or
 529      * file formats that, for example, group data into segments
 530      * consisting of one or more fixed-length headers followed by a
 531      * variable-length body.  See
 532      * {@link java.nio.channels.GatheringByteChannel} for more
 533      * information on gathering, and {@link
 534      * java.nio.channels.GatheringByteChannel#write(ByteBuffer[],
 535      * int, int)} for more information on the subsequence
 536      * behavior.
 537      * <P>
 538      * Depending on the state of the SSLEngine, this method may produce
 539      * network data without consuming any application data (for example,
 540      * it may generate handshake data.)
 541      * <P>
 542      * The application is responsible for reliably transporting the
 543      * network data to the peer, and for ensuring that data created by
 544      * multiple calls to wrap() is transported in the same order in which
 545      * it was generated.  The application must properly synchronize
 546      * multiple calls to this method.
 547      * <P>
 548      * If this {@code SSLEngine} has not yet started its initial
 549      * handshake, this method will automatically start the handshake.
 550      * <P>
 551      * This method will attempt to produce SSL/TLS/DTLS records, and will
 552      * consume as much source data as possible, but will never consume
 553      * more than the sum of the bytes remaining in each buffer.  Each
 554      * {@code ByteBuffer}'s position is updated to reflect the
 555      * amount of data consumed or produced.  The limits remain the
 556      * same.
 557      * <P>
 558      * The underlying memory used by the {@code srcs} and
 559      * {@code dst ByteBuffer}s must not be the same.
 560      * <P>
 561      * See the class description for more information on engine closure.
 562      *
 563      * @param   srcs
 564      *          an array of {@code ByteBuffers} containing the
 565      *          outbound application data
 566      * @param   offset
 567      *          The offset within the buffer array of the first buffer from
 568      *          which bytes are to be retrieved; it must be non-negative
 569      *          and no larger than {@code srcs.length}
 570      * @param   length
 571      *          The maximum number of buffers to be accessed; it must be
 572      *          non-negative and no larger than
 573      *          {@code srcs.length}&nbsp;-&nbsp;{@code offset}
 574      * @param   dst
 575      *          a {@code ByteBuffer} to hold outbound network data
 576      * @return  an {@code SSLEngineResult} describing the result
 577      *          of this operation.
 578      * @throws  SSLException
 579      *          A problem was encountered while processing the
 580      *          data that caused the {@code SSLEngine} to abort.
 581      *          See the class description for more information on
 582      *          engine closure.
 583      * @throws  IndexOutOfBoundsException
 584      *          if the preconditions on the {@code offset} and
 585      *          {@code length} parameters do not hold.
 586      * @throws  ReadOnlyBufferException
 587      *          if the {@code dst} buffer is read-only.
 588      * @throws  IllegalArgumentException
 589      *          if either {@code srcs} or {@code dst}
 590      *          is null, or if any element in the {@code srcs}
 591      *          subsequence specified is null.
 592      * @throws  IllegalStateException if the client/server mode
 593      *          has not yet been set.
 594      * @see     java.nio.channels.GatheringByteChannel
 595      * @see     java.nio.channels.GatheringByteChannel#write(
 596      *              ByteBuffer[], int, int)
 597      */
 598     public abstract SSLEngineResult wrap(ByteBuffer [] srcs, int offset,
 599             int length, ByteBuffer dst) throws SSLException;
 600 
 601     /**
 602      * Attempts to decode SSL/TLS/DTLS network data into a plaintext
 603      * application data buffer.
 604      * <P>
 605      * An invocation of this method behaves in exactly the same manner
 606      * as the invocation:
 607      * <blockquote><pre>
 608      * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
 609      *     engine.unwrap(src, new ByteBuffer [] { dst }, 0, 1);}
 610      * </pre></blockquote>
 611      *
 612      * @param   src
 613      *          a {@code ByteBuffer} containing inbound network data.
 614      * @param   dst
 615      *          a {@code ByteBuffer} to hold inbound application data.
 616      * @return  an {@code SSLEngineResult} describing the result
 617      *          of this operation.
 618      * @throws  SSLException
 619      *          A problem was encountered while processing the
 620      *          data that caused the {@code SSLEngine} to abort.
 621      *          See the class description for more information on
 622      *          engine closure.
 623      * @throws  ReadOnlyBufferException
 624      *          if the {@code dst} buffer is read-only.
 625      * @throws  IllegalArgumentException
 626      *          if either {@code src} or {@code dst}
 627      *          is null.
 628      * @throws  IllegalStateException if the client/server mode
 629      *          has not yet been set.
 630      * @see     #unwrap(ByteBuffer, ByteBuffer [], int, int)
 631      */
 632     public SSLEngineResult unwrap(ByteBuffer src,
 633             ByteBuffer dst) throws SSLException {
 634         return unwrap(src, new ByteBuffer [] { dst }, 0, 1);
 635     }
 636 
 637     /**
 638      * Attempts to decode SSL/TLS/DTLS network data into a sequence of plaintext
 639      * application data buffers.
 640      * <P>
 641      * An invocation of this method behaves in exactly the same manner
 642      * as the invocation:
 643      * <blockquote><pre>
 644      * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
 645      *     engine.unwrap(src, dsts, 0, dsts.length);}
 646      * </pre></blockquote>
 647      *
 648      * @param   src
 649      *          a {@code ByteBuffer} containing inbound network data.
 650      * @param   dsts
 651      *          an array of {@code ByteBuffer}s to hold inbound
 652      *          application data.
 653      * @return  an {@code SSLEngineResult} describing the result
 654      *          of this operation.
 655      * @throws  SSLException
 656      *          A problem was encountered while processing the
 657      *          data that caused the {@code SSLEngine} to abort.
 658      *          See the class description for more information on
 659      *          engine closure.
 660      * @throws  ReadOnlyBufferException
 661      *          if any of the {@code dst} buffers are read-only.
 662      * @throws  IllegalArgumentException
 663      *          if either {@code src} or {@code dsts}
 664      *          is null, or if any element in {@code dsts} is null.
 665      * @throws  IllegalStateException if the client/server mode
 666      *          has not yet been set.
 667      * @see     #unwrap(ByteBuffer, ByteBuffer [], int, int)
 668      */
 669     public SSLEngineResult unwrap(ByteBuffer src,
 670             ByteBuffer [] dsts) throws SSLException {
 671         if (dsts == null) {
 672             throw new IllegalArgumentException("dsts == null");
 673         }
 674         return unwrap(src, dsts, 0, dsts.length);
 675     }
 676 
 677     /**
 678      * Attempts to decode SSL/TLS/DTLS network data into a subsequence of
 679      * plaintext application data buffers.  This <i>"scattering"</i>
 680      * operation decodes, in a single invocation, a sequence of bytes
 681      * into one or more of a given sequence of buffers.  Scattering
 682      * unwraps are often useful when implementing network protocols or
 683      * file formats that, for example, group data into segments
 684      * consisting of one or more fixed-length headers followed by a
 685      * variable-length body.  See
 686      * {@link java.nio.channels.ScatteringByteChannel} for more
 687      * information on scattering, and {@link
 688      * java.nio.channels.ScatteringByteChannel#read(ByteBuffer[],
 689      * int, int)} for more information on the subsequence
 690      * behavior.
 691      * <P>
 692      * Depending on the state of the SSLEngine, this method may consume
 693      * network data without producing any application data (for example,
 694      * it may consume handshake data.)
 695      * <P>
 696      * The application is responsible for reliably obtaining the network
 697      * data from the peer, and for invoking unwrap() on the data in the
 698      * order it was received.  The application must properly synchronize
 699      * multiple calls to this method.
 700      * <P>
 701      * If this {@code SSLEngine} has not yet started its initial
 702      * handshake, this method will automatically start the handshake.
 703      * <P>
 704      * This method will attempt to consume one complete SSL/TLS/DTLS network
 705      * packet, but will never consume more than the sum of the bytes
 706      * remaining in the buffers.  Each {@code ByteBuffer}'s
 707      * position is updated to reflect the amount of data consumed or
 708      * produced.  The limits remain the same.
 709      * <P>
 710      * The underlying memory used by the {@code src} and
 711      * {@code dsts ByteBuffer}s must not be the same.
 712      * <P>
 713      * The inbound network buffer may be modified as a result of this
 714      * call:  therefore if the network data packet is required for some
 715      * secondary purpose, the data should be duplicated before calling this
 716      * method.  Note:  the network data will not be useful to a second
 717      * SSLEngine, as each SSLEngine contains unique random state which
 718      * influences the SSL/TLS/DTLS messages.
 719      * <P>
 720      * See the class description for more information on engine closure.
 721      *
 722      * @param   src
 723      *          a {@code ByteBuffer} containing inbound network data.
 724      * @param   dsts
 725      *          an array of {@code ByteBuffer}s to hold inbound
 726      *          application data.
 727      * @param   offset
 728      *          The offset within the buffer array of the first buffer from
 729      *          which bytes are to be transferred; it must be non-negative
 730      *          and no larger than {@code dsts.length}.
 731      * @param   length
 732      *          The maximum number of buffers to be accessed; it must be
 733      *          non-negative and no larger than
 734      *          {@code dsts.length}&nbsp;-&nbsp;{@code offset}.
 735      * @return  an {@code SSLEngineResult} describing the result
 736      *          of this operation.
 737      * @throws  SSLException
 738      *          A problem was encountered while processing the
 739      *          data that caused the {@code SSLEngine} to abort.
 740      *          See the class description for more information on
 741      *          engine closure.
 742      * @throws  IndexOutOfBoundsException
 743      *          If the preconditions on the {@code offset} and
 744      *          {@code length} parameters do not hold.
 745      * @throws  ReadOnlyBufferException
 746      *          if any of the {@code dst} buffers are read-only.
 747      * @throws  IllegalArgumentException
 748      *          if either {@code src} or {@code dsts}
 749      *          is null, or if any element in the {@code dsts}
 750      *          subsequence specified is null.
 751      * @throws  IllegalStateException if the client/server mode
 752      *          has not yet been set.
 753      * @see     java.nio.channels.ScatteringByteChannel
 754      * @see     java.nio.channels.ScatteringByteChannel#read(
 755      *              ByteBuffer[], int, int)
 756      */
 757     public abstract SSLEngineResult unwrap(ByteBuffer src,
 758             ByteBuffer [] dsts, int offset, int length) throws SSLException;
 759 
 760 
 761     /**
 762      * Returns a delegated {@code Runnable} task for
 763      * this {@code SSLEngine}.
 764      * <P>
 765      * {@code SSLEngine} operations may require the results of
 766      * operations that block, or may take an extended period of time to
 767      * complete.  This method is used to obtain an outstanding {@link
 768      * java.lang.Runnable} operation (task).  Each task must be assigned
 769      * a thread (possibly the current) to perform the {@link
 770      * java.lang.Runnable#run() run} operation.  Once the
 771      * {@code run} method returns, the {@code Runnable} object
 772      * is no longer needed and may be discarded.
 773      * <P>
 774      * Delegated tasks run in the {@code AccessControlContext}
 775      * in place when this object was created.
 776      * <P>
 777      * A call to this method will return each outstanding task
 778      * exactly once.
 779      * <P>
 780      * Multiple delegated tasks can be run in parallel.
 781      *
 782      * @return  a delegated {@code Runnable} task, or null
 783      *          if none are available.
 784      */
 785     public abstract Runnable getDelegatedTask();
 786 
 787 
 788     /**
 789      * Signals that no more inbound network data will be sent
 790      * to this {@code SSLEngine}.
 791      * <P>
 792      * If the application initiated the closing process by calling
 793      * {@link #closeOutbound()}, under some circumstances it is not
 794      * required that the initiator wait for the peer's corresponding
 795      * close message.  (See section 7.2.1 of the TLS specification (<A
 796      * HREF="http://www.ietf.org/rfc/rfc2246.txt">RFC 2246</A>) for more
 797      * information on waiting for closure alerts.)  In such cases, this
 798      * method need not be called.
 799      * <P>
 800      * But if the application did not initiate the closure process, or
 801      * if the circumstances above do not apply, this method should be
 802      * called whenever the end of the SSL/TLS/DTLS data stream is reached.
 803      * This ensures closure of the inbound side, and checks that the
 804      * peer followed the SSL/TLS/DTLS close procedure properly, thus
 805      * detecting possible truncation attacks.
 806      * <P>
 807      * This method is idempotent:  if the inbound side has already
 808      * been closed, this method does not do anything.
 809      * <P>
 810      * {@link #wrap(ByteBuffer, ByteBuffer) wrap()} should be
 811      * called to flush any remaining handshake data.
 812      *
 813      * @throws  SSLException
 814      *          if this engine has not received the proper SSL/TLS/DTLS close
 815      *          notification message from the peer.
 816      *
 817      * @see     #isInboundDone()
 818      * @see     #isOutboundDone()
 819      */
 820     public abstract void closeInbound() throws SSLException;
 821 
 822 
 823     /**
 824      * Returns whether {@link #unwrap(ByteBuffer, ByteBuffer)} will
 825      * accept any more inbound data messages.
 826      *
 827      * @return  true if the {@code SSLEngine} will not
 828      *          consume anymore network data (and by implication,
 829      *          will not produce any more application data.)
 830      * @see     #closeInbound()
 831      */
 832     public abstract boolean isInboundDone();
 833 
 834 
 835     /**
 836      * Signals that no more outbound application data will be sent
 837      * on this {@code SSLEngine}.
 838      * <P>
 839      * This method is idempotent:  if the outbound side has already
 840      * been closed, this method does not do anything.
 841      * <P>
 842      * {@link #wrap(ByteBuffer, ByteBuffer)} should be
 843      * called to flush any remaining handshake data.
 844      *
 845      * @see     #isOutboundDone()
 846      */
 847     public abstract void closeOutbound();
 848 
 849 
 850     /**
 851      * Returns whether {@link #wrap(ByteBuffer, ByteBuffer)} will
 852      * produce any more outbound data messages.
 853      * <P>
 854      * Note that during the closure phase, a {@code SSLEngine} may
 855      * generate handshake closure data that must be sent to the peer.
 856      * {@code wrap()} must be called to generate this data.  When
 857      * this method returns true, no more outbound data will be created.
 858      *
 859      * @return  true if the {@code SSLEngine} will not produce
 860      *          any more network data
 861      *
 862      * @see     #closeOutbound()
 863      * @see     #closeInbound()
 864      */
 865     public abstract boolean isOutboundDone();
 866 
 867 
 868     /**
 869      * Returns the names of the cipher suites which could be enabled for use
 870      * on this engine.  Normally, only a subset of these will actually
 871      * be enabled by default, since this list may include cipher suites which
 872      * do not meet quality of service requirements for those defaults.  Such
 873      * cipher suites might be useful in specialized applications.
 874      * <P>
 875      * The returned array includes cipher suites from the list of standard
 876      * cipher suite names in the <a href=
 877      * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names">
 878      * JSSE Cipher Suite Names</a> section of the Java Cryptography
 879      * Architecture Standard Algorithm Name Documentation, and may also
 880      * include other cipher suites that the provider supports.
 881      *
 882      * @return  an array of cipher suite names
 883      * @see     #getEnabledCipherSuites()
 884      * @see     #setEnabledCipherSuites(String [])
 885      */
 886     public abstract String [] getSupportedCipherSuites();
 887 
 888 
 889     /**
 890      * Returns the names of the SSL cipher suites which are currently
 891      * enabled for use on this engine.  When an SSLEngine is first
 892      * created, all enabled cipher suites support a minimum quality of
 893      * service.  Thus, in some environments this value might be empty.
 894      * <P>
 895      * Note that even if a suite is enabled, it may never be used. This
 896      * can occur if the peer does not support it, or its use is restricted,
 897      * or the requisite certificates (and private keys) for the suite are
 898      * not available, or an anonymous suite is enabled but authentication
 899      * is required.
 900      * <P>
 901      * The returned array includes cipher suites from the list of standard
 902      * cipher suite names in the <a href=
 903      * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names">
 904      * JSSE Cipher Suite Names</a> section of the Java Cryptography
 905      * Architecture Standard Algorithm Name Documentation, and may also
 906      * include other cipher suites that the provider supports.
 907      *
 908      * @return  an array of cipher suite names
 909      * @see     #getSupportedCipherSuites()
 910      * @see     #setEnabledCipherSuites(String [])
 911      */
 912     public abstract String [] getEnabledCipherSuites();
 913 
 914 
 915     /**
 916      * Sets the cipher suites enabled for use on this engine.
 917      * <P>
 918      * Each cipher suite in the {@code suites} parameter must have
 919      * been listed by getSupportedCipherSuites(), or the method will
 920      * fail.  Following a successful call to this method, only suites
 921      * listed in the {@code suites} parameter are enabled for use.
 922      * <P>
 923      * Note that the standard list of cipher suite names may be found in the
 924      * <a href=
 925      * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names">
 926      * JSSE Cipher Suite Names</a> section of the Java Cryptography
 927      * Architecture Standard Algorithm Name Documentation.  Providers
 928      * may support cipher suite names not found in this list or might not
 929      * use the recommended name for a certain cipher suite.
 930      * <P>
 931      * See {@link #getEnabledCipherSuites()} for more information
 932      * on why a specific cipher suite may never be used on a engine.
 933      *
 934      * @param   suites Names of all the cipher suites to enable
 935      * @throws  IllegalArgumentException when one or more of the ciphers
 936      *          named by the parameter is not supported, or when the
 937      *          parameter is null.
 938      * @see     #getSupportedCipherSuites()
 939      * @see     #getEnabledCipherSuites()
 940      */
 941     public abstract void setEnabledCipherSuites(String[] suites);
 942 
 943 
 944     /**
 945      * Returns the names of the protocols which could be enabled for use
 946      * with this {@code SSLEngine}.
 947      *
 948      * @return  an array of protocols supported
 949      */
 950     public abstract String [] getSupportedProtocols();
 951 
 952 
 953     /**
 954      * Returns the names of the protocol versions which are currently
 955      * enabled for use with this {@code SSLEngine}.
 956      * <P>
 957      * Note that even if a protocol is enabled, it may never be used.
 958      * This can occur if the peer does not support the protocol, or its
 959      * use is restricted, or there are no enabled cipher suites supported
 960      * by the protocol.
 961      *
 962      * @return  an array of protocols
 963      * @see     #setEnabledProtocols(String [])
 964      */
 965     public abstract String [] getEnabledProtocols();
 966 
 967 
 968     /**
 969      * Set the protocol versions enabled for use on this engine.
 970      * <P>
 971      * The protocols must have been listed by getSupportedProtocols()
 972      * as being supported.  Following a successful call to this method,
 973      * only protocols listed in the {@code protocols} parameter
 974      * are enabled for use.
 975      *
 976      * @param   protocols Names of all the protocols to enable.
 977      * @throws  IllegalArgumentException when one or more of
 978      *          the protocols named by the parameter is not supported or
 979      *          when the protocols parameter is null.
 980      * @see     #getEnabledProtocols()
 981      */
 982     public abstract void setEnabledProtocols(String[] protocols);
 983 
 984 
 985     /**
 986      * Returns the {@code SSLSession} in use in this
 987      * {@code SSLEngine}.
 988      * <P>
 989      * These can be long lived, and frequently correspond to an entire
 990      * login session for some user.  The session specifies a particular
 991      * cipher suite which is being actively used by all connections in
 992      * that session, as well as the identities of the session's client
 993      * and server.
 994      * <P>
 995      * Unlike {@link SSLSocket#getSession()}
 996      * this method does not block until handshaking is complete.
 997      * <P>
 998      * Until the initial handshake has completed, this method returns
 999      * a session object which reports an invalid cipher suite of
1000      * "SSL_NULL_WITH_NULL_NULL".
1001      *
1002      * @return  the {@code SSLSession} for this {@code SSLEngine}
1003      * @see     SSLSession
1004      */
1005     public abstract SSLSession getSession();
1006 
1007 
1008     /**
1009      * Returns the {@code SSLSession} being constructed during a SSL/TLS/DTLS
1010      * handshake.
1011      * <p>
1012      * TLS/DTLS protocols may negotiate parameters that are needed when using
1013      * an instance of this class, but before the {@code SSLSession} has
1014      * been completely initialized and made available via {@code getSession}.
1015      * For example, the list of valid signature algorithms may restrict
1016      * the type of certificates that can used during TrustManager
1017      * decisions, or the maximum TLS/DTLS fragment packet sizes can be
1018      * resized to better support the network environment.
1019      * <p>
1020      * This method provides early access to the {@code SSLSession} being
1021      * constructed.  Depending on how far the handshake has progressed,
1022      * some data may not yet be available for use.  For example, if a
1023      * remote server will be sending a Certificate chain, but that chain
1024      * has yet not been processed, the {@code getPeerCertificates}
1025      * method of {@code SSLSession} will throw a
1026      * SSLPeerUnverifiedException.  Once that chain has been processed,
1027      * {@code getPeerCertificates} will return the proper value.
1028      *
1029      * @see SSLSocket
1030      * @see SSLSession
1031      * @see ExtendedSSLSession
1032      * @see X509ExtendedKeyManager
1033      * @see X509ExtendedTrustManager
1034      *
1035      * @return null if this instance is not currently handshaking, or
1036      *         if the current handshake has not progressed far enough to
1037      *         create a basic SSLSession.  Otherwise, this method returns the
1038      *         {@code SSLSession} currently being negotiated.
1039      * @throws UnsupportedOperationException if the underlying provider
1040      *         does not implement the operation.
1041      *
1042      * @since 1.7
1043      */
1044     public SSLSession getHandshakeSession() {
1045         throw new UnsupportedOperationException();
1046     }
1047 
1048 
1049     /**
1050      * Initiates handshaking (initial or renegotiation) on this SSLEngine.
1051      * <P>
1052      * This method is not needed for the initial handshake, as the
1053      * {@code wrap()} and {@code unwrap()} methods will
1054      * implicitly call this method if handshaking has not already begun.
1055      * <P>
1056      * Note that the peer may also request a session renegotiation with
1057      * this {@code SSLEngine} by sending the appropriate
1058      * session renegotiate handshake message.
1059      * <P>
1060      * Unlike the {@link SSLSocket#startHandshake()
1061      * SSLSocket#startHandshake()} method, this method does not block
1062      * until handshaking is completed.
1063      * <P>
1064      * To force a complete SSL/TLS/DTLS session renegotiation, the current
1065      * session should be invalidated prior to calling this method.
1066      * <P>
1067      * Some protocols may not support multiple handshakes on an existing
1068      * engine and may throw an {@code SSLException}.
1069      *
1070      * @throws  SSLException
1071      *          if a problem was encountered while signaling the
1072      *          {@code SSLEngine} to begin a new handshake.
1073      *          See the class description for more information on
1074      *          engine closure.
1075      * @throws  IllegalStateException if the client/server mode
1076      *          has not yet been set.
1077      * @see     SSLSession#invalidate()
1078      */
1079     public abstract void beginHandshake() throws SSLException;
1080 
1081 
1082     /**
1083      * Returns the current handshake status for this {@code SSLEngine}.
1084      *
1085      * @return  the current {@code SSLEngineResult.HandshakeStatus}.
1086      */
1087     public abstract SSLEngineResult.HandshakeStatus getHandshakeStatus();
1088 
1089 
1090     /**
1091      * Configures the engine to use client (or server) mode when
1092      * handshaking.
1093      * <P>
1094      * This method must be called before any handshaking occurs.
1095      * Once handshaking has begun, the mode can not be reset for the
1096      * life of this engine.
1097      * <P>
1098      * Servers normally authenticate themselves, and clients
1099      * are not required to do so.
1100      *
1101      * @param   mode true if the engine should start its handshaking
1102      *          in "client" mode
1103      * @throws  IllegalArgumentException if a mode change is attempted
1104      *          after the initial handshake has begun.
1105      * @see     #getUseClientMode()
1106      */
1107     public abstract void setUseClientMode(boolean mode);
1108 
1109 
1110     /**
1111      * Returns true if the engine is set to use client mode when
1112      * handshaking.
1113      *
1114      * @return  true if the engine should do handshaking
1115      *          in "client" mode
1116      * @see     #setUseClientMode(boolean)
1117      */
1118     public abstract boolean getUseClientMode();
1119 
1120 
1121     /**
1122      * Configures the engine to <i>require</i> client authentication.  This
1123      * option is only useful for engines in the server mode.
1124      * <P>
1125      * An engine's client authentication setting is one of the following:
1126      * <ul>
1127      * <li> client authentication required
1128      * <li> client authentication requested
1129      * <li> no client authentication desired
1130      * </ul>
1131      * <P>
1132      * Unlike {@link #setWantClientAuth(boolean)}, if this option is set and
1133      * the client chooses not to provide authentication information
1134      * about itself, <i>the negotiations will stop and the engine will
1135      * begin its closure procedure</i>.
1136      * <P>
1137      * Calling this method overrides any previous setting made by
1138      * this method or {@link #setWantClientAuth(boolean)}.
1139      *
1140      * @param   need set to true if client authentication is required,
1141      *          or false if no client authentication is desired.
1142      * @see     #getNeedClientAuth()
1143      * @see     #setWantClientAuth(boolean)
1144      * @see     #getWantClientAuth()
1145      * @see     #setUseClientMode(boolean)
1146      */
1147     public abstract void setNeedClientAuth(boolean need);
1148 
1149 
1150     /**
1151      * Returns true if the engine will <i>require</i> client authentication.
1152      * This option is only useful to engines in the server mode.
1153      *
1154      * @return  true if client authentication is required,
1155      *          or false if no client authentication is desired.
1156      * @see     #setNeedClientAuth(boolean)
1157      * @see     #setWantClientAuth(boolean)
1158      * @see     #getWantClientAuth()
1159      * @see     #setUseClientMode(boolean)
1160      */
1161     public abstract boolean getNeedClientAuth();
1162 
1163 
1164     /**
1165      * Configures the engine to <i>request</i> client authentication.
1166      * This option is only useful for engines in the server mode.
1167      * <P>
1168      * An engine's client authentication setting is one of the following:
1169      * <ul>
1170      * <li> client authentication required
1171      * <li> client authentication requested
1172      * <li> no client authentication desired
1173      * </ul>
1174      * <P>
1175      * Unlike {@link #setNeedClientAuth(boolean)}, if this option is set and
1176      * the client chooses not to provide authentication information
1177      * about itself, <i>the negotiations will continue</i>.
1178      * <P>
1179      * Calling this method overrides any previous setting made by
1180      * this method or {@link #setNeedClientAuth(boolean)}.
1181      *
1182      * @param   want set to true if client authentication is requested,
1183      *          or false if no client authentication is desired.
1184      * @see     #getWantClientAuth()
1185      * @see     #setNeedClientAuth(boolean)
1186      * @see     #getNeedClientAuth()
1187      * @see     #setUseClientMode(boolean)
1188      */
1189     public abstract void setWantClientAuth(boolean want);
1190 
1191 
1192     /**
1193      * Returns true if the engine will <i>request</i> client authentication.
1194      * This option is only useful for engines in the server mode.
1195      *
1196      * @return  true if client authentication is requested,
1197      *          or false if no client authentication is desired.
1198      * @see     #setNeedClientAuth(boolean)
1199      * @see     #getNeedClientAuth()
1200      * @see     #setWantClientAuth(boolean)
1201      * @see     #setUseClientMode(boolean)
1202      */
1203     public abstract boolean getWantClientAuth();
1204 
1205 
1206     /**
1207      * Controls whether new SSL sessions may be established by this engine.
1208      * If session creations are not allowed, and there are no
1209      * existing sessions to resume, there will be no successful
1210      * handshaking.
1211      *
1212      * @param   flag true indicates that sessions may be created; this
1213      *          is the default.  false indicates that an existing session
1214      *          must be resumed
1215      * @see     #getEnableSessionCreation()
1216      */
1217     public abstract void setEnableSessionCreation(boolean flag);
1218 
1219 
1220     /**
1221      * Returns true if new SSL sessions may be established by this engine.
1222      *
1223      * @return  true indicates that sessions may be created; this
1224      *          is the default.  false indicates that an existing session
1225      *          must be resumed
1226      * @see     #setEnableSessionCreation(boolean)
1227      */
1228     public abstract boolean getEnableSessionCreation();
1229 
1230     /**
1231      * Returns the SSLParameters in effect for this SSLEngine.
1232      * The ciphersuites and protocols of the returned SSLParameters
1233      * are always non-null.
1234      *
1235      * @return the SSLParameters in effect for this SSLEngine.
1236      * @since 1.6
1237      */
1238     public SSLParameters getSSLParameters() {
1239         SSLParameters params = new SSLParameters();
1240         params.setCipherSuites(getEnabledCipherSuites());
1241         params.setProtocols(getEnabledProtocols());
1242         if (getNeedClientAuth()) {
1243             params.setNeedClientAuth(true);
1244         } else if (getWantClientAuth()) {
1245             params.setWantClientAuth(true);
1246         }
1247         return params;
1248     }
1249 
1250     /**
1251      * Applies SSLParameters to this engine.
1252      *
1253      * <p>This means:
1254      * <ul>
1255      * <li>If {@code params.getCipherSuites()} is non-null,
1256      *   {@code setEnabledCipherSuites()} is called with that value.</li>
1257      * <li>If {@code params.getProtocols()} is non-null,
1258      *   {@code setEnabledProtocols()} is called with that value.</li>
1259      * <li>If {@code params.getNeedClientAuth()} or
1260      *   {@code params.getWantClientAuth()} return {@code true},
1261      *   {@code setNeedClientAuth(true)} and
1262      *   {@code setWantClientAuth(true)} are called, respectively;
1263      *   otherwise {@code setWantClientAuth(false)} is called.</li>
1264      * <li>If {@code params.getServerNames()} is non-null, the engine will
1265      *   configure its server names with that value.</li>
1266      * <li>If {@code params.getSNIMatchers()} is non-null, the engine will
1267      *   configure its SNI matchers with that value.</li>
1268      * </ul>
1269      *
1270      * @param params the parameters
1271      * @throws IllegalArgumentException if the setEnabledCipherSuites() or
1272      *    the setEnabledProtocols() call fails
1273      * @since 1.6
1274      */
1275     public void setSSLParameters(SSLParameters params) {
1276         String[] s;
1277         s = params.getCipherSuites();
1278         if (s != null) {
1279             setEnabledCipherSuites(s);
1280         }
1281         s = params.getProtocols();
1282         if (s != null) {
1283             setEnabledProtocols(s);
1284         }
1285         if (params.getNeedClientAuth()) {
1286             setNeedClientAuth(true);
1287         } else if (params.getWantClientAuth()) {
1288             setWantClientAuth(true);
1289         } else {
1290             setWantClientAuth(false);
1291         }
1292     }
1293 
1294     /**
1295      * Returns the most recent application protocol value negotiated for this
1296      * connection.
1297      * <p>
1298      * If supported by the underlying SSL/TLS/DTLS implementation,
1299      * application name negotiation mechanisms such as <a
1300      * href="http://www.ietf.org/rfc/rfc7301.txt"> RFC 7301 </a>, the
1301      * Application-Layer Protocol Negotiation (ALPN), can negotiate
1302      * application-level values between peers.
1303      *
1304      * @implSpec
1305      * The implementation in this class throws
1306      * {@code UnsupportedOperationException} and performs no other action.
1307      *
1308      * @return null if it has not yet been determined if application
1309      *         protocols might be used for this connection, an empty
1310      *         {@code String} if application protocols values will not
1311      *         be used, or a non-empty application protocol {@code String}
1312      *         if a value was successfully negotiated.
1313      * @throws UnsupportedOperationException if the underlying provider
1314      *         does not implement the operation.
1315      * @since 9
1316      */
1317     public String getApplicationProtocol() {
1318         throw new UnsupportedOperationException();
1319     }
1320 
1321     /**
1322      * Returns the application protocol value negotiated on a SSL/TLS
1323      * handshake currently in progress.
1324      * <p>
1325      * Like {@link #getHandshakeSession()},
1326      * a connection may be in the middle of a handshake. The
1327      * application protocol may or may not yet be available.
1328      *
1329      * @implSpec
1330      * The implementation in this class throws
1331      * {@code UnsupportedOperationException} and performs no other action.
1332      *
1333      * @return null if it has not yet been determined if application
1334      *         protocols might be used for this handshake, an empty
1335      *         {@code String} if application protocols values will not
1336      *         be used, or a non-empty application protocol {@code String}
1337      *         if a value was successfully negotiated.
1338      * @throws UnsupportedOperationException if the underlying provider
1339      *         does not implement the operation.
1340      * @since 9
1341      */
1342     public String getHandshakeApplicationProtocol() {
1343         throw new UnsupportedOperationException();
1344     }
1345 
1346     /**
1347      * Registers a callback function that selects an application protocol
1348      * value for a SSL/TLS/DTLS handshake.
1349      * The function overrides any values supplied using
1350      * {@link SSLParameters#setApplicationProtocols
1351      * SSLParameters.setApplicationProtocols} and it supports the following
1352      * type parameters:
1353      * <blockquote>
1354      * <dl>
1355      * <dt> {@code SSLEngine}
1356      * <dd> The function's first argument allows the current {@code SSLEngine}
1357      *      to be inspected, including the handshake session and configuration
1358      *      settings.
1359      * <dt> {@code List<String>}
1360      * <dd> The function's second argument lists the application protocol names
1361      *      advertised by the TLS peer.
1362      * <dt> {@code String}
1363      * <dd> The function's result is an application protocol name, or null to
1364      *      indicate that none of the advertised names are acceptable.
1365      *      If the return value is an empty {@code String} then application
1366      *      protocol indications will not be used.
1367      *      If the return value is null (no value chosen) or is a value that
1368      *      was not advertised by the peer, the underlying protocol will
1369      *      determine what action to take. (For example, ALPN will send a
1370      *      "no_application_protocol" alert and terminate the connection.)
1371      * </dl>
1372      * </blockquote>
1373      *
1374      * For example, the following call registers a callback function that
1375      * examines the TLS handshake parameters and selects an application protocol
1376      * name:
1377      * <pre>{@code
1378      *     serverEngine.setHandshakeApplicationProtocolSelector(
1379      *         (serverEngine, clientProtocols) -> {
1380      *             SSLSession session = serverEngine.getHandshakeSession();
1381      *             return chooseApplicationProtocol(
1382      *                 serverEngine,
1383      *                 clientProtocols,
1384      *                 session.getProtocol(),
1385      *                 session.getCipherSuite());
1386      *         });
1387      * }</pre>
1388      *
1389      * @apiNote
1390      * This method should be called by TLS server applications before the TLS
1391      * handshake begins. Also, this {@code SSLEngine} should be configured with
1392      * parameters that are compatible with the application protocol selected by
1393      * the callback function. For example, enabling a poor choice of cipher
1394      * suites could result in no suitable application protocol.
1395      * See {@link SSLParameters}.
1396      *
1397      * @implSpec
1398      * The implementation in this class throws
1399      * {@code UnsupportedOperationException} and performs no other action.
1400      *
1401      * @param selector the callback function, or null to disable the callback
1402      *         functionality.
1403      * @throws UnsupportedOperationException if the underlying provider
1404      *         does not implement the operation.
1405      * @since 9
1406      */
1407     public void setHandshakeApplicationProtocolSelector(
1408             BiFunction<SSLEngine, List<String>, String> selector) {
1409         throw new UnsupportedOperationException();
1410     }
1411 
1412     /**
1413      * Retrieves the callback function that selects an application protocol
1414      * value during a SSL/TLS/DTLS handshake.
1415      * See {@link #setHandshakeApplicationProtocolSelector
1416      * setHandshakeApplicationProtocolSelector}
1417      * for the function's type parameters.
1418      *
1419      * @implSpec
1420      * The implementation in this class throws
1421      * {@code UnsupportedOperationException} and performs no other action.
1422      *
1423      * @return the callback function, or null if none has been set.
1424      * @throws UnsupportedOperationException if the underlying provider
1425      *         does not implement the operation.
1426      * @since 9
1427      */
1428     public BiFunction<SSLEngine, List<String>, String>
1429             getHandshakeApplicationProtocolSelector() {
1430         throw new UnsupportedOperationException();
1431     }
1432 }