282. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 9/25/2018 2:13:26 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

282.1 Files compared

# Location File Last Modified
1 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\sun\security\ssl SSLEngineImpl.java Mon Jan 22 14:46:54 2018 UTC
2 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\sun\security\ssl SSLEngineImpl.java Wed Sep 12 17:54:50 2018 UTC

282.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 4340
Changed 1 2
Inserted 0 0
Removed 0 0

282.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

282.4 Active regular expressions

No regular expressions were active.

282.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 200 3, 2014, O racle and/ or its aff iliates. A ll rights  reserved.
  3    * DO NOT  ALTER OR R EMOVE COPY RIGHT NOTI CES OR THI S FILE HEA DER.
  4    *
  5    * This co de is free  software;  you can r edistribut e it and/o r modify i t
  6    * under t he terms o f the GNU  General Pu blic Licen se version  2 only, a s
  7    * publish ed by the  Free Softw are Founda tion.  Ora cle design ates this
  8    * particu lar file a s subject  to the "Cl asspath" e xception a s provided
  9    * by Orac le in the  LICENSE fi le that ac companied  this code.
  10    *
  11    * This co de is dist ributed in  the hope  that it wi ll be usef ul, but WI THOUT
  12    * ANY WAR RANTY; wit hout even  the implie d warranty  of MERCHA NTABILITY  or
  13    * FITNESS  FOR A PAR TICULAR PU RPOSE.  Se e the GNU  General Pu blic Licen se
  14    * version  2 for mor e details  (a copy is  included  in the LIC ENSE file  that
  15    * accompa nied this  code).
  16    *
  17    * You sho uld have r eceived a  copy of th e GNU Gene ral Public  License v ersion
  18    * 2 along  with this  work; if  not, write  to the Fr ee Softwar e Foundati on,
  19    * Inc., 5 1 Franklin  St, Fifth  Floor, Bo ston, MA 0 2110-1301  USA.
  20    *
  21    * Please  contact Or acle, 500  Oracle Par kway, Redw ood Shores , CA 94065  USA
  22    * or visi t www.orac le.com if  you need a dditional  informatio n or have  any
  23    * questio ns.
  24    */
  25  
  26   package su n.security .ssl;
  27  
  28   import jav a.io.*;
  29   import jav a.nio.*;
  30   import jav a.util.*;
  31   import jav a.security .*;
  32  
  33   import jav ax.crypto. BadPadding Exception;
  34  
  35   import jav ax.net.ssl .*;
  36   import jav ax.net.ssl .SSLEngine Result.*;
  37  
  38   /**
  39    * Impleme ntation of  an non-bl ocking SSL Engine.
  40    *
  41    * *Curren tly*, the  SSLEngine  code exist s in paral lel with t he current
  42    * SSLSock et.  As su ch, the cu rrent impl ementation  is using  legacy cod e
  43    * with ma ny of the  same abstr actions.   However, i t varies i n many
  44    * areas,  most drama tically in  the IO ha ndling.
  45    *
  46    * There a re three m ain I/O th reads that  can be ex isting in  parallel:
  47    * wrap(),  unwrap(),  and begin Handshake( ).  We are  encouragi ng users t o
  48    * not cal l multiple  instances  of wrap o r unwrap,  because th e data cou ld
  49    * appear  to flow ou t of the S SLEngine i n a non-se quential o rder.  We
  50    * take al l steps we  can to at  least mak e sure the  ordering  remains
  51    * consist ent, but o nce the ca lls return s, anythin g can happ en.  For
  52    * example , thread1  and thread 2 both cal l wrap, th read1 gets  the first
  53    * packet,  thread2 g ets the se cond packe t, but thr ead2 gets  control ba ck
  54    * before  thread1, a nd sends t he data.   The receiv ing side w ould see a n
  55    * out-of- order erro r.
  56    *
  57    * Handsha king is st ill done t he same wa y as SSLSo cket using  the norma l
  58    * InputSt ream/Outpu tStream ab stactions.   We creat e
  59    * ClientH andshakers /ServerHan dshakers,  which prod uce/consum e the
  60    * handsha king data.   The tran sfer of th e data is  largely ha ndled by t he
  61    * Handsha keInStream /Handshake OutStreams .  Lastly,  the
  62    * InputRe cord/Outpu tRecords s till have  the same f unctionali ty, except
  63    * that th ey are ove rridden wi th EngineI nputRecord /EngineOut putRecord,
  64    * which p rovide SSL Engine-spe cific func tionality.
  65    *
  66    * Some of  the major  differenc es are:
  67    *
  68    * EngineI nputRecord /EngineOut putRecord/ EngineWrit er:
  69    *
  70    *      In  order to  avoid writ ing whole  new contro l flows fo r
  71    *      ha ndshaking,  and to re use most o f the same  code, we  kept most
  72    *      of  the actua l handshak e code the  same.  As  usual, re ading
  73    *      ha ndshake da ta may tri gger outpu t of more  handshake  data, so
  74    *      wh at we do i s write th is data to  internal  buffers, a nd wait fo r
  75    *      wr ap() to be  called to  give that  data a ri de.
  76    *
  77    *      Al l data is  routed thr ough
  78    *      En gineInputR ecord/Engi neOutputRe cord.  How ever, all  handshake
  79    *      da ta (ct_ale rt/ct_chan ge_cipher_ spec/ct_ha ndshake) a re passed
  80    *      th rough to t he the und erlying In putRecord/ OutputReco rd, and
  81    *      th e data use s the inte rnal buffe rs.
  82    *
  83    *      Ap plication  data is ha ndled slig htly diffe rent, we c opy the da ta
  84    *      di rectly fro m the src  to the dst  buffers,  and do all  operation s
  85    *      on  those buf fers, savi ng the ove rhead of m ultiple co pies.
  86    *
  87    *      In  the case  of an inbo und record , unwrap p asses the  inbound
  88    *      By teBuffer t o the Inpu tRecord.   If the dat a is hands hake data,
  89    *      th e data is  read into  the InputR ecord's in ternal buf fer.  If
  90    *      th e data is  applicatio n data, th e data is  decoded di rectly int o
  91    *      th e dst buff er.
  92    *
  93    *      In  the case  of an outb ound recor d, when th e write to  the
  94    *      "r eal" Outpu tStream's  would norm ally take  place, ins tead we
  95    *      ca ll back up  to the En gineOutput Record's v ersion of
  96    *      wr iteBuffer,  at which  time we ca pture the  resulting  output in  a
  97    *      By teBuffer,  and send t hat back t o the Engi neWriter f or interna l
  98    *      st orage.
  99    *
  100    *      En gineWriter  is respon sible for  "handling"  all outbo und
  101    *      da ta, be it  handshake  or app dat a, and for  returning  the data
  102    *      to  wrap() in  the prope r order.
  103    *
  104    * ClientH andshaker/ ServerHand shaker/Han dshaker:
  105    *      Me thods whic h relied o n SSLSocke t now have  work on e ither
  106    *      SS LSockets o r SSLEngin es.
  107    *
  108    * @author  Brad Wetm ore
  109    */
  110   final publ ic class S SLEngineIm pl extends  SSLEngine  {
  111  
  112       //
  113       // Fie lds and gl obal comme nts
  114       //
  115  
  116       /*
  117        * The re's a sta te machine  associate d with eac h connecti on, which
  118        * amo ng other r oles serve s to negot iate sessi on changes .
  119        *
  120        * - S TART with  constructo r, until t he TCP con nection's  around.
  121        * - H ANDSHAKE p icks sessi on paramet ers before  allowing  traffic.
  122        *           Ther e are many  substates  due to se quencing r equirement s
  123        *           for  handshake  messages.
  124        * - D ATA may be  transmitt ed.
  125        * - R ENEGOTIATE  state all ows concur rent data  and handsh aking
  126        *           traf fic ("same " substate s as HANDS HAKE), and  terminate s
  127        *           in s election o f new sess ion (and c onnection)  parameter s
  128        * - E RROR state  immediate ly precede s abortive  disconnec t.
  129        * - C LOSED when  one side  closes dow n, used to  start the  shutdown
  130        *           proc ess.  SSL  connection  objects a re not reu sed.
  131        *
  132        * Sta te affects  what SSL  record typ es may leg ally be se nt:
  133        *
  134        * - H andshake . .. only in  HANDSHAKE  and RENEG OTIATE sta tes
  135        * - A pp Data .. . only in  DATA and R ENEGOTIATE  states
  136        * - A lert ... i n HANDSHAK E, DATA, R ENEGOTIATE
  137        *
  138        * Re  what may b e received :  same as  what may  be sent, e xcept that
  139        * Han dshakeRequ est handsh aking mess ages can c ome from s ervers eve n
  140        * in  the applic ation data  state, to  request e ntry to RE NEGOTIATE.
  141        *
  142        * The  state mac hine withi n HANDSHAK E and RENE GOTIATE st ates contr ols
  143        * the  pending s ession, no t the conn ection sta te, until  the change
  144        * cip her spec a nd "Finish ed" handsh ake messag es are pro cessed and
  145        * mak e the "new " session  become the  current o ne.
  146        *
  147        * NOT E: details  of the SM s always n eed to be  nailed dow n better.
  148        * The  text abov e illustra tes the co re ideas.
  149        *
  150        *                  +---->-- -----+---- -->------- -->------- +
  151        *                  |             |                           |
  152        *      <-----<     ^             ^  <- ----<                 |
  153        *STAR T>----->HA NDSHAKE>-- --->DATA>- ---->RENEG OTIATE     |
  154        *                  v             v                 v         |
  155        *                  |             |                 |         |
  156        *                  +------- -----+---- ---------- -+         |
  157        *                  |                                         |
  158        *                  v                                         |
  159        *                 ERROR>--- --->-----> CLOSED<--- -----<---- +
  160        *
  161        * ALS O, note th at the the  purpose o f handshak ing (reneg otiation i s
  162        * inc luded) is  to assign  a differen t, and per haps new,  session to
  163        * the  connectio n.  The SS Lv3 spec i s a bit co nfusing on  that new
  164        * pro tocol feat ure.
  165        */
  166       privat e int                   connecti onState;
  167  
  168       privat e static f inal int     cs_START  = 0;
  169       privat e static f inal int     cs_HANDS HAKE = 1;
  170       privat e static f inal int     cs_DATA  = 2;
  171       privat e static f inal int     cs_RENEG OTIATE = 3 ;
  172       privat e static f inal int     cs_ERROR  = 4;
  173       privat e static f inal int     cs_CLOSE D = 6;
  174  
  175       /*
  176        * Onc e we're in  state cs_ CLOSED, we  can conti nue to
  177        * wra p/unwrap u ntil we fi nish sendi ng/receivi ng the mes sages
  178        * for  close_not ify.  Engi neWriter h andles out boundDone.
  179        */
  180       privat e boolean               inboundD one = fals e;
  181  
  182       Engine Writer                  writer;
  183  
  184       /*
  185        * The  authentic ation cont ext holds  all inform ation used  to establ ish
  186        * who  this end  of the con nection is  (certific ate chains , private  keys,
  187        * etc ) and who  is trusted  (e.g. as  CAs or web sites).
  188        */
  189       privat e SSLConte xtImpl       sslConte xt;
  190  
  191       /*
  192        * Thi s connecti on is one  of (potent ially) man y associat ed with
  193        * any  given ses sion.  The  output of  the hands hake proto col is a
  194        * new  session . .. althoug h all the  protocol d escription  talks
  195        * abo ut changin g the ciph er spec (a nd it does  change),  in fact
  196        * tha t's incide ntal since  it's done  by changi ng everyth ing that
  197        * is  associated  with a se ssion at t he same ti me.  (TLS/ IETF may
  198        * cha nge that t o add clie nt authent ication w/ o new key  exchg.)
  199        */
  200       privat e Handshak er                    handshaker ;
  201       privat e SSLSessi onImpl                sess;
  202       privat e volatile  SSLSessio nImpl      handshakeS ession;
  203  
  204  
  205       /*
  206        * Cli ent authen tication b e off, req uested, or  required.
  207        *
  208        * Thi s will be  used by bo th this cl ass and SS LSocket's  variants.
  209        */
  210       static  final byt e            clauth_n one = 0;
  211       static  final byt e            clauth_r equested =  1;
  212       static  final byt e            clauth_r equired =  2;
  213  
  214       /*
  215        * Fla g indicati ng that th e engine h as receive d a Change CipherSpec  message.
  216        */
  217       privat e boolean               received CCS;
  218  
  219       /*
  220        * Fla g indicati ng if the  next recor d we recei ve MUST be  a Finishe d
  221        * mes sage. Temp orarily se t during t he handsha ke to ensu re that
  222        * a c hange ciph er spec me ssage is f ollowed by  a finishe d message.
  223        */
  224       privat e boolean               expectin gFinished;
  225  
  226  
  227       /*
  228        * If  someone tr ies to clo seInbound( ) (say at  End-Of-Str eam)
  229        * our  engine ha ving recei ved a clos e_notify,  we need to
  230        * not ify the ap p that we  may have a  truncatio n attack u nderway.
  231        */
  232       privat e boolean               recvCN;
  233  
  234       /*
  235        * For  improved  diagnostic s, we deta il connect ion closur e
  236        * If  the engine  is closed  (connecti onState >=  cs_ERROR) ,
  237        * clo seReason ! = null ind icates if  the engine  was close d
  238        * bec ause of an  error or  because or  normal sh utdown.
  239        */
  240       privat e SSLExcep tion         closeRea son;
  241  
  242       /*
  243        * Per -connectio n private  state that  doesn't c hange when  the
  244        * ses sion is ch anged.
  245        */
  246       privat e byte                           doClientAu th;
  247       privat e boolean                        enableSess ionCreatio n = true;
  248       Engine InputRecor d                     inputRecor d;
  249       Engine OutputReco rd                    outputReco rd;
  250       privat e AccessCo ntrolConte xt         acc;
  251  
  252       // The  cipher su ites enabl ed for use  on this c onnection.
  253       privat e CipherSu iteList               enabledCip herSuites;
  254  
  255       // the  endpoint  identifica tion proto col
  256       privat e String                         identifica tionProtoc ol = null;
  257  
  258       // The  cryptogra phic algor ithm const raints
  259       privat e Algorith mConstrain ts         algorithmC onstraints  = null;
  260  
  261       // The  server na me indicat ion and ma tchers
  262       List<S NIServerNa me>          serverNa mes =
  263                                          Coll ections.<S NIServerNa me>emptyLi st();
  264       Collec tion<SNIMa tcher>       sniMatch ers =
  265                                          Coll ections.<S NIMatcher> emptyList( );
  266  
  267       // Hav e we been  told wheth er we're c lient or s erver?
  268       privat e boolean                        serverMode Set = fals e;
  269       privat e boolean                        roleIsServ er;
  270  
  271       /*
  272        * The  protocol  versions e nabled for  use on th is connect ion.
  273        *
  274        * Not e: we supp ort a pseu do protoco l called S SLv2Hello  which when
  275        * set  will resu lt in an S SL v2 Hell o being se nt with SS L (version  3.0)
  276        * or  TLS (versi on 3.1, 3. 2, etc.) v ersion inf o.
  277        */
  278       privat e Protocol List         enabledP rotocols;
  279  
  280       /*
  281        * The  SSL versi on associa ted with t his connec tion.
  282        */
  283       privat e Protocol Version      protocol Version =  ProtocolVe rsion.DEFA ULT;
  284  
  285       /*
  286        * Cry pto state  that's rei nitialized  when the  session ch anges.
  287        */
  288       privat e Authenti cator        readAuth enticator,  writeAuth enticator;
  289       privat e CipherBo x            readCiph er, writeC ipher;
  290       // NOT E: compres sion state  would be  saved here
  291  
  292       /*
  293        * sec urity para meters for  secure re negotiatio n.
  294        */
  295       privat e boolean               secureRe negotiatio n;
  296       privat e byte[]                clientVe rifyData;
  297       privat e byte[]                serverVe rifyData;
  298  
  299       /*
  300        * REA D ME * REA D ME * REA D ME * REA D ME * REA D ME * REA D ME *
  301        * IMP ORTANT STU FF TO UNDE RSTANDING  THE SYNCHR ONIZATION  ISSUES.
  302        * REA D ME * REA D ME * REA D ME * REA D ME * REA D ME * REA D ME *
  303        *
  304        * The re are sev eral locks  here.
  305        *
  306        * The  primary l ock is the  per-insta nce lock u sed by
  307        * syn chronized( this) and  the synchr onized met hods.  It  controls a ll
  308        * acc ess to thi ngs such a s the conn ection sta te and var iables whi ch
  309        * aff ect handsh aking.  If  we are in side a syn chronized  method, we
  310        * can  access th e state di rectly, ot herwise, w e must use  the
  311        * syn chronized  equivalent s.
  312        *
  313        * Not e that we  must never  acquire t he <code>t his</code>  lock afte r
  314        * <co de>writeLo ck</code>  or run the  risk of d eadlock.
  315        *
  316        * Gra b some cof fee, and b e careful  with any c ode change s.
  317        */
  318       privat e Object                wrapLock ;
  319       privat e Object                unwrapLo ck;
  320       Object                         writeLoc k;
  321  
  322       /*
  323        * Is  it the fir st applica tion recor d to write ?
  324        */
  325       privat e boolean  isFirstApp OutputReco rd = true;
  326  
  327       /*
  328        * Whe ther local  cipher su ites prefe rence in s erver side  should be
  329        * hon ored durin g handshak ing?
  330        */
  331       privat e boolean  preferLoca lCipherSui tes = fals e;
  332  
  333       /*
  334        * Cla ss and sub class dyna mic debugg ing suppor t
  335        */
  336       privat e static f inal Debug  debug = D ebug.getIn stance("ss l");
  337  
  338       //
  339       // Ini tializatio n/Construc tors
  340       //
  341  
  342       /**
  343        * Con structor f or an SSLE ngine from  SSLContex t, without
  344        * hos t/port hin ts.  This  Engine wil l not be a ble to cac he
  345        * ses sions, but  must rene gotiate ev erything b y hand.
  346        */
  347       SSLEng ineImpl(SS LContextIm pl ctx) {
  348           su per();
  349           in it(ctx);
  350       }
  351  
  352       /**
  353        * Con structor f or an SSLE ngine from  SSLContex t.
  354        */
  355       SSLEng ineImpl(SS LContextIm pl ctx, St ring host,  int port)  {
  356           su per(host,  port);
  357           in it(ctx);
  358       }
  359  
  360       /**
  361        * Ini tializes t he Engine
  362        */
  363       privat e void ini t(SSLConte xtImpl ctx ) {
  364           if  (debug !=  null && D ebug.isOn( "ssl")) {
  365                System.o ut.println ("Using SS LEngineImp l.");
  366           }
  367  
  368           ss lContext =  ctx;
  369           se ss = SSLSe ssionImpl. nullSessio n;
  370           ha ndshakeSes sion = nul l;
  371  
  372           /*
  373            *  State is  cs_START u ntil we in itialize t he handsha ker.
  374            *
  375            *  Apps usin g SSLEngin e are prob ably going  to be ser ver.
  376            *  Somewhat  arbitrary  choice.
  377            * /
  378           ro leIsServer  = true;
  379           co nnectionSt ate = cs_S TART;
  380           re ceivedCCS  = false;
  381  
  382           //  default s erver name  indicatio n
  383           se rverNames  =
  384                Utilitie s.addToSNI ServerName List(serve rNames, ge tPeerHost( ));
  385  
  386           /*
  387            *  default r ead and wr ite side c ipher and  MAC suppor t
  388            *
  389            *  Note:  co mpression  support wo uld go her e too
  390            * /
  391           re adCipher =  CipherBox .NULL;
  392           re adAuthenti cator = MA C.NULL;
  393           wr iteCipher  = CipherBo x.NULL;
  394           wr iteAuthent icator = M AC.NULL;
  395  
  396           //  default s ecurity pa rameters f or secure  renegotiat ion
  397           se cureRenego tiation =  false;
  398           cl ientVerify Data = new  byte[0];
  399           se rverVerify Data = new  byte[0];
  400  
  401           en abledCiphe rSuites =
  402                    sslC ontext.get DefaultCip herSuiteLi st(roleIsS erver);
  403           en abledProto cols =
  404                    sslC ontext.get DefaultPro tocolList( roleIsServ er);
  405  
  406           wr apLock = n ew Object( );
  407           un wrapLock =  new Objec t();
  408           wr iteLock =  new Object ();
  409  
  410           /*
  411            *  Save the  Access Con trol Conte xt.  This  will be us ed later
  412            *  for a cou ple of thi ngs, inclu ding provi ding a con text to
  413            *  run tasks  in, and f or determi ning which  credentia ls
  414            *  to use fo r Subject  based (JAA S) decisio ns
  415            * /
  416           ac c = Access Controller .getContex t();
  417  
  418           /*
  419            *  All outbo und applic ation data  goes thro ugh this O utputRecor d,
  420            *  other dat a goes thr ough their  respectiv e records  created
  421            *  elsewhere .  All inb ound data  goes throu gh this on e
  422            *  input rec ord.
  423            * /
  424           ou tputRecord  =
  425                new Engi neOutputRe cord(Recor d.ct_appli cation_dat a, this);
  426           in putRecord  = new Engi neInputRec ord(this);
  427           in putRecord. enableForm atChecks() ;
  428  
  429           wr iter = new  EngineWri ter();
  430       }
  431  
  432       /**
  433        * Ini tialize th e handshak er object.  This mean s:
  434        *
  435        *  .  if a hands hake is al ready in p rogress (s tate is cs _HANDSHAKE
  436        *     or cs_RENE GOTIATE),  do nothing  and retur n
  437        *
  438        *  .  if the eng ine is alr eady close d, throw a n Exceptio n (interna l error)
  439        *
  440        *  .  otherwise  (cs_START  or cs_DATA ), create  the approp riate hand shaker
  441        *     object and  advance t he connect ion state  (to cs_HAN DSHAKE or
  442        *     cs_RENEGOT IATE, resp ectively).
  443        *
  444        * Thi s method i s called r ight after  a new eng ine is cre ated, when
  445        * sta rting rene gotiation,  or when c hanging cl ient/serve r mode of  the
  446        * eng ine.
  447        */
  448       privat e void ini tHandshake r() {
  449           sw itch (conn ectionStat e) {
  450  
  451           //
  452           //  Starting  a new hand shake.
  453           //
  454           ca se cs_STAR T:
  455           ca se cs_DATA :
  456                break;
  457  
  458           //
  459           //  We're alr eady in th e middle o f a handsh ake.
  460           //
  461           ca se cs_HAND SHAKE:
  462           ca se cs_RENE GOTIATE:
  463                return;
  464  
  465           //
  466           //  Anyone al lowed to c all this r outine is  required t o
  467           //  do so ONL Y if the c onnection  state is r easonable. ..
  468           //
  469           de fault:
  470                throw ne w IllegalS tateExcept ion("Inter nal error" );
  471           }
  472  
  473           //  state is  either cs_ START or c s_DATA
  474           if  (connecti onState ==  cs_START)  {
  475                connecti onState =  cs_HANDSHA KE;
  476           }  else { //  cs_DATA
  477                connecti onState =  cs_RENEGOT IATE;
  478           }
  479           if  (roleIsSe rver) {
  480                handshak er = new S erverHands haker(this , sslConte xt,
  481                         enabledPro tocols, do ClientAuth ,
  482                         protocolVe rsion, con nectionSta te == cs_H ANDSHAKE,
  483                         secureRene gotiation,  clientVer ifyData, s erverVerif yData);
  484                handshak er.setSNIM atchers(sn iMatchers) ;
  485                handshak er.setUseC ipherSuite sOrder(pre ferLocalCi pherSuites );
  486           }  else {
  487                handshak er = new C lientHands haker(this , sslConte xt,
  488                         enabledPro tocols,
  489                         protocolVe rsion, con nectionSta te == cs_H ANDSHAKE,
  490                         secureRene gotiation,  clientVer ifyData, s erverVerif yData);
  491                handshak er.setSNIS erverNames (serverNam es);
  492           }
  493           ha ndshaker.s etEnabledC ipherSuite s(enabledC ipherSuite s);
  494           ha ndshaker.s etEnableSe ssionCreat ion(enable SessionCre ation);
  495       }
  496  
  497       /*
  498        * Rep ort the cu rrent stat us of the  Handshaker
  499        */
  500       privat e Handshak eStatus ge tHSStatus( HandshakeS tatus hss)  {
  501  
  502           if  (hss != n ull) {
  503                return h ss;
  504           }
  505  
  506           sy nchronized  (this) {
  507                if (writ er.hasOutb oundData() ) {
  508                    retu rn Handsha keStatus.N EED_WRAP;
  509                } else i f (handsha ker != nul l) {
  510                    if ( handshaker .taskOutst anding())  {
  511                         return Han dshakeStat us.NEED_TA SK;
  512                    } el se {
  513                         return Han dshakeStat us.NEED_UN WRAP;
  514                    }
  515                } else i f (connect ionState = = cs_CLOSE D) {
  516                    /*
  517                     * S pecial cas e where we 're closin g, but
  518                     * s till need  the close_ notify bef ore we
  519                     * c an officia lly be clo sed.
  520                     *
  521                     * N ote isOutb oundDone i s taken ca re of by
  522                     * h asOutbound Data() abo ve.
  523                     */
  524                    if ( !isInbound Done()) {
  525                         return Han dshakeStat us.NEED_UN WRAP;
  526                    } //  else not  handshakin g
  527                }
  528  
  529                return H andshakeSt atus.NOT_H ANDSHAKING ;
  530           }
  531       }
  532  
  533       synchr onized pri vate void  checkTaskT hrown() th rows SSLEx ception {
  534           if  (handshak er != null ) {
  535                handshak er.checkTh rown();
  536           }
  537       }
  538  
  539       //
  540       // Han dshaking a nd connect ion state  code
  541       //
  542  
  543       /*
  544        * Pro vides "thi s" synchro nization f or connect ion state.
  545        * Oth erwise, yo u can acce ss it dire ctly.
  546        */
  547       synchr onized pri vate int g etConnecti onState()  {
  548           re turn conne ctionState ;
  549       }
  550  
  551       synchr onized pri vate void  setConnect ionState(i nt state)  {
  552           co nnectionSt ate = stat e;
  553       }
  554  
  555       /*
  556        * Get  the Acces s Control  Context.
  557        *
  558        * Use d for a kn own contex t to
  559        * run  tasks in,  and for d etermining  which cre dentials
  560        * to  use for Su bject-base d (JAAS) d ecisions.
  561        */
  562       Access ControlCon text getAc c() {
  563           re turn acc;
  564       }
  565  
  566       /*
  567        * Is  a handshak e currentl y underway ?
  568        */
  569       @Overr ide
  570       public  SSLEngine Result.Han dshakeStat us getHand shakeStatu s() {
  571           re turn getHS Status(nul l);
  572       }
  573  
  574       /*
  575        * Whe n a connec tion finis hes handsh aking by e nabling us e of a new ly
  576        * neg otiated se ssion, eac h end lear ns about i t in two h alves (rea d,
  577        * and  write).   When both  read and w rite ciphe rs have ch anged, and  the
  578        * las t handshak e message  has been r ead, the c onnection  has joined
  579        * (re joined) th e new sess ion.
  580        *
  581        * NOT E:  The SS Lv3 spec i s rather u nclear on  the concep ts here.
  582        * Ses sions don' t change o nce they'r e establis hed (inclu ding ciphe r
  583          * suite an d master  PW      ) but conn ections ca n join the m (and lea ve
  584        * the m).  They' re created  by handsh aking, tho ugh someti me handsha king
  585        * cau ses connec tions to j oin up wit h pre-esta blished se ssions.
  586        *
  587        * Syn chronized  on "this"  from readR ecord.
  588        */
  589       privat e void cha ngeReadCip hers() thr ows SSLExc eption {
  590           if  (connecti onState !=  cs_HANDSH AKE
  591                    && c onnectionS tate != cs _RENEGOTIA TE) {
  592                throw ne w SSLProto colExcepti on(
  593                    "Sta te error,  change cip her specs" );
  594           }
  595  
  596           //  ... creat e decompre ssor
  597  
  598           Ci pherBox ol dCipher =  readCipher ;
  599  
  600           tr y {
  601                readCiph er = hands haker.newR eadCipher( );
  602                readAuth enticator  = handshak er.newRead Authentica tor();
  603           }  catch (Gen eralSecuri tyExceptio n e) {
  604                // "can' t happen"
  605                throw ne w SSLExcep tion("Algo rithm miss ing:  ", e );
  606           }
  607  
  608           /*
  609            *  Dispose o f any inte rmediate s tate in th e underlyi ng cipher.
  610            *  For PKCS1 1 ciphers,  this will  release a ny attache d sessions ,
  611            *  and thus  make final ization fa ster.
  612            *
  613            *  Since MAC 's doFinal () is call ed for eve ry SSL/TLS  packet, i t's
  614            *  not neces sary to do  the same  with MAC's .
  615            * /
  616           ol dCipher.di spose();
  617       }
  618  
  619       /*
  620        * use d by Hands haker to c hange the  active wri te cipher,  follows
  621        * the  output of  the CCS m essage.
  622        *
  623        * Als o synchron ized on "t his" from  readRecord /delegated Task.
  624        */
  625       void c hangeWrite Ciphers()  throws SSL Exception  {
  626           if  (connecti onState !=  cs_HANDSH AKE
  627                    && c onnectionS tate != cs _RENEGOTIA TE) {
  628                throw ne w SSLProto colExcepti on(
  629                    "Sta te error,  change cip her specs" );
  630           }
  631  
  632           //  ... creat e compress or
  633  
  634           Ci pherBox ol dCipher =  writeCiphe r;
  635  
  636           tr y {
  637                writeCip her = hand shaker.new WriteCiphe r();
  638                writeAut henticator  = handsha ker.newWri teAuthenti cator();
  639           }  catch (Gen eralSecuri tyExceptio n e) {
  640                // "can' t happen"
  641                throw ne w SSLExcep tion("Algo rithm miss ing:  ", e );
  642           }
  643  
  644           //  See comme nt above.
  645           ol dCipher.di spose();
  646  
  647           //  reset the  flag of t he first a pplication  record
  648           is FirstAppOu tputRecord  = true;
  649       }
  650  
  651       /*
  652        * Upd ates the S SL version  associate d with thi s connecti on.
  653        * Cal led from H andshaker  once it ha s determin ed the neg otiated ve rsion.
  654        */
  655       synchr onized voi d setVersi on(Protoco lVersion p rotocolVer sion) {
  656           th is.protoco lVersion =  protocolV ersion;
  657           ou tputRecord .setVersio n(protocol Version);
  658       }
  659  
  660  
  661       /**
  662        * Kic kstart the  handshake  if it is  not alread y in progr ess.
  663        * Thi s means:
  664        *
  665        *  .  if handsha king is al ready unde rway, do n othing and  return
  666        *
  667        *  .  if the eng ine is not  connected  or alread y closed,  throw an
  668        *     Exception.
  669        *
  670        *  .  otherwise,  call init Handshake( ) to initi alize the  handshaker
  671        *     object and  progress  the state.  Then, sen d the init ial
  672        *     handshakin g message  if appropr iate (alwa ys on clie nts and
  673        *     on servers  when rene gotiating) .
  674        */
  675       privat e synchron ized void  kickstartH andshake()  throws IO Exception  {
  676           sw itch (conn ectionStat e) {
  677  
  678           ca se cs_STAR T:
  679                if (!ser verModeSet ) {
  680                    thro w new Ille galStateEx ception(
  681                         "Client/Se rver mode  not yet se t.");
  682                }
  683                initHand shaker();
  684                break;
  685  
  686           ca se cs_HAND SHAKE:
  687                // hands haker alre ady setup,  proceed
  688                break;
  689  
  690           ca se cs_DATA :
  691                if (!sec ureRenegot iation &&  !Handshake r.allowUns afeRenegot iation) {
  692                    thro w new SSLH andshakeEx ception(
  693                             "Insec ure renego tiation is  not allow ed");
  694                }
  695  
  696                if (!sec ureRenegot iation) {
  697                    if ( debug != n ull && Deb ug.isOn("h andshake") ) {
  698                         System.out .println(
  699                             "Warni ng: Using  insecure r enegotiati on");
  700                    }
  701                }
  702  
  703                // initi alize the  handshaker , move to  cs_RENEGOT IATE
  704                initHand shaker();
  705                break;
  706  
  707           ca se cs_RENE GOTIATE:
  708                // hands haking alr eady in pr ogress, re turn
  709                return;
  710  
  711           de fault:
  712                // cs_ER ROR/cs_CLO SED
  713                throw ne w SSLExcep tion("SSLE ngine is c losing/clo sed");
  714           }
  715  
  716           //
  717           //  Kickstart  handshake  state mac hine if we  need to . ..
  718           //
  719           //  Note that  handshake r.kickstar t() writes  the messa ge
  720           //  to its Ha ndshakeOut Stream, wh ich calls  back into
  721           //  SSLSocket Impl.write Record() t o send it.
  722           //
  723           if  (!handsha ker.activa ted()) {
  724                 // prio r to hands haking, ac tivate the  handshake
  725                if (conn ectionStat e == cs_RE NEGOTIATE)  {
  726                    // d on't use S SLv2Hello  when reneg otiating
  727                    hand shaker.act ivate(prot ocolVersio n);
  728                } else {
  729                    hand shaker.act ivate(null );
  730                }
  731  
  732                if (hand shaker ins tanceof Cl ientHandsh aker) {
  733                    // s end client  hello
  734                    hand shaker.kic kstart();
  735                } else {     // ins tanceof Se rverHandsh aker
  736                    if ( connection State == c s_HANDSHAK E) {
  737                         // initial  handshake , no kicks tart messa ge to send
  738                    } el se {
  739                         // we want  to renego tiate, sen d hello re quest
  740                         handshaker .kickstart ();
  741  
  742                         // hello r equest is  not includ ed in the  handshake
  743                         // hashes,  reset the m
  744                         handshaker .handshake Hash.reset ();
  745                    }
  746                }
  747           }
  748       }
  749  
  750       /*
  751        * Sta rt a SSLEn gine hands hake
  752        */
  753       @Overr ide
  754       public  void begi nHandshake () throws  SSLExcepti on {
  755           tr y {
  756                kickstar tHandshake ();
  757           }  catch (Exc eption e)  {
  758                fatal(Al erts.alert _handshake _failure,
  759                    "Cou ldn't kick start hand shaking",  e);
  760           }
  761       }
  762  
  763  
  764       //
  765       // Rea d/unwrap s ide
  766       //
  767  
  768  
  769       /**
  770        * Unw raps a buf fer.  Does  a variety  of checks  before gr abbing
  771        * the  unwrapLoc k, which b locks mult iple unwra ps from oc curring.
  772        */
  773       @Overr ide
  774       public  SSLEngine Result unw rap(ByteBu ffer netDa ta, ByteBu ffer [] ap pData,
  775                int offs et, int le ngth) thro ws SSLExce ption {
  776  
  777           En gineArgs e a = new En gineArgs(n etData, ap pData, off set, lengt h);
  778  
  779           tr y {
  780                synchron ized (unwr apLock) {
  781                    retu rn readNet Record(ea) ;
  782                }
  783           }  catch (Exc eption e)  {
  784                /*
  785                 * Don't  reset pos ition so i t looks li ke we didn 't
  786                 * consu me anythin g.  We did  consume s omething,  and it
  787                 * got u s into thi s situatio n, so repo rt that mu ch back.
  788                 * Our d ays of con suming are  now over  anyway.
  789                 */
  790                fatal(Al erts.alert _internal_ error,
  791                    "pro blem unwra pping net  record", e );
  792                return n ull;  // m ake compil er happy
  793           }  finally {
  794                /*
  795                 * Just  in case so mething fa iled to re set limits  properly.
  796                 */
  797                ea.reset Lim();
  798           }
  799       }
  800  
  801       /*
  802        * Mak es additio nal checks  for unwra p, but thi s time mor e
  803        * spe cific to t his packet  and the c urrent sta te of the  machine.
  804        */
  805       privat e SSLEngin eResult re adNetRecor d(EngineAr gs ea) thr ows IOExce ption {
  806  
  807           St atus statu s = null;
  808           Ha ndshakeSta tus hsStat us = null;
  809  
  810           /*
  811            *  See if th e handshak er needs t o report b ack some S SLExceptio n.
  812            * /
  813           ch eckTaskThr own();
  814  
  815           /*
  816            *  Check if  we are clo sing/close d.
  817            * /
  818           if  (isInboun dDone()) {
  819                return n ew SSLEngi neResult(S tatus.CLOS ED, getHSS tatus(null ), 0, 0);
  820           }
  821  
  822           /*
  823            *  If we're  still in c s_HANDSHAK E, make su re it's be en
  824            *  started.
  825            * /
  826           sy nchronized  (this) {
  827                if ((con nectionSta te == cs_H ANDSHAKE)  ||
  828                         (connectio nState ==  cs_START))  {
  829                    kick startHands hake();
  830  
  831                    /*
  832                     * I f there's  still outb ound data  to flush,  we
  833                     * c an return  without tr ying to un wrap anyth ing.
  834                     */
  835                    hsSt atus = get HSStatus(n ull);
  836  
  837                    if ( hsStatus = = Handshak eStatus.NE ED_WRAP) {
  838                         return new  SSLEngine Result(Sta tus.OK, hs Status, 0,  0);
  839                    }
  840                }
  841           }
  842  
  843           /*
  844            *  Grab a co py of this  if it doe sn't alrea dy exist,
  845            *  and we ca n use it s everal pla ces before  anything  major
  846            *  happens o n this sid e.  Races  aren't cri tical
  847            *  here.
  848            * /
  849           if  (hsStatus  == null)  {
  850                hsStatus  = getHSSt atus(null) ;
  851           }
  852  
  853           /*
  854            *  If we hav e a task o utstanding , this *MU ST* be don e before
  855            *  doing any  more unwr apping, be cause we c ould be in  the middl e
  856            *  of receiv ing a hand shake mess age, for e xample, a  finished
  857            *  message w hich would  change th e ciphers.
  858            * /
  859           if  (hsStatus  == Handsh akeStatus. NEED_TASK)  {
  860                return n ew SSLEngi neResult(
  861                    Stat us.OK, hsS tatus, 0,  0);
  862           }
  863  
  864           /*
  865            *  Check the  packet to  make sure  enough is  here.
  866            *  This will  also indi rectly che ck for 0 l en packets .
  867            * /
  868           in t packetLe n = inputR ecord.byte sInComplet ePacket(ea .netData);
  869  
  870           //  Is this p acket bigg er than SS L/TLS norm ally allow s?
  871           if  (packetLe n > sess.g etPacketBu fferSize() ) {
  872                if (pack etLen > Re cord.maxLa rgeRecordS ize) {
  873                    thro w new SSLP rotocolExc eption(
  874                         "Input SSL /TLS recor d too big:  max = " +
  875                         Record.max LargeRecor dSize +
  876                         " len = "  + packetLe n);
  877                } else {
  878                    // E xpand the  expected m aximum pac ket/applic ation buff er
  879                    // s izes.
  880                    sess .expandBuf ferSizes() ;
  881                }
  882           }
  883  
  884           /*
  885            *  Check for  OVERFLOW.
  886            *
  887            *  To be con sidered: W e could de lay enforc ing the ap plication  buffer
  888            *  free spac e requirem ent until  after the  initial ha ndshaking.
  889            * /
  890           if  ((packetL en - Recor d.headerSi ze) > ea.g etAppRemai ning()) {
  891                return n ew SSLEngi neResult(S tatus.BUFF ER_OVERFLO W, hsStatu s, 0, 0);
  892           }
  893  
  894           //  check for  UNDERFLOW .
  895           if  ((packetL en == -1)  || (ea.net Data.remai ning() < p acketLen))  {
  896                return n ew SSLEngi neResult(
  897                    Stat us.BUFFER_ UNDERFLOW,  hsStatus,  0, 0);
  898           }
  899  
  900           /*
  901            *  We're now  ready to  actually d o the read .
  902            *  The only  result cod e we reall y need to  be exactly
  903            *  right is  the HS fin ished, for  signaling  to
  904            *  Handshake CompletedL isteners.
  905            * /
  906           tr y {
  907                hsStatus  = readRec ord(ea);
  908           }  catch (SSL Exception  e) {
  909                throw e;
  910           }  catch (IOE xception e ) {
  911                throw ne w SSLExcep tion("read Record", e );
  912           }
  913  
  914           /*
  915            *  Check the  various c ondition t hat we cou ld be repo rting.
  916            *
  917            *  It's *pos sible* som ething mig ht have ha ppened bet ween the
  918            *  above and  now, but  it was bet ter to min imally loc k "this"
  919            *  during th e read pro cess.  We' ll return  the curren t
  920            *  status, w hich is mo re represe ntative of  the curre nt state.
  921            *
  922            *  status ab ove should  cover:  F INISHED, N EED_TASK
  923            * /
  924           st atus = (is InboundDon e() ? Stat us.CLOSED  : Status.O K);
  925           hs Status = g etHSStatus (hsStatus) ;
  926  
  927           re turn new S SLEngineRe sult(statu s, hsStatu s,
  928                ea.delta Net(), ea. deltaApp() );
  929       }
  930  
  931       /*
  932        * Act ually do t he read re cord proce ssing.
  933        *
  934        * Ret urns a Sta tus if it  can make s pecific de terminatio ns
  935        * of  the engine  state.  I n particul ar, we nee d to signa l
  936        * tha t a handsh ake just c ompleted.
  937        *
  938        * It  would be n ice to be  symmetrica l with the  write sid e and move
  939        * the  majority  of this to  EngineInp utRecord,  but there' s too much
  940        * SSL Engine sta te to do t hat cleanl y.  It mus t still li ve here.
  941        */
  942       privat e Handshak eStatus re adRecord(E ngineArgs  ea) throws  IOExcepti on {
  943  
  944           Ha ndshakeSta tus hsStat us = null;
  945  
  946           /*
  947            *  The vario us operati ons will r eturn new  sliced BB' s,
  948            *  this will  avoid hav ing to wor ry about p ositions a nd
  949            *  limits in  the netBB .
  950            * /
  951           By teBuffer r eadBB = nu ll;
  952           By teBuffer d ecryptedBB  = null;
  953  
  954           if  (getConne ctionState () != cs_E RROR) {
  955  
  956                /*
  957                 * Read  a record . .. maybe e mitting an  alert if  we get a
  958                 * compr ehensible  but unsupp orted "hel lo" messag e during
  959                 * forma t checking  (e.g. V2) .
  960                 */
  961                try {
  962                    read BB = input Record.rea d(ea.netDa ta);
  963                } catch  (IOExcepti on e) {
  964                    fata l(Alerts.a lert_unexp ected_mess age, e);
  965                }
  966  
  967                /*
  968                 * The b asic SSLv3  record pr otection i nvolves (o ptional)
  969                 * encry ption for  privacy, a nd an inte grity chec k ensuring
  970                 * data  origin aut henticatio n.  We do  them both  here, and
  971                 * throw  a fatal a lert if th e integrit y check fa ils.
  972                 */
  973                try {
  974                    decr yptedBB =  inputRecor d.decrypt(
  975                                          read Authentica tor, readC ipher, rea dBB);
  976                } catch  (BadPaddin gException  e) {
  977                    byte  alertType  = (inputR ecord.cont entType()  ==
  978                         Record.ct_ handshake)  ?
  979                             Alerts .alert_han dshake_fai lure :
  980                             Alerts .alert_bad _record_ma c;
  981                    fata l(alertTyp e, e.getMe ssage(), e );
  982                }
  983  
  984                // if (! inputRecor d.decompre ss(c))
  985                //     f atal(Alert s.alert_de compressio n_failure,
  986                //     " decompress ion failur e");
  987  
  988  
  989                /*
  990                 * Proce ss the rec ord.
  991                 */
  992  
  993                synchron ized (this ) {
  994                    swit ch (inputR ecord.cont entType())  {
  995                    case  Record.ct _handshake :
  996                         /*
  997                          * Handsha ke message s always g o to a pen ding sessi on
  998                          * handsha ker ... if  there isn 't one, cr eate one.   This
  999                          * must wo rk asynchr onously, f or renegot iation.
  1000                          *
  1001                          * NOTE th at handsha king will  either res ume a sess ion
  1002                          * which w as in the  cache (and  which mig ht have ot her
  1003                          * connect ions in it  already),  or else w ill start  a new
  1004                          * session  (new keys  exchanged ) with jus t this con nection
  1005                          * in it.
  1006                          */
  1007                         initHandsh aker();
  1008                         if (!hands haker.acti vated()) {
  1009                             // pri or to hand shaking, a ctivate th e handshak e
  1010                             if (co nnectionSt ate == cs_ RENEGOTIAT E) {
  1011                                 //  don't use  SSLv2Hell o when ren egotiating
  1012                                 ha ndshaker.a ctivate(pr otocolVers ion);
  1013                             } else  {
  1014                                 ha ndshaker.a ctivate(nu ll);
  1015                             }
  1016                         }
  1017  
  1018                         /*
  1019                          * process  the hands hake recor d ... may  contain ju st
  1020                          * a parti al handsha ke message  or multip le message s.
  1021                          *
  1022                          * The han dshaker st ate machin e will ens ure that i t's
  1023                          * a finis hed messag e.
  1024                          */
  1025                         handshaker .process_r ecord(inpu tRecord, e xpectingFi nished);
  1026                         expectingF inished =  false;
  1027  
  1028                         if (handsh aker.inval idated) {
  1029                             handsh aker = nul l;
  1030                             receiv edCCS = fa lse;
  1031                             // if  state is c s_RENEGOTI ATE, rever t it to cs _DATA
  1032                             if (co nnectionSt ate == cs_ RENEGOTIAT E) {
  1033                                 co nnectionSt ate = cs_D ATA;
  1034                             }
  1035                         } else if  (handshake r.isDone() ) {
  1036                             // res et the par ameters fo r secure r enegotiati on.
  1037                             secure Renegotiat ion =
  1038                                               handshaker .isSecureR enegotiati on();
  1039                             client VerifyData  = handsha ker.getCli entVerifyD ata();
  1040                             server VerifyData  = handsha ker.getSer verVerifyD ata();
  1041  
  1042                             sess =  handshake r.getSessi on();
  1043                             handsh akeSession  = null;
  1044                             if (!w riter.hasO utboundDat a()) {
  1045                                 hs Status = H andshakeSt atus.FINIS HED;
  1046                             }
  1047                             handsh aker = nul l;
  1048                             connec tionState  = cs_DATA;
  1049                             receiv edCCS = fa lse;
  1050  
  1051                             // No  handshakeL isteners h ere.  That 's a
  1052                             // SSL Socket thi ng.
  1053                         } else if  (handshake r.taskOuts tanding())  {
  1054                             hsStat us = Hands hakeStatus .NEED_TASK ;
  1055                         }
  1056                         break;
  1057  
  1058                    case  Record.ct _applicati on_data:
  1059                         // Pass th is right b ack up to  the applic ation.
  1060                         if ((conne ctionState  != cs_DAT A)
  1061                                 &&  (connecti onState !=  cs_RENEGO TIATE)
  1062                                 &&  (connecti onState !=  cs_CLOSED )) {
  1063                             throw  new SSLPro tocolExcep tion(
  1064                                 "D ata receiv ed in non- data state : " +
  1065                                 co nnectionSt ate);
  1066                         }
  1067  
  1068                         if (expect ingFinishe d) {
  1069                             throw  new SSLPro tocolExcep tion
  1070                                      ("Expect ing finish ed message , received  data");
  1071                         }
  1072  
  1073                         /*
  1074                          * Don't r eturn data  once the  inbound si de is
  1075                          * closed.
  1076                          */
  1077                         if (!inbou ndDone) {
  1078                             ea.sca tter(decry ptedBB.sli ce());
  1079                         }
  1080                         break;
  1081  
  1082                    case  Record.ct _alert:
  1083                         recvAlert( );
  1084                         break;
  1085  
  1086                    case  Record.ct _change_ci pher_spec:
  1087                         if ((conne ctionState  != cs_HAN DSHAKE
  1088                                      && conne ctionState  != cs_REN EGOTIATE)
  1089                                 ||  !handshak er.session KeysCalcul ated()
  1090                                 ||  receivedC CS) {
  1091                             // For  the CCS m essage arr iving in t he wrong s tate
  1092                             fatal( Alerts.ale rt_unexpec ted_messag e,
  1093                                      "illegal  change ci pher spec  msg, conn  state = "
  1094                                      + connec tionState  + ", hands hake state  = "
  1095                                      + handsh aker.state );
  1096                         } else if  (inputReco rd.availab le() != 1
  1097                                 ||  inputReco rd.read()  != 1) {
  1098                             // For  structura l/content  issues wit h the CCS
  1099                             fatal( Alerts.ale rt_unexpec ted_messag e,
  1100                                      "Malform ed change  cipher spe c msg");
  1101                         }
  1102  
  1103                         // Once we 've receiv ed CCS, up date the f lag.
  1104                         // If the  remote end point send s it again  in this h andshake
  1105                         // we won' t process  it.
  1106                         receivedCC S = true;
  1107  
  1108                         //
  1109                         // The fir st message  after a c hange_ciph er_spec
  1110                         // record  MUST be a  "Finished"  handshake  record,
  1111                         // else it 's a proto col violat ion.  We f orce this
  1112                         // to be c hecked by  a minor tw eak to the  state
  1113                         // machine .
  1114                         //
  1115                         changeRead Ciphers();
  1116                         // next me ssage MUST  be a fini shed messa ge
  1117                         expectingF inished =  true;
  1118                         break;
  1119  
  1120                    defa ult:
  1121                         //
  1122                         // TLS req uires that  unrecogni zed record s be ignor ed.
  1123                         //
  1124                         if (debug  != null &&  Debug.isO n("ssl"))  {
  1125                             System .out.print ln(Thread. currentThr ead().getN ame() +
  1126                                 ",  Received  record typ e: "
  1127                                 +  inputRecor d.contentT ype());
  1128                         }
  1129                         break;
  1130                    } //  switch
  1131  
  1132                    /*
  1133                     * W e only nee d to check  the seque nce number  state for
  1134                     * n on-handsha king recor d.
  1135                     *
  1136                     * N ote that i n order to  maintain  the handsh ake status
  1137                     * p roperly, w e check th e sequence  number af ter the la st
  1138                     * r ecord read ing proces s. As we r equest ren egotiation
  1139                     * o r close th e connecti on for wra pped seque nce number
  1140                     * w hen there  is enough  sequence n umber spac e left to
  1141                     * h andle a fe w more rec ords, so t he sequenc e number
  1142                     * o f the last  record ca nnot be wr apped.
  1143                     */
  1144                    hsSt atus = get HSStatus(h sStatus);
  1145                    if ( connection State < cs _ERROR &&  !isInbound Done() &&
  1146                             (hsSta tus == Han dshakeStat us.NOT_HAN DSHAKING))  {
  1147                         if (checkS equenceNum ber(readAu thenticato r,
  1148                                 in putRecord. contentTyp e())) {
  1149                             hsStat us = getHS Status(nul l);
  1150                         }
  1151                    }
  1152                } // syn chronized  (this)
  1153           }
  1154  
  1155           re turn hsSta tus;
  1156       }
  1157  
  1158  
  1159       //
  1160       // wri te/wrap si de
  1161       //
  1162  
  1163  
  1164       /**
  1165        * Wra ps a buffe r.  Does a  variety o f checks b efore grab bing
  1166        * the  wrapLock,  which blo cks multip le wraps f rom occurr ing.
  1167        */
  1168       @Overr ide
  1169       public  SSLEngine Result wra p(ByteBuff er [] appD ata,
  1170                int offs et, int le ngth, Byte Buffer net Data) thro ws SSLExce ption {
  1171  
  1172           En gineArgs e a = new En gineArgs(a ppData, of fset, leng th, netDat a);
  1173  
  1174           /*
  1175            *  We can be  smarter a bout using  smaller b uffer size s later.
  1176            *  For now,  force it t o be large  enough to  handle an y
  1177            *  valid SSL /TLS recor d.
  1178            * /
  1179           if  (netData. remaining( ) < Engine OutputReco rd.maxReco rdSize) {
  1180                return n ew SSLEngi neResult(
  1181                    Stat us.BUFFER_ OVERFLOW,  getHSStatu s(null), 0 , 0);
  1182           }
  1183  
  1184           tr y {
  1185                synchron ized (wrap Lock) {
  1186                    retu rn writeAp pRecord(ea );
  1187                }
  1188           }  catch (Exc eption e)  {
  1189                ea.reset Pos();
  1190  
  1191                fatal(Al erts.alert _internal_ error,
  1192                    "pro blem wrapp ing app da ta", e);
  1193                return n ull;  // m ake compil er happy
  1194           }  finally {
  1195                /*
  1196                 * Just  in case so mething di dn't reset  limits pr operly.
  1197                 */
  1198                ea.reset Lim();
  1199           }
  1200       }
  1201  
  1202       /*
  1203        * Mak es additio nal checks  for unwra p, but thi s time mor e
  1204        * spe cific to t his packet  and the c urrent sta te of the  machine.
  1205        */
  1206       privat e SSLEngin eResult wr iteAppReco rd(EngineA rgs ea) th rows IOExc eption {
  1207  
  1208           St atus statu s = null;
  1209           Ha ndshakeSta tus hsStat us = null;
  1210  
  1211           /*
  1212            *  See if th e handshak er needs t o report b ack some S SLExceptio n.
  1213            * /
  1214           ch eckTaskThr own();
  1215  
  1216           /*
  1217            *  short cir cuit if we 're closed /closing.
  1218            * /
  1219           if  (writer.i sOutboundD one()) {
  1220                return n ew SSLEngi neResult(S tatus.CLOS ED, getHSS tatus(null ), 0, 0);
  1221           }
  1222  
  1223           /*
  1224            *  If we're  still in c s_HANDSHAK E, make su re it's be en
  1225            *  started.
  1226            * /
  1227           sy nchronized  (this) {
  1228                if ((con nectionSta te == cs_H ANDSHAKE)  ||
  1229                         (connectio nState ==  cs_START))  {
  1230                    kick startHands hake();
  1231  
  1232                    /*
  1233                     * I f there's  no HS data  available  to write,  we can re turn
  1234                     * w ithout try ing to wra p anything .
  1235                     */
  1236                    hsSt atus = get HSStatus(n ull);
  1237  
  1238                    if ( hsStatus = = Handshak eStatus.NE ED_UNWRAP)  {
  1239                         return new  SSLEngine Result(Sta tus.OK, hs Status, 0,  0);
  1240                    }
  1241                }
  1242           }
  1243  
  1244           /*
  1245            *  Grab a co py of this  if it doe sn't alrea dy exist,
  1246            *  and we ca n use it s everal pla ces before  anything  major
  1247            *  happens o n this sid e.  Races  aren't cri tical
  1248            *  here.
  1249            * /
  1250           if  (hsStatus  == null)  {
  1251                hsStatus  = getHSSt atus(null) ;
  1252           }
  1253  
  1254           /*
  1255            *  If we hav e a task o utstanding , this *MU ST* be don e before
  1256            *  doing any  more wrap ping, beca use we cou ld be in t he middle
  1257            *  of receiv ing a hand shake mess age, for e xample, a  finished
  1258            *  message w hich would  change th e ciphers.
  1259            * /
  1260           if  (hsStatus  == Handsh akeStatus. NEED_TASK)  {
  1261                return n ew SSLEngi neResult(
  1262                    Stat us.OK, hsS tatus, 0,  0);
  1263           }
  1264  
  1265           /*
  1266            *  This will  obtain an y waiting  outbound d ata, or wi ll
  1267            *  process t he outboun d appData.
  1268            * /
  1269           tr y {
  1270                synchron ized (writ eLock) {
  1271                    hsSt atus = wri teRecord(o utputRecor d, ea);
  1272                }
  1273           }  catch (SSL Exception  e) {
  1274                throw e;
  1275           }  catch (IOE xception e ) {
  1276                throw ne w SSLExcep tion("Writ e problems ", e);
  1277           }
  1278  
  1279           /*
  1280            *  writeReco rd might h ave report ed some st atus.
  1281            *  Now check  for the r emaining c ases.
  1282            *
  1283            *  status ab ove should  cover:  N EED_WRAP/F INISHED
  1284            * /
  1285           st atus = (is OutboundDo ne() ? Sta tus.CLOSED  : Status. OK);
  1286           hs Status = g etHSStatus (hsStatus) ;
  1287  
  1288           re turn new S SLEngineRe sult(statu s, hsStatu s,
  1289                ea.delta App(), ea. deltaNet() );
  1290       }
  1291  
  1292       /*
  1293        * Cen tral point  to write/ get all of  the outgo ing data.
  1294        */
  1295       privat e Handshak eStatus wr iteRecord( EngineOutp utRecord e or,
  1296                EngineAr gs ea) thr ows IOExce ption {
  1297  
  1298           //  eventuall y compress  as well.
  1299           Ha ndshakeSta tus hsStat us =
  1300                    writ er.writeRe cord(eor,  ea, writeA uthenticat or, writeC ipher);
  1301  
  1302           /*
  1303            *  We only n eed to che ck the seq uence numb er state f or
  1304            *  non-hands haking rec ord.
  1305            *
  1306            *  Note that  in order  to maintai n the hand shake stat us
  1307            *  properly,  we check  the sequen ce number  after the  last
  1308            *  record wr iting proc ess. As we  request r enegotiati on
  1309            *  or close  the connec tion for w rapped seq uence numb er
  1310            *  when ther e is enoug h sequence  number sp ace left t o
  1311            *  handle a  few more r ecords, so  the seque nce number
  1312            *  of the la st record  cannot be  wrapped.
  1313            * /
  1314           hs Status = g etHSStatus (hsStatus) ;
  1315           if  (connecti onState <  cs_ERROR & & !isOutbo undDone()  &&
  1316                    (hsS tatus == H andshakeSt atus.NOT_H ANDSHAKING )) {
  1317                if (chec kSequenceN umber(writ eAuthentic ator, eor. contentTyp e())) {
  1318                    hsSt atus = get HSStatus(n ull);
  1319                }
  1320           }
  1321  
  1322           /*
  1323            *  turn off  the flag o f the firs t applicat ion record  if we rea lly
  1324            *  consumed  at least b yte.
  1325            * /
  1326           if  (isFirstA ppOutputRe cord && ea .deltaApp( ) > 0) {
  1327                isFirstA ppOutputRe cord = fal se;
  1328           }
  1329  
  1330           re turn hsSta tus;
  1331       }
  1332  
  1333       /*
  1334        * Nee d to split  the paylo ad except  the follow ing cases:
  1335        *
  1336        * 1.  protocol v ersion is  TLS 1.1 or  later;
  1337        * 2.  bulk ciphe r does not  use CBC m ode, inclu ding null  bulk ciphe r suites.
  1338        * 3.  the payloa d is the f irst appli cation rec ord of a f reshly
  1339        *     negotiated  TLS sessi on.
  1340        * 4.  the CBC pr otection i s disabled ;
  1341        *
  1342        * Mor e details,  please re fer to
  1343        * Eng ineOutputR ecord.writ e(EngineAr gs, MAC, C ipherBox).
  1344        */
  1345       boolea n needToSp litPayload (CipherBox  cipher, P rotocolVer sion proto col) {
  1346           re turn (prot ocol.v <=  ProtocolVe rsion.TLS1 0.v) &&
  1347                    ciph er.isCBCMo de() && !i sFirstAppO utputRecor d &&
  1348                    Reco rd.enableC BCProtecti on;
  1349       }
  1350  
  1351       /*
  1352        * Non -applicati on OutputR ecords go  through he re.
  1353        */
  1354       void w riteRecord (EngineOut putRecord  eor) throw s IOExcept ion {
  1355           //  eventuall y compress  as well.
  1356           wr iter.write Record(eor , writeAut henticator , writeCip her);
  1357  
  1358           /*
  1359            *  Check the  sequence  number sta te
  1360            *
  1361            *  Note that  in order  to maintai n the conn ection I/O
  1362            *  properly,  we check  the sequen ce number  after the  last
  1363            *  record wr iting proc ess. As we  request r enegotiati on
  1364            *  or close  the connec tion for w rapped seq uence numb er
  1365            *  when ther e is enoug h sequence  number sp ace left t o
  1366            *  handle a  few more r ecords, so  the seque nce number
  1367            *  of the la st record  cannot be  wrapped.
  1368            * /
  1369           if  ((connect ionState <  cs_ERROR)  && !isOut boundDone( )) {
  1370                checkSeq uenceNumbe r(writeAut henticator , eor.cont entType()) ;
  1371           }
  1372       }
  1373  
  1374       //
  1375       // Clo se code
  1376       //
  1377  
  1378       /**
  1379        * Che ck the seq uence numb er state
  1380        *
  1381        * RFC  4346 stat es that, " Sequence n umbers are  of type u int64 and
  1382        * may  not excee d 2^64-1.   Sequence  numbers do  not wrap.  If a TLS
  1383        * imp lementatio n would ne ed to wrap  a sequenc e number,  it must
  1384        * ren egotiate i nstead."
  1385        *
  1386        * Ret urn true i f the hand shake stat us may be  changed.
  1387        */
  1388       privat e boolean  checkSeque nceNumber( Authentica tor authen ticator, b yte type)
  1389                throws I OException  {
  1390  
  1391           /*
  1392            *  Don't bot her to che ck the seq uence numb er for err or or
  1393            *  closed co nnections,  or NULL M AC
  1394            * /
  1395           if  (connecti onState >=  cs_ERROR  || authent icator ==  MAC.NULL)  {
  1396                return f alse;
  1397           }
  1398  
  1399           /*
  1400            *  Conservat ively, clo se the con nection im mediately  when the
  1401            *  sequence  number is  close to o verflow
  1402            * /
  1403           if  (authenti cator.seqN umOverflow ()) {
  1404                /*
  1405                 * TLS p rotocols d o not defi ne a error  alert for  sequence
  1406                 * numbe r overflow . We use h andshake_f ailure err or alert
  1407                 * for h andshaking  and bad_r ecord_mac  for other  records.
  1408                 */
  1409                if (debu g != null  && Debug.i sOn("ssl") ) {
  1410                    Syst em.out.pri ntln(Threa d.currentT hread().ge tName() +
  1411                         ", sequenc e number e xtremely c lose to ov erflow " +
  1412                         "(2^64-1 p ackets). C losing con nection.") ;
  1413                }
  1414  
  1415                fatal(Al erts.alert _handshake _failure,  "sequence  number ove rflow");
  1416  
  1417                return t rue; // ma ke the com piler happ y
  1418           }
  1419  
  1420           /*
  1421            *  Ask for r enegotiati on when ne ed to rene w sequence  number.
  1422            *
  1423            *  Don't bot her to kic kstart the  renegotia tion when  the local  is
  1424            *  asking fo r it.
  1425            * /
  1426           if  ((type !=  Record.ct _handshake ) && authe nticator.s eqNumIsHug e()) {
  1427                if (debu g != null  && Debug.i sOn("ssl") ) {
  1428                    Syst em.out.pri ntln(Threa d.currentT hread().ge tName() +
  1429                             ", req uest reneg otiation "  +
  1430                             "to av oid sequen ce number  overflow") ;
  1431                }
  1432  
  1433                beginHan dshake();
  1434                return t rue;
  1435           }
  1436  
  1437           re turn false ;
  1438       }
  1439  
  1440       /**
  1441        * Sig nals that  no more ou tbound app lication d ata will b e sent
  1442        * on  this <code >SSLEngine </code>.
  1443        */
  1444       privat e void clo seOutbound Internal()  {
  1445  
  1446           if  ((debug ! = null) &&  Debug.isO n("ssl"))  {
  1447                System.o ut.println (Thread.cu rrentThrea d().getNam e() +
  1448                                          ", c loseOutbou ndInternal ()");
  1449           }
  1450  
  1451           /*
  1452            *  Already c losed, ign ore
  1453            * /
  1454           if  (writer.i sOutboundD one()) {
  1455                return;
  1456           }
  1457  
  1458           sw itch (conn ectionStat e) {
  1459  
  1460           /*
  1461            *  If we hav en't even  started ye t, don't b other read ing inboun d.
  1462            * /
  1463           ca se cs_STAR T:
  1464                writer.c loseOutbou nd();
  1465                inboundD one = true ;
  1466                break;
  1467  
  1468           ca se cs_ERRO R:
  1469           ca se cs_CLOS ED:
  1470                break;
  1471  
  1472           /*
  1473            *  Otherwise  we indica te clean t ermination .
  1474            * /
  1475           //  case cs_H ANDSHAKE:
  1476           //  case cs_D ATA:
  1477           //  case cs_R ENEGOTIATE :
  1478           de fault:
  1479                warning( Alerts.ale rt_close_n otify);
  1480                writer.c loseOutbou nd();
  1481                break;
  1482           }
  1483  
  1484           //  See comme nt in chan geReadCiph ers()
  1485           wr iteCipher. dispose();
  1486  
  1487           co nnectionSt ate = cs_C LOSED;
  1488       }
  1489  
  1490       @Overr ide
  1491       synchr onized pub lic void c loseOutbou nd() {
  1492           /*
  1493            *  Dump out  a close_no tify to th e remote s ide
  1494            * /
  1495           if  ((debug ! = null) &&  Debug.isO n("ssl"))  {
  1496                System.o ut.println (Thread.cu rrentThrea d().getNam e() +
  1497                                          ", c alled clos eOutbound( )");
  1498           }
  1499  
  1500           cl oseOutboun dInternal( );
  1501       }
  1502  
  1503       /**
  1504        * Ret urns the o utbound ap plication  data closu re state
  1505        */
  1506       @Overr ide
  1507       public  boolean i sOutboundD one() {
  1508           re turn write r.isOutbou ndDone();
  1509       }
  1510  
  1511       /**
  1512        * Sig nals that  no more in bound netw ork data w ill be sen t
  1513        * to  this <code >SSLEngine </code>.
  1514        */
  1515       privat e void clo seInboundI nternal()  {
  1516  
  1517           if  ((debug ! = null) &&  Debug.isO n("ssl"))  {
  1518                System.o ut.println (Thread.cu rrentThrea d().getNam e() +
  1519                                          ", c loseInboun dInternal( )");
  1520           }
  1521  
  1522           /*
  1523            *  Already c losed, ign ore
  1524            * /
  1525           if  (inboundD one) {
  1526                return;
  1527           }
  1528  
  1529           cl oseOutboun dInternal( );
  1530           in boundDone  = true;
  1531  
  1532           //  See comme nt in chan geReadCiph ers()
  1533           re adCipher.d ispose();
  1534  
  1535           co nnectionSt ate = cs_C LOSED;
  1536       }
  1537  
  1538       /*
  1539        * Clo se the inb ound side  of the con nection.   We grab th e
  1540        * loc k here, an d do the r eal work i n the inte rnal veris on.
  1541        * We  do check f or truncat ion attack s.
  1542        */
  1543       @Overr ide
  1544       synchr onized pub lic void c loseInboun d() throws  SSLExcept ion {
  1545           /*
  1546            *  Currently  closes th e outbound  side as w ell.  The  IETF TLS
  1547            *  working g roup has e xpressed t he opinion  that 1/2  open
  1548            *  connectio ns are not  allowed b y the spec .  May cha nge
  1549            *  someday i n the futu re.
  1550            * /
  1551           if  ((debug ! = null) &&  Debug.isO n("ssl"))  {
  1552                System.o ut.println (Thread.cu rrentThrea d().getNam e() +
  1553                                          ", c alled clos eInbound() ");
  1554           }
  1555  
  1556           /*
  1557            *  No need t o throw an  Exception  if we hav en't even  started ye t.
  1558            * /
  1559           if  ((connect ionState ! = cs_START ) && !recv CN) {
  1560                recvCN =  true;  //  Only rece ive the Ex ception on ce
  1561                fatal(Al erts.alert _internal_ error,
  1562                    "Inb ound close d before r eceiving p eer's clos e_notify:  " +
  1563                    "pos sible trun cation att ack?");
  1564           }  else {
  1565                /*
  1566                 * Curre ntly, this  is a no-o p, but in  case we ch ange
  1567                 * the c lose inbou nd code la ter.
  1568                 */
  1569                closeInb oundIntern al();
  1570           }
  1571       }
  1572  
  1573       /**
  1574        * Ret urns the n etwork inb ound data  closure st ate
  1575        */
  1576       @Overr ide
  1577       synchr onized pub lic boolea n isInboun dDone() {
  1578           re turn inbou ndDone;
  1579       }
  1580  
  1581  
  1582       //
  1583       // Mis c stuff
  1584       //
  1585  
  1586  
  1587       /**
  1588        * Ret urns the c urrent <co de>SSLSess ion</code>  for this
  1589        * <co de>SSLEngi ne</code>
  1590        * <P>
  1591        * The se can be  long lived , and freq uently cor respond to  an
  1592        * ent ire login  session fo r some use r.
  1593        */
  1594       @Overr ide
  1595       synchr onized pub lic SSLSes sion getSe ssion() {
  1596           re turn sess;
  1597       }
  1598  
  1599       @Overr ide
  1600       synchr onized pub lic SSLSes sion getHa ndshakeSes sion() {
  1601           re turn hands hakeSessio n;
  1602       }
  1603  
  1604       synchr onized voi d setHands hakeSessio n(SSLSessi onImpl ses sion) {
  1605           ha ndshakeSes sion = ses sion;
  1606       }
  1607  
  1608       /**
  1609        * Ret urns a del egated <co de>Runnabl e</code> t ask for
  1610        * thi s <code>SS LEngine</c ode>.
  1611        */
  1612       @Overr ide
  1613       synchr onized pub lic Runnab le getDele gatedTask( ) {
  1614           if  (handshak er != null ) {
  1615                return h andshaker. getTask();
  1616           }
  1617           re turn null;
  1618       }
  1619  
  1620  
  1621       //
  1622       // EXC EPTION AND  ALERT HAN DLING
  1623       //
  1624  
  1625       /*
  1626        * Sen d a warnin g alert.
  1627        */
  1628       void w arning(byt e descript ion) {
  1629           se ndAlert(Al erts.alert _warning,  descriptio n);
  1630       }
  1631  
  1632       synchr onized voi d fatal(by te descrip tion, Stri ng diagnos tic)
  1633                throws S SLExceptio n {
  1634           fa tal(descri ption, dia gnostic, n ull);
  1635       }
  1636  
  1637       synchr onized voi d fatal(by te descrip tion, Thro wable caus e)
  1638                throws S SLExceptio n {
  1639           fa tal(descri ption, nul l, cause);
  1640       }
  1641  
  1642       /*
  1643        * We' ve got a f atal error  here, so  start the  shutdown p rocess.
  1644        *
  1645        * Bec ause of th e way the  code was w ritten, we  have some  code
  1646        * cal ling fatal  directly  when the " descriptio n" is know n
  1647        * and  some thro wing Excep tions whic h are then  caught by  higher
  1648        * lev els which  then call  here.  Thi s code nee ds to dete rmine
  1649        * if  one of the  lower lev els has al ready star ted the pr ocess.
  1650        *
  1651        * We  won't worr y about Er ror's, if  we have on e of those ,
  1652        * we' re in wors e trouble.   Note:  t he network ing code d oesn't
  1653        * dea l with Err ors either .
  1654        */
  1655       synchr onized voi d fatal(by te descrip tion, Stri ng diagnos tic,
  1656                Throwabl e cause) t hrows SSLE xception {
  1657  
  1658           /*
  1659            *  If we hav e no furth er informa tion, make  a general -purpose
  1660            *  message f or folks t o see.  We  generally  have one  or the oth er.
  1661            * /
  1662           if  (diagnost ic == null ) {
  1663                diagnost ic = "Gene ral SSLEng ine proble m";
  1664           }
  1665           if  (cause ==  null) {
  1666                cause =  Alerts.get SSLExcepti on(descrip tion, caus e, diagnos tic);
  1667           }
  1668  
  1669           /*
  1670            *  If we've  already sh utdown bec ause of an  error,
  1671            *  there is  nothing we  can do ex cept rethr ow the exc eption.
  1672            *
  1673            *  Most exce ptions see n here wil l be SSLEx ceptions.
  1674            *  We may fi nd the occ asional Ex ception wh ich hasn't  been
  1675            *  converted  to a SSLE xception,  so we'll d o it here.
  1676            * /
  1677           if  (closeRea son != nul l) {
  1678                if ((deb ug != null ) && Debug .isOn("ssl ")) {
  1679                    Syst em.out.pri ntln(Threa d.currentT hread().ge tName() +
  1680                         ", fatal:  engine alr eady close d.  Rethro wing " +
  1681                         cause.toSt ring());
  1682                }
  1683                if (caus e instance of Runtime Exception)  {
  1684                    thro w (Runtime Exception) cause;
  1685                } else i f (cause i nstanceof  SSLExcepti on) {
  1686                    thro w (SSLExce ption)caus e;
  1687                } else i f (cause i nstanceof  Exception)  {
  1688                    thro w new SSLE xception(" fatal SSLE ngine cond ition", ca use);
  1689                }
  1690           }
  1691  
  1692           if  ((debug ! = null) &&  Debug.isO n("ssl"))  {
  1693                System.o ut.println (Thread.cu rrentThrea d().getNam e()
  1694                             + ", f atal error : " + desc ription +
  1695                             ": " +  diagnosti c + "\n" +  cause.toS tring());
  1696           }
  1697  
  1698           /*
  1699            *  Ok, this  engine's g oing down.
  1700            * /
  1701           in t oldState  = connect ionState;
  1702           co nnectionSt ate = cs_E RROR;
  1703  
  1704           in boundDone  = true;
  1705  
  1706           se ss.invalid ate();
  1707           if  (handshak eSession ! = null) {
  1708                handshak eSession.i nvalidate( );
  1709           }
  1710  
  1711           /*
  1712            *  If we hav en't even  started ha ndshaking  yet, no ne ed
  1713            *  to genera te the fat al close a lert.
  1714            * /
  1715           if  (oldState  != cs_STA RT) {
  1716                sendAler t(Alerts.a lert_fatal , descript ion);
  1717           }
  1718  
  1719           if  (cause in stanceof S SLExceptio n) { // on ly true if  != null
  1720                closeRea son = (SSL Exception) cause;
  1721           }  else {
  1722                /*
  1723                 * Inclu ding Runti meExceptio ns, but we 'll throw  those
  1724                 * down  below.  Th e closeRea son isn't  used again ,
  1725                 * excep t for null  checks.
  1726                 */
  1727                closeRea son =
  1728                    Aler ts.getSSLE xception(d escription , cause, d iagnostic) ;
  1729           }
  1730  
  1731           wr iter.close Outbound() ;
  1732  
  1733           co nnectionSt ate = cs_C LOSED;
  1734  
  1735           //  See comme nt in chan geReadCiph ers()
  1736           re adCipher.d ispose();
  1737           wr iteCipher. dispose();
  1738  
  1739           if  (cause in stanceof R untimeExce ption) {
  1740                throw (R untimeExce ption)caus e;
  1741           }  else {
  1742                throw cl oseReason;
  1743           }
  1744       }
  1745  
  1746       /*
  1747        * Pro cess an in coming ale rt ... cal ler must a lready hav e synchron ized
  1748        * acc ess to "th is".
  1749        */
  1750       privat e void rec vAlert() t hrows IOEx ception {
  1751           by te level =  (byte)inp utRecord.r ead();
  1752           by te descrip tion = (by te)inputRe cord.read( );
  1753           if  (descript ion == -1)  { // chec k for shor t message
  1754                fatal(Al erts.alert _illegal_p arameter,  "Short ale rt message ");
  1755           }
  1756  
  1757           if  (debug !=  null && ( Debug.isOn ("record")  ||
  1758                    Debu g.isOn("ha ndshake")) ) {
  1759                synchron ized (Syst em.out) {
  1760                    Syst em.out.pri nt(Thread. currentThr ead().getN ame());
  1761                    Syst em.out.pri nt(", RECV  " + proto colVersion  + " ALERT :  ");
  1762                    if ( level == A lerts.aler t_fatal) {
  1763                         System.out .print("fa tal, ");
  1764                    } el se if (lev el == Aler ts.alert_w arning) {
  1765                         System.out .print("wa rning, ");
  1766                    } el se {
  1767                         System.out .print("<l evel " + ( 0x0ff & le vel) + ">,  ");
  1768                    }
  1769                    Syst em.out.pri ntln(Alert s.alertDes cription(d escription ));
  1770                }
  1771           }
  1772  
  1773           if  (level ==  Alerts.al ert_warnin g) {
  1774                if (desc ription ==  Alerts.al ert_close_ notify) {
  1775                    if ( connection State == c s_HANDSHAK E) {
  1776                         fatal(Aler ts.alert_u nexpected_ message,
  1777                                      "Receive d close_no tify durin g handshak e");
  1778                    } el se {
  1779                         recvCN = t rue;
  1780                         closeInbou ndInternal ();  // re ply to clo se
  1781                    }
  1782                } else {
  1783  
  1784                    //
  1785                    // T he other l egal warni ngs relate  to certif icates,
  1786                    // e .g. no_cer tificate,  bad_certif icate, etc ; these
  1787                    // a re importa nt to the  handshakin g code, wh ich can
  1788                    // a lso handle  illegal p rotocol al erts if ne eded.
  1789                    //
  1790                    if ( handshaker  != null)  {
  1791                         handshaker .handshake Alert(desc ription);
  1792                    }
  1793                }
  1794           }  else { //  fatal or u nknown lev el
  1795                String r eason = "R eceived fa tal alert:  "
  1796                    + Al erts.alert Descriptio n(descript ion);
  1797                if (clos eReason ==  null) {
  1798                    clos eReason =  Alerts.get SSLExcepti on(descrip tion, reas on);
  1799                }
  1800                fatal(Al erts.alert _unexpecte d_message,  reason);
  1801           }
  1802       }
  1803  
  1804  
  1805       /*
  1806        * Emi t alerts.   Caller mu st have sy nchronized  with "thi s".
  1807        */
  1808       privat e void sen dAlert(byt e level, b yte descri ption) {
  1809           //  the conne ctionState  cannot be  cs_START
  1810           if  (connecti onState >=  cs_CLOSED ) {
  1811                return;
  1812           }
  1813  
  1814           //  For initi al handsha king, don' t send ale rt message  to peer i f
  1815           //  handshake r has not  started.
  1816           if  (connecti onState ==  cs_HANDSH AKE &&
  1817                (handsha ker == nul l || !hand shaker.sta rted())) {
  1818                return;
  1819           }
  1820  
  1821           En gineOutput Record r =  new Engin eOutputRec ord(Record .ct_alert,  this);
  1822           r. setVersion (protocolV ersion);
  1823  
  1824           bo olean useD ebug = deb ug != null  && Debug. isOn("ssl" );
  1825           if  (useDebug ) {
  1826                synchron ized (Syst em.out) {
  1827                    Syst em.out.pri nt(Thread. currentThr ead().getN ame());
  1828                    Syst em.out.pri nt(", SEND  " + proto colVersion  + " ALERT :  ");
  1829                    if ( level == A lerts.aler t_fatal) {
  1830                         System.out .print("fa tal, ");
  1831                    } el se if (lev el == Aler ts.alert_w arning) {
  1832                         System.out .print("wa rning, ");
  1833                    } el se {
  1834                         System.out .print("<l evel = " +  (0x0ff &  level) + " >, ");
  1835                    }
  1836                    Syst em.out.pri ntln("desc ription =  "
  1837                             + Aler ts.alertDe scription( descriptio n));
  1838                }
  1839           }
  1840  
  1841           r. write(leve l);
  1842           r. write(desc ription);
  1843           tr y {
  1844                writeRec ord(r);
  1845           }  catch (IOE xception e ) {
  1846                if (useD ebug) {
  1847                    Syst em.out.pri ntln(Threa d.currentT hread().ge tName() +
  1848                         ", Excepti on sending  alert: "  + e);
  1849                }
  1850           }
  1851       }
  1852  
  1853  
  1854       //
  1855       // VAR IOUS OTHER  METHODS ( COMMON TO  SSLSocket)
  1856       //
  1857  
  1858  
  1859       /**
  1860        * Con trols whet her new co nnections  may cause  creation o f new SSL
  1861        * ses sions.
  1862        *
  1863        * As  long as ha ndshaking  has not st arted, we  can change
  1864        * whe ther we en able sessi on creatio ns.  Other wise,
  1865        * we  will need  to wait fo r the next  handshake .
  1866        */
  1867       @Overr ide
  1868       synchr onized pub lic void s etEnableSe ssionCreat ion(boolea n flag) {
  1869           en ableSessio nCreation  = flag;
  1870  
  1871           if  ((handsha ker != nul l) && !han dshaker.ac tivated())  {
  1872                handshak er.setEnab leSessionC reation(en ableSessio nCreation) ;
  1873           }
  1874       }
  1875  
  1876       /**
  1877        * Ret urns true  if new con nections m ay cause c reation of  new SSL
  1878        * ses sions.
  1879        */
  1880       @Overr ide
  1881       synchr onized pub lic boolea n getEnabl eSessionCr eation() {
  1882           re turn enabl eSessionCr eation;
  1883       }
  1884  
  1885  
  1886       /**
  1887        * Set s the flag  controlli ng whether  a server  mode engin e
  1888        * *RE QUIRES* SS L client a uthenticat ion.
  1889        *
  1890        * As  long as ha ndshaking  has not st arted, we  can change
  1891        * whe ther clien t authenti cation is  needed.  O therwise,
  1892        * we  will need  to wait fo r the next  handshake .
  1893        */
  1894       @Overr ide
  1895       synchr onized pub lic void s etNeedClie ntAuth(boo lean flag)  {
  1896           do ClientAuth  = (flag ?
  1897                SSLEngin eImpl.clau th_require d : SSLEng ineImpl.cl auth_none) ;
  1898  
  1899           if  ((handsha ker != nul l) &&
  1900                    (han dshaker in stanceof S erverHands haker) &&
  1901                    !han dshaker.ac tivated())  {
  1902                ((Server Handshaker ) handshak er).setCli entAuth(do ClientAuth );
  1903           }
  1904       }
  1905  
  1906       @Overr ide
  1907       synchr onized pub lic boolea n getNeedC lientAuth( ) {
  1908           re turn (doCl ientAuth = = SSLEngin eImpl.clau th_require d);
  1909       }
  1910  
  1911       /**
  1912        * Set s the flag  controlli ng whether  a server  mode engin e
  1913        * *RE QUESTS* SS L client a uthenticat ion.
  1914        *
  1915        * As  long as ha ndshaking  has not st arted, we  can change
  1916        * whe ther clien t authenti cation is  requested.   Otherwis e,
  1917        * we  will need  to wait fo r the next  handshake .
  1918        */
  1919       @Overr ide
  1920       synchr onized pub lic void s etWantClie ntAuth(boo lean flag)  {
  1921           do ClientAuth  = (flag ?
  1922                SSLEngin eImpl.clau th_request ed : SSLEn gineImpl.c lauth_none );
  1923  
  1924           if  ((handsha ker != nul l) &&
  1925                    (han dshaker in stanceof S erverHands haker) &&
  1926                    !han dshaker.ac tivated())  {
  1927                ((Server Handshaker ) handshak er).setCli entAuth(do ClientAuth );
  1928           }
  1929       }
  1930  
  1931       @Overr ide
  1932       synchr onized pub lic boolea n getWantC lientAuth( ) {
  1933           re turn (doCl ientAuth = = SSLEngin eImpl.clau th_request ed);
  1934       }
  1935  
  1936  
  1937       /**
  1938        * Set s the flag  controlli ng whether  the engin e is in SS L
  1939        * cli ent or ser ver mode.   Must be c alled befo re any SSL
  1940        * tra ffic has s tarted.
  1941        */
  1942       @Overr ide
  1943       @Suppr essWarning s("fallthr ough")
  1944       synchr onized pub lic void s etUseClien tMode(bool ean flag)  {
  1945           sw itch (conn ectionStat e) {
  1946  
  1947           ca se cs_STAR T:
  1948                /*
  1949                 * If we  need to c hange the  engine mod e and the  enabled
  1950                 * proto cols haven 't specifi cally been  set by th e user,
  1951                 * chang e them to  the corres ponding de fault ones .
  1952                 */
  1953                if (role IsServer ! = (!flag)  &&
  1954                         sslContext .isDefault ProtocolLi st(enabled Protocols) ) {
  1955                    enab ledProtoco ls = sslCo ntext.getD efaultProt ocolList(! flag);
  1956                }
  1957  
  1958                roleIsSe rver = !fl ag;
  1959                serverMo deSet = tr ue;
  1960                break;
  1961  
  1962           ca se cs_HAND SHAKE:
  1963                /*
  1964                 * If we  have a ha ndshaker,  but haven' t started
  1965                 * SSL t raffic, we  can throw  away our  current
  1966                 * hands haker, and  start fro m scratch.   Don't
  1967                 * need  to call do neConnect( ) again, w e already
  1968                 * have  the stream s.
  1969                 */
  1970                assert(h andshaker  != null);
  1971                if (!han dshaker.ac tivated())  {
  1972                    /*
  1973                     * I f we need  to change  the engine  mode and  the enable d
  1974                     * p rotocols h aven't spe cifically  been set b y the user ,
  1975                     * c hange them  to the co rrespondin g default  ones.
  1976                     */
  1977                    if ( roleIsServ er != (!fl ag) &&
  1978                             sslCon text.isDef aultProtoc olList(ena bledProtoc ols)) {
  1979                         enabledPro tocols = s slContext. getDefault ProtocolLi st(!flag);
  1980                    }
  1981  
  1982                    role IsServer =  !flag;
  1983                    conn ectionStat e = cs_STA RT;
  1984                    init Handshaker ();
  1985                    brea k;
  1986                }
  1987  
  1988                // If ha ndshake ha s started,  that's an  error.  F all throug h...
  1989  
  1990           de fault:
  1991                if (debu g != null  && Debug.i sOn("ssl") ) {
  1992                    Syst em.out.pri ntln(Threa d.currentT hread().ge tName() +
  1993                         ", setUseC lientMode( ) invoked  in state =  " +
  1994                         connection State);
  1995                }
  1996  
  1997                /*
  1998                 * We ca n let them  continue  if they ca tch this c orrectly,
  1999                 * we do n't need t o shut thi s down.
  2000                 */
  2001                throw ne w IllegalA rgumentExc eption(
  2002                    "Can not change  mode afte r SSL traf fic has st arted");
  2003           }
  2004       }
  2005  
  2006       @Overr ide
  2007       synchr onized pub lic boolea n getUseCl ientMode()  {
  2008           re turn !role IsServer;
  2009       }
  2010  
  2011  
  2012       /**
  2013        * Ret urns the n ames of th e cipher s uites whic h could be  enabled f or use
  2014        * on  an SSL con nection.   Normally,  only a sub set of the se will ac tually
  2015        * be  enabled by  default,  since this  list may  include ci pher suite s which
  2016        * do  not suppor t the mutu al authent ication of  servers a nd clients , or
  2017        * whi ch do not  protect da ta confide ntiality.   Servers m ay also ne ed
  2018        * cer tain kinds  of certif icates to  use certai n cipher s uites.
  2019        *
  2020        * @re turn an ar ray of cip her suite  names
  2021        */
  2022       @Overr ide
  2023       public  String[]  getSupport edCipherSu ites() {
  2024           re turn sslCo ntext.getS upportedCi pherSuiteL ist().toSt ringArray( );
  2025       }
  2026  
  2027       /**
  2028        * Con trols whic h particul ar cipher  suites are  enabled f or use on
  2029        * thi s connecti on.  The c ipher suit es must ha ve been li sted by
  2030        * get CipherSuit es() as be ing suppor ted.  Even  if a suit e has been
  2031        * ena bled, it m ight never  be used i f no peer  supports i t or the
  2032        * req uisite cer tificates  (and priva te keys) a re not ava ilable.
  2033        *
  2034        * @pa ram suites  Names of  all the ci pher suite s to enabl e.
  2035        */
  2036       @Overr ide
  2037       synchr onized pub lic void s etEnabledC ipherSuite s(String[]  suites) {
  2038           en abledCiphe rSuites =  new Cipher SuiteList( suites);
  2039           if  ((handsha ker != nul l) && !han dshaker.ac tivated())  {
  2040                handshak er.setEnab ledCipherS uites(enab ledCipherS uites);
  2041           }
  2042       }
  2043  
  2044       /**
  2045        * Ret urns the n ames of th e SSL ciph er suites  which are  currently  enabled
  2046        * for  use on th is connect ion.  When  an SSL en gine is fi rst create d,
  2047        * all  enabled c ipher suit es <em>(a) </em> prot ect data c onfidentia lity,
  2048        * by  traffic en cryption,  and <em>(b )</em> can  mutually  authentica te
  2049        * bot h clients  and server s.  Thus,  in some en vironments , this val ue
  2050        * mig ht be empt y.
  2051        *
  2052        * @re turn an ar ray of cip her suite  names
  2053        */
  2054       @Overr ide
  2055       synchr onized pub lic String [] getEnab ledCipherS uites() {
  2056           re turn enabl edCipherSu ites.toStr ingArray() ;
  2057       }
  2058  
  2059  
  2060       /**
  2061        * Ret urns the p rotocols t hat are su pported by  this impl ementation .
  2062        * A s ubset of t he support ed protoco ls may be  enabled fo r this con nection
  2063        * @re turn an ar ray of pro tocol name s.
  2064        */
  2065       @Overr ide
  2066       public  String[]  getSupport edProtocol s() {
  2067           re turn sslCo ntext.getS uportedPro tocolList( ).toString Array();
  2068       }
  2069  
  2070       /**
  2071        * Con trols whic h protocol s are enab led for us e on
  2072        * thi s connecti on.  The p rotocols m ust have b een listed  by
  2073        * get SupportedP rotocols()  as being  supported.
  2074        *
  2075        * @pa ram protoc ols protoc ols to ena ble.
  2076        * @ex ception Il legalArgum entExcepti on when on e of the p rotocols
  2077        *  na med by the  parameter  is not su pported.
  2078        */
  2079       @Overr ide
  2080       synchr onized pub lic void s etEnabledP rotocols(S tring[] pr otocols) {
  2081           en abledProto cols = new  ProtocolL ist(protoc ols);
  2082           if  ((handsha ker != nul l) && !han dshaker.ac tivated())  {
  2083                handshak er.setEnab ledProtoco ls(enabled Protocols) ;
  2084           }
  2085       }
  2086  
  2087       @Overr ide
  2088       synchr onized pub lic String [] getEnab ledProtoco ls() {
  2089           re turn enabl edProtocol s.toString Array();
  2090       }
  2091  
  2092       /**
  2093        * Ret urns the S SLParamete rs in effe ct for thi s SSLEngin e.
  2094        */
  2095       @Overr ide
  2096       synchr onized pub lic SSLPar ameters ge tSSLParame ters() {
  2097           SS LParameter s params =  super.get SSLParamet ers();
  2098  
  2099           //  the super  implement ation does  not handl e the foll owing para meters
  2100           pa rams.setEn dpointIden tification Algorithm( identifica tionProtoc ol);
  2101           pa rams.setAl gorithmCon straints(a lgorithmCo nstraints) ;
  2102           pa rams.setSN IMatchers( sniMatcher s);
  2103           pa rams.setSe rverNames( serverName s);
  2104           pa rams.setUs eCipherSui tesOrder(p referLocal CipherSuit es);
  2105  
  2106           re turn param s;
  2107       }
  2108  
  2109       /**
  2110        * App lies SSLPa rameters t o this eng ine.
  2111        */
  2112       @Overr ide
  2113       synchr onized pub lic void s etSSLParam eters(SSLP arameters  params) {
  2114           su per.setSSL Parameters (params);
  2115  
  2116           //  the super  implement ation does  not handl e the foll owing para meters
  2117           id entificati onProtocol  = params. getEndpoin tIdentific ationAlgor ithm();
  2118           al gorithmCon straints =  params.ge tAlgorithm Constraint s();
  2119           pr eferLocalC ipherSuite s = params .getUseCip herSuitesO rder();
  2120  
  2121           Li st<SNIServ erName> sn iNames = p arams.getS erverNames ();
  2122           if  (sniNames  != null)  {
  2123                serverNa mes = sniN ames;
  2124           }
  2125  
  2126           Co llection<S NIMatcher>  matchers  = params.g etSNIMatch ers();
  2127           if  (matchers  != null)  {
  2128                sniMatch ers = matc hers;
  2129           }
  2130  
  2131           if  ((handsha ker != nul l) && !han dshaker.st arted()) {
  2132                handshak er.setIden tification Protocol(i dentificat ionProtoco l);
  2133                handshak er.setAlgo rithmConst raints(alg orithmCons traints);
  2134                if (role IsServer)  {
  2135                    hand shaker.set SNIMatcher s(sniMatch ers);
  2136                    hand shaker.set UseCipherS uitesOrder (preferLoc alCipherSu ites);
  2137                } else {
  2138                    hand shaker.set SNIServerN ames(serve rNames);
  2139                }
  2140           }
  2141       }
  2142  
  2143       /*
  2144        * Ret urns a boo lean indic ating whet her the Ch angeCipher Spec messa ge
  2145        * has  been rece ived for t his handsh ake.
  2146        */
  2147       boolea n received ChangeCiph erSpec() {
  2148           re turn recei vedCCS;
  2149       }
  2150  
  2151       /**
  2152        * Ret urns a pri ntable rep resentatio n of this  end of the  connectio n.
  2153        */
  2154       @Overr ide
  2155       public  String to String() {
  2156           St ringBuilde r retval =  new Strin gBuilder(8 0);
  2157  
  2158           re tval.appen d(Integer. toHexStrin g(hashCode ()));
  2159           re tval.appen d("[");
  2160           re tval.appen d("SSLEngi ne[hostnam e=");
  2161           St ring host  = getPeerH ost();
  2162           re tval.appen d((host ==  null) ? " null" : ho st);
  2163           re tval.appen d(" port=" );
  2164           re tval.appen d(Integer. toString(g etPeerPort ()));
  2165           re tval.appen d("] ");
  2166           re tval.appen d(getSessi on().getCi pherSuite( ));
  2167           re tval.appen d("]");
  2168  
  2169           re turn retva l.toString ();
  2170       }
  2171   }