213. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 9/25/2018 2:13:13 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.

213.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\nio\ch SocketChannelImpl.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\nio\ch SocketChannelImpl.java Wed Sep 12 17:45:58 2018 UTC

213.2 Comparison summary

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

213.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

213.4 Active regular expressions

No regular expressions were active.

213.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 200 0, 2013, 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.nio.ch;
  27  
  28   import jav a.io.FileD escriptor;
  29   import jav a.io.IOExc eption;
  30   import jav a.net.*;
  31   import jav a.nio.Byte Buffer;
  32   import jav a.nio.chan nels.*;
  33   import jav a.nio.chan nels.spi.* ;
  34   import jav a.util.*;
  35   import sun .net.NetHo oks;
  36   import sun .net.Exten dedOptions Impl;
  37  
  38  
  39   /**
  40    * An impl ementation  of Socket Channels
  41    */
  42  
  43   class Sock etChannelI mpl
  44       extend s SocketCh annel
  45       implem ents SelCh Impl
  46   {
  47  
  48       // Use d to make  native rea d and writ e calls
  49       privat e static N ativeDispa tcher nd;
  50  
  51       // Our  file desc riptor obj ect
  52       privat e final Fi leDescript or fd;
  53  
  54       // fd  value need ed for dev /poll. Thi s value wi ll remain  valid
  55       // eve n after th e value in  the file  descriptor  object ha s been set  to -1
  56       privat e final in t fdVal;
  57  
  58       // IDs  of native  threads d oing reads  and write s, for sig nalling
  59       privat e volatile  long read erThread =  0;
  60       privat e volatile  long writ erThread =  0;
  61  
  62       // Loc k held by  current re ading or c onnecting  thread
  63       privat e final Ob ject readL ock = new  Object();
  64  
  65       // Loc k held by  current wr iting or c onnecting  thread
  66       privat e final Ob ject write Lock = new  Object();
  67  
  68       // Loc k held by  any thread  that modi fies the s tate field s declared  below
  69       // DO  NOT invoke  a blockin g I/O oper ation whil e holding  this lock!
  70       privat e final Ob ject state Lock = new  Object();
  71  
  72       // --  The follow ing fields  are prote cted by st ateLock
  73  
  74       // set  true when  exclusive  binding i s on and S O_REUSEADD R is emula ted
  75       privat e boolean  isReuseAdd ress;
  76  
  77       // Sta te, increa ses monoto nically
  78       privat e static f inal int S T_UNINITIA LIZED = -1 ;
  79       privat e static f inal int S T_UNCONNEC TED = 0;
  80       privat e static f inal int S T_PENDING  = 1;
  81       privat e static f inal int S T_CONNECTE D = 2;
  82       privat e static f inal int S T_KILLPEND ING = 3;
  83       privat e static f inal int S T_KILLED =  4;
  84       privat e int stat e = ST_UNI NITIALIZED ;
  85  
  86       // Bin ding
  87       privat e InetSock etAddress  localAddre ss;
  88       privat e InetSock etAddress  remoteAddr ess;
  89  
  90       // Inp ut/Output  open
  91       privat e boolean  isInputOpe n = true;
  92       privat e boolean  isOutputOp en = true;
  93       privat e boolean  readyToCon nect = fal se;
  94  
  95       // Soc ket adapto r, created  on demand
  96       privat e Socket s ocket;
  97  
  98       // --  End of fie lds protec ted by sta teLock
  99  
  100  
  101       // Con structor f or normal  connecting  sockets
  102       //
  103       Socket ChannelImp l(Selector Provider s p) throws  IOExceptio n {
  104           su per(sp);
  105           th is.fd = Ne t.socket(t rue);
  106           th is.fdVal =  IOUtil.fd Val(fd);
  107           th is.state =  ST_UNCONN ECTED;
  108       }
  109  
  110       Socket ChannelImp l(Selector Provider s p,
  111                           FileDesc riptor fd,
  112                           boolean  bound)
  113           th rows IOExc eption
  114       {
  115           su per(sp);
  116           th is.fd = fd ;
  117           th is.fdVal =  IOUtil.fd Val(fd);
  118           th is.state =  ST_UNCONN ECTED;
  119           if  (bound)
  120                this.loc alAddress  = Net.loca lAddress(f d);
  121       }
  122  
  123       // Con structor f or sockets  obtained  from serve r sockets
  124       //
  125       Socket ChannelImp l(Selector Provider s p,
  126                           FileDesc riptor fd,  InetSocke tAddress r emote)
  127           th rows IOExc eption
  128       {
  129           su per(sp);
  130           th is.fd = fd ;
  131           th is.fdVal =  IOUtil.fd Val(fd);
  132           th is.state =  ST_CONNEC TED;
  133           th is.localAd dress = Ne t.localAdd ress(fd);
  134           th is.remoteA ddress = r emote;
  135       }
  136  
  137       public  Socket so cket() {
  138           sy nchronized  (stateLoc k) {
  139                if (sock et == null )
  140                    sock et = Socke tAdaptor.c reate(this );
  141                return s ocket;
  142           }
  143       }
  144  
  145       @Overr ide
  146       public  SocketAdd ress getLo calAddress () throws  IOExceptio n {
  147           sy nchronized  (stateLoc k) {
  148                if (!isO pen())
  149                    thro w new Clos edChannelE xception() ;
  150                return   Net.getRev ealedLocal Address(lo calAddress );
  151           }
  152       }
  153  
  154       @Overr ide
  155       public  SocketAdd ress getRe moteAddres s() throws  IOExcepti on {
  156           sy nchronized  (stateLoc k) {
  157                if (!isO pen())
  158                    thro w new Clos edChannelE xception() ;
  159                return r emoteAddre ss;
  160           }
  161       }
  162  
  163       @Overr ide
  164       public  <T> Socke tChannel s etOption(S ocketOptio n<T> name,  T value)
  165           th rows IOExc eption
  166       {
  167           if  (name ==  null)
  168                throw ne w NullPoin terExcepti on();
  169           if  (!support edOptions( ).contains (name))
  170                throw ne w Unsuppor tedOperati onExceptio n("'" + na me + "' no t supporte d");
  171  
  172           sy nchronized  (stateLoc k) {
  173                if (!isO pen())
  174                    thro w new Clos edChannelE xception() ;
  175  
  176                if (name  == Standa rdSocketOp tions.IP_T OS) {
  177                    Prot ocolFamily  family =  Net.isIPv6 Available( ) ?
  178                         StandardPr otocolFami ly.INET6 :  StandardP rotocolFam ily.INET;
  179                    Net. setSocketO ption(fd,  family, na me, value) ;
  180                    retu rn this;
  181                }
  182  
  183                if (name  == Standa rdSocketOp tions.SO_R EUSEADDR & & Net.useE xclusiveBi nd()) {
  184                    // S O_REUSEADD R emulated  when usin g exclusiv e bind
  185                    isRe useAddress  = (Boolea n)value;
  186                    retu rn this;
  187                }
  188  
  189                // no op tions that  require s pecial han dling
  190                Net.setS ocketOptio n(fd, Net. UNSPEC, na me, value) ;
  191                return t his;
  192           }
  193       }
  194  
  195       @Overr ide
  196       @Suppr essWarning s("uncheck ed")
  197       public  <T> T get Option(Soc ketOption< T> name)
  198           th rows IOExc eption
  199       {
  200           if  (name ==  null)
  201                throw ne w NullPoin terExcepti on();
  202           if  (!support edOptions( ).contains (name))
  203                throw ne w Unsuppor tedOperati onExceptio n("'" + na me + "' no t supporte d");
  204  
  205           sy nchronized  (stateLoc k) {
  206                if (!isO pen())
  207                    thro w new Clos edChannelE xception() ;
  208  
  209                if (name  == Standa rdSocketOp tions.SO_R EUSEADDR & &
  210                         Net.useExc lusiveBind ())
  211                {
  212                    // S O_REUSEADD R emulated  when usin g exclusiv e bind
  213                    retu rn (T)Bool ean.valueO f(isReuseA ddress);
  214                }
  215  
  216                // speci al handlin g for IP_T OS: always  return 0  when IPv6
  217                if (name  == Standa rdSocketOp tions.IP_T OS) {
  218                    Prot ocolFamily  family =  Net.isIPv6 Available( ) ?
  219                         StandardPr otocolFami ly.INET6 :  StandardP rotocolFam ily.INET;
  220                    retu rn (T) Net .getSocket Option(fd,  family, n ame);
  221                }
  222  
  223                // no op tions that  require s pecial han dling
  224                return ( T) Net.get SocketOpti on(fd, Net .UNSPEC, n ame);
  225           }
  226       }
  227  
  228       privat e static c lass Defau ltOptionsH older {
  229           st atic final  Set<Socke tOption<?> > defaultO ptions = d efaultOpti ons();
  230  
  231           pr ivate stat ic Set<Soc ketOption< ?>> defaul tOptions()  {
  232                HashSet< SocketOpti on<?>> set  = new Has hSet<Socke tOption<?> >(8);
  233                set.add( StandardSo cketOption s.SO_SNDBU F);
  234                set.add( StandardSo cketOption s.SO_RCVBU F);
  235                set.add( StandardSo cketOption s.SO_KEEPA LIVE);
  236                set.add( StandardSo cketOption s.SO_REUSE ADDR);
  237                set.add( StandardSo cketOption s.SO_LINGE R);
  238                set.add( StandardSo cketOption s.TCP_NODE LAY);
  239                // addit ional opti ons requir ed by sock et adaptor
  240                set.add( StandardSo cketOption s.IP_TOS);
  241                set.add( ExtendedSo cketOption .SO_OOBINL INE);
  242                if (Exte ndedOption sImpl.flow Supported( )) {
  243                    set. add(jdk.ne t.Extended SocketOpti ons.SO_FLO W_SLA);
  244                }
  245                return C ollections .unmodifia bleSet(set );
  246           }
  247       }
  248  
  249       @Overr ide
  250       public  final Set <SocketOpt ion<?>> su pportedOpt ions() {
  251           re turn Defau ltOptionsH older.defa ultOptions ;
  252       }
  253  
  254       privat e boolean  ensureRead Open() thr ows Closed ChannelExc eption {
  255           sy nchronized  (stateLoc k) {
  256                if (!isO pen())
  257                    thro w new Clos edChannelE xception() ;
  258                if (!isC onnected() )
  259                    thro w new NotY etConnecte dException ();
  260                if (!isI nputOpen)
  261                    retu rn false;
  262                else
  263                    retu rn true;
  264           }
  265       }
  266  
  267       privat e void ens ureWriteOp en() throw s ClosedCh annelExcep tion {
  268           sy nchronized  (stateLoc k) {
  269                if (!isO pen())
  270                    thro w new Clos edChannelE xception() ;
  271                if (!isO utputOpen)
  272                    thro w new Clos edChannelE xception() ;
  273                if (!isC onnected() )
  274                    thro w new NotY etConnecte dException ();
  275           }
  276       }
  277  
  278       privat e void rea derCleanup () throws  IOExceptio n {
  279           sy nchronized  (stateLoc k) {
  280                readerTh read = 0;
  281                if (stat e == ST_KI LLPENDING)
  282                    kill ();
  283           }
  284       }
  285  
  286       privat e void wri terCleanup () throws  IOExceptio n {
  287           sy nchronized  (stateLoc k) {
  288                writerTh read = 0;
  289                if (stat e == ST_KI LLPENDING)
  290                    kill ();
  291           }
  292       }
  293  
  294       public  int read( ByteBuffer  buf) thro ws IOExcep tion {
  295  
  296           if  (buf == n ull)
  297                throw ne w NullPoin terExcepti on();
  298  
  299           sy nchronized  (readLock ) {
  300                if (!ens ureReadOpe n())
  301                    retu rn -1;
  302                int n =  0;
  303                try {
  304  
  305                    // S et up the  interrupti on machine ry; see
  306                    // A bstractInt erruptible Channel fo r details
  307                    //
  308                    begi n();
  309  
  310                    sync hronized ( stateLock)  {
  311                         if (!isOpe n()) {
  312                         // Either  the curren t thread i s already  interrupte d, so
  313                         // begin()  closed th e channel,  or anothe r thread c losed the
  314                         // channel  since we  checked it  a few byt ecodes ago .  In
  315                         // either  case the v alue retur ned here i s irreleva nt since
  316                         // the inv ocation of  end() in  the finall y block wi ll throw
  317                         // an appr opriate ex ception.
  318                         //
  319                             return  0;
  320  
  321                         }
  322  
  323                         // Save th is thread  so that it  can be si gnalled on  those
  324                         // platfor ms that re quire it
  325                         //
  326                         readerThre ad = Nativ eThread.cu rrent();
  327                    }
  328  
  329                    // B etween the  previous  test of is Open() and  the retur n of the
  330                    // I OUtil.read  invocatio n below, t his channe l might be  closed
  331                    // o r this thr ead might  be interru pted.  We  rely upon  the
  332                    // i mplicit sy nchronizat ion point  in the ker nel read()  call to
  333                    // m ake sure t hat the ri ght thing  happens.   In either  case the
  334                    // i mplCloseSe lectableCh annel meth od is ulti mately inv oked in
  335                    // s ome other  thread, so  there are  three pos sibilities :
  336                    //
  337                    //    - implClo seSelectab leChannel( ) invokes  nd.preClos e()
  338                    //      before  this threa d invokes  read(), in  which cas e the
  339                    //      read re turns imme diately wi th either  EOF or an  error,
  340                    //      the lat ter of whi ch will ca use an IOE xception t o be
  341                    //      thrown.
  342                    //
  343                    //    - implClo seSelectab leChannel( ) invokes  nd.preClos e() after
  344                    //      this th read is bl ocked in r ead().  On  some oper ating
  345                    //      systems  (e.g., So laris and  Windows) t his causes  the read
  346                    //      to retu rn immedia tely with  either EOF  or an err or
  347                    //      indicat ion.
  348                    //
  349                    //    - implClo seSelectab leChannel( ) invokes  nd.preClos e() after
  350                    //      this th read is bl ocked in r ead() but  the operat ing
  351                    //      system  (e.g., Lin ux) doesn' t support  preemptive  close,
  352                    //      so impl CloseSelec tableChann el() proce eds to sig nal this
  353                    //      thread,  thereby c ausing the  read to r eturn imme diately
  354                    //      with IO Status.INT ERRUPTED.
  355                    //
  356                    // I n all thre e cases th e invocati on of end( ) in the f inally
  357                    // c lause will  notice th at the cha nnel has b een closed  and
  358                    // t hrow an ap propriate  exception  (Asynchron ousCloseEx ception
  359                    // o r ClosedBy InterruptE xception)  if necessa ry.
  360                    //
  361                    // * There is A  fourth po ssibility.  implClose Selectable Channel()
  362                    // i nvokes nd. preClose() , signals  reader/wri ter thred  and quickl y
  363                    // m oves on to  nd.close( ) in kill( ), which d oes a real  close.
  364                    // T hen a thir d thread a ccepts a n ew connect ion, opens  file or
  365                    // w hatever th at causes  the releas ed "fd" to  be recycl ed. All
  366                    // a bove happe ns just be tween our  last isOpe n() check  and the
  367                    // n ext kernel  read reac hed, with  the recycl ed "fd". T he solutio n
  368                    // i s to postp one the re al kill()  if there i s a reader  or/and
  369                    // w riter thre ad(s) over  there "wa iting", le ave the cl eanup/kill
  370                    // t o the read er or writ er thread.  (the preC lose() sti ll happens
  371                    // s o the conn ection get s cut off  as usual).
  372                    //
  373                    // F or socket  channels t here is th e addition al wrinkle  that
  374                    // a synchronou s shutdown  works muc h like asy nchronous  close,
  375                    // e xcept that  the chann el is shut down rathe r than com pletely
  376                    // c losed.  Th is is anal ogous to t he first t wo cases a bove,
  377                    // e xcept that  the shutd own operat ion plays  the role o f
  378                    // n d.preClose ().
  379                    for  (;;) {
  380                         n = IOUtil .read(fd,  buf, -1, n d);
  381                         if ((n ==  IOStatus.I NTERRUPTED ) && isOpe n()) {
  382                             // The  system ca ll was int errupted b ut the cha nnel
  383                             // is  still open , so retry
  384                             contin ue;
  385                         }
  386                         return IOS tatus.norm alize(n);
  387                    }
  388  
  389                } finall y {
  390                    read erCleanup( );         // Clear r eader thre ad
  391                    // T he end met hod, which  is define d in our s uperclass
  392                    // A bstractInt erruptible Channel, r esets the  interrupti on
  393                    // m achinery.   If its ar gument is  true then  it returns
  394                    // n ormally; o therwise i t checks t he interru pt and ope n state
  395                    // o f this cha nnel and t hrows an a ppropriate  exception  if
  396                    // n ecessary.
  397                    //
  398                    // S o, if we a ctually ma naged to d o any I/O  in the abo ve try
  399                    // b lock then  we pass tr ue to the  end method .  We also  pass
  400                    // t rue if the  channel w as in non- blocking m ode when t he I/O
  401                    // o peration w as initiat ed but no  data could  be transf erred;
  402                    // t his preven ts spuriou s exceptio ns from be ing thrown  in the
  403                    // r are event  that a cha nnel is cl osed or a  thread is
  404                    // i nterrupted  at the ex act moment  that a no n-blocking  I/O
  405                    // r equest is  made.
  406                    //
  407                    end( n > 0 || ( n == IOSta tus.UNAVAI LABLE));
  408  
  409                    // E xtra case  for socket  channels:  Asynchron ous shutdo wn
  410                    //
  411                    sync hronized ( stateLock)  {
  412                         if ((n <=  0) && (!is InputOpen) )
  413                             return  IOStatus. EOF;
  414                    }
  415  
  416                    asse rt IOStatu s.check(n) ;
  417  
  418                }
  419           }
  420       }
  421  
  422       public  long read (ByteBuffe r[] dsts,  int offset , int leng th)
  423           th rows IOExc eption
  424       {
  425           if  ((offset  < 0) || (l ength < 0)  || (offse t > dsts.l ength - le ngth))
  426                throw ne w IndexOut OfBoundsEx ception();
  427           sy nchronized  (readLock ) {
  428                if (!ens ureReadOpe n())
  429                    retu rn -1;
  430                long n =  0;
  431                try {
  432                    begi n();
  433                    sync hronized ( stateLock)  {
  434                         if (!isOpe n())
  435                             return  0;
  436                         readerThre ad = Nativ eThread.cu rrent();
  437                    }
  438  
  439                    for  (;;) {
  440                         n = IOUtil .read(fd,  dsts, offs et, length , nd);
  441                         if ((n ==  IOStatus.I NTERRUPTED ) && isOpe n())
  442                             contin ue;
  443                         return IOS tatus.norm alize(n);
  444                    }
  445                } finall y {
  446                    read erCleanup( );
  447                    end( n > 0 || ( n == IOSta tus.UNAVAI LABLE));
  448                    sync hronized ( stateLock)  {
  449                         if ((n <=  0) && (!is InputOpen) )
  450                             return  IOStatus. EOF;
  451                    }
  452                    asse rt IOStatu s.check(n) ;
  453                }
  454           }
  455       }
  456  
  457       public  int write (ByteBuffe r buf) thr ows IOExce ption {
  458           if  (buf == n ull)
  459                throw ne w NullPoin terExcepti on();
  460           sy nchronized  (writeLoc k) {
  461                ensureWr iteOpen();
  462                int n =  0;
  463                try {
  464                    begi n();
  465                    sync hronized ( stateLock)  {
  466                         if (!isOpe n())
  467                             return  0;
  468                         writerThre ad = Nativ eThread.cu rrent();
  469                    }
  470                    for  (;;) {
  471                         n = IOUtil .write(fd,  buf, -1,  nd);
  472                         if ((n ==  IOStatus.I NTERRUPTED ) && isOpe n())
  473                             contin ue;
  474                         return IOS tatus.norm alize(n);
  475                    }
  476                } finall y {
  477                    writ erCleanup( );
  478                    end( n > 0 || ( n == IOSta tus.UNAVAI LABLE));
  479                    sync hronized ( stateLock)  {
  480                         if ((n <=  0) && (!is OutputOpen ))
  481                             throw  new Asynch ronousClos eException ();
  482                    }
  483                    asse rt IOStatu s.check(n) ;
  484                }
  485           }
  486       }
  487  
  488       public  long writ e(ByteBuff er[] srcs,  int offse t, int len gth)
  489           th rows IOExc eption
  490       {
  491           if  ((offset  < 0) || (l ength < 0)  || (offse t > srcs.l ength - le ngth))
  492                throw ne w IndexOut OfBoundsEx ception();
  493           sy nchronized  (writeLoc k) {
  494                ensureWr iteOpen();
  495                long n =  0;
  496                try {
  497                    begi n();
  498                    sync hronized ( stateLock)  {
  499                         if (!isOpe n())
  500                             return  0;
  501                         writerThre ad = Nativ eThread.cu rrent();
  502                    }
  503                    for  (;;) {
  504                         n = IOUtil .write(fd,  srcs, off set, lengt h, nd);
  505                         if ((n ==  IOStatus.I NTERRUPTED ) && isOpe n())
  506                             contin ue;
  507                         return IOS tatus.norm alize(n);
  508                    }
  509                } finall y {
  510                    writ erCleanup( );
  511                    end( (n > 0) ||  (n == IOS tatus.UNAV AILABLE));
  512                    sync hronized ( stateLock)  {
  513                         if ((n <=  0) && (!is OutputOpen ))
  514                             throw  new Asynch ronousClos eException ();
  515                    }
  516                    asse rt IOStatu s.check(n) ;
  517                }
  518           }
  519       }
  520  
  521       // pac kage-priva te
  522       int se ndOutOfBan dData(byte  b) throws  IOExcepti on {
  523           sy nchronized  (writeLoc k) {
  524                ensureWr iteOpen();
  525                int n =  0;
  526                try {
  527                    begi n();
  528                    sync hronized ( stateLock)  {
  529                         if (!isOpe n())
  530                             return  0;
  531                         writerThre ad = Nativ eThread.cu rrent();
  532                    }
  533                    for  (;;) {
  534                         n = sendOu tOfBandDat a(fd, b);
  535                         if ((n ==  IOStatus.I NTERRUPTED ) && isOpe n())
  536                             contin ue;
  537                         return IOS tatus.norm alize(n);
  538                    }
  539                } finall y {
  540                    writ erCleanup( );
  541                    end( (n > 0) ||  (n == IOS tatus.UNAV AILABLE));
  542                    sync hronized ( stateLock)  {
  543                         if ((n <=  0) && (!is OutputOpen ))
  544                             throw  new Asynch ronousClos eException ();
  545                    }
  546                    asse rt IOStatu s.check(n) ;
  547                }
  548           }
  549       }
  550  
  551       protec ted void i mplConfigu reBlocking (boolean b lock) thro ws IOExcep tion {
  552           IO Util.confi gureBlocki ng(fd, blo ck);
  553       }
  554  
  555       public  InetSocke tAddress l ocalAddres s() {
  556           sy nchronized  (stateLoc k) {
  557                return l ocalAddres s;
  558           }
  559       }
  560  
  561       public  SocketAdd ress remot eAddress()  {
  562           sy nchronized  (stateLoc k) {
  563                return r emoteAddre ss;
  564           }
  565       }
  566  
  567       @Overr ide
  568       public  SocketCha nnel bind( SocketAddr ess local)  throws IO Exception  {
  569           sy nchronized  (readLock ) {
  570                synchron ized (writ eLock) {
  571                    sync hronized ( stateLock)  {
  572                         if (!isOpe n())
  573                             throw  new Closed ChannelExc eption();
  574                         if (state  == ST_PEND ING)
  575                             throw  new Connec tionPendin gException ();
  576                         if (localA ddress !=  null)
  577                             throw  new Alread yBoundExce ption();
  578                         InetSocket Address is a = (local  == null)  ?
  579                             new In etSocketAd dress(0) :  Net.check Address(lo cal);
  580                         SecurityMa nager sm =  System.ge tSecurityM anager();
  581                         if (sm !=  null) {
  582                             sm.che ckListen(i sa.getPort ());
  583                         }
  584                         NetHooks.b eforeTcpBi nd(fd, isa .getAddres s(), isa.g etPort());
  585                         Net.bind(f d, isa.get Address(),  isa.getPo rt());
  586                         localAddre ss = Net.l ocalAddres s(fd);
  587                    }
  588                }
  589           }
  590           re turn this;
  591       }
  592  
  593       public  boolean i sConnected () {
  594           sy nchronized  (stateLoc k) {
  595                return ( state == S T_CONNECTE D);
  596           }
  597       }
  598  
  599       public  boolean i sConnectio nPending()  {
  600           sy nchronized  (stateLoc k) {
  601                return ( state == S T_PENDING) ;
  602           }
  603       }
  604  
  605       void e nsureOpenA ndUnconnec ted() thro ws IOExcep tion { //  package-pr ivate
  606           sy nchronized  (stateLoc k) {
  607                if (!isO pen())
  608                    thro w new Clos edChannelE xception() ;
  609                if (stat e == ST_CO NNECTED)
  610                    thro w new Alre adyConnect edExceptio n();
  611                if (stat e == ST_PE NDING)
  612                    thro w new Conn ectionPend ingExcepti on();
  613           }
  614       }
  615  
  616       public  boolean c onnect(Soc ketAddress  sa) throw s IOExcept ion {
  617             int localP ORT      
;
  618  
  619           sy nchronized  (readLock ) {
  620                synchron ized (writ eLock) {
  621                    ensu reOpenAndU nconnected ();
  622                    Inet SocketAddr ess isa =  Net.checkA ddress(sa) ;
  623                    Secu rityManage r sm = Sys tem.getSec urityManag er();
  624                    if ( sm != null )
  625                         sm.checkCo nnect(isa. getAddress ().getHost Address(),
  626                                          isa. getPort()) ;
  627                    sync hronized ( blockingLo ck()) {
  628                         int n = 0;
  629                         try {
  630                             try {
  631                                 be gin();
  632                                 sy nchronized  (stateLoc k) {
  633                                      if (!isO pen()) {
  634                                          retu rn false;
  635                                      }
  636                                      // notif y hook onl y if unbou nd
  637                                      if (loca lAddress = = null) {
  638                                          NetH ooks.befor eTcpConnec t(fd,
  639                                                                   i sa.getAddr ess(),
  640                                                                   i sa.getPort ());
  641                                      }
  642                                      readerTh read = Nat iveThread. current();
  643                                 }
  644                                 fo r (;;) {
  645                                      InetAddr ess ia = i sa.getAddr ess();
  646                                      if (ia.i sAnyLocalA ddress())
  647                                          ia =  InetAddre ss.getLoca lHost();
  648                                      n = Net. connect(fd ,
  649                                                       ia ,
  650                                                       is a.getPort( ));
  651                                      if (  (n  == IOStat us.INTERRU PTED)
  652                                            &&  isOpen())
  653                                          cont inue;
  654                                      break;
  655                                 }
  656  
  657                             } fina lly {
  658                                 re aderCleanu p();
  659                                 en d((n > 0)  || (n == I OStatus.UN AVAILABLE) );
  660                                 as sert IOSta tus.check( n);
  661                             }
  662                         } catch (I OException  x) {
  663                             // If  an excepti on was thr own, close  the chann el after
  664                             // inv oking end( ) so as to  avoid bog us
  665                             // Asy nchronousC loseExcept ions
  666                             close( );
  667                             throw  x;
  668                         }
  669                         synchroniz ed (stateL ock) {
  670                             remote Address =  isa;
  671                             if (n  > 0) {
  672  
  673                                 //  Connectio n succeede d; disallo w further
  674                                 //  invocatio n
  675                                 st ate = ST_C ONNECTED;
  676                                 if  (isOpen() )
  677                                      localAdd ress = Net .localAddr ess(fd);
  678                                 re turn true;
  679                             }
  680                             // If  nonblockin g and no e xception t hen connec tion
  681                             // pen ding; disa llow anoth er invocat ion
  682                             if (!i sBlocking( ))
  683                                 st ate = ST_P ENDING;
  684                             else
  685                                 as sert false ;
  686                         }
  687                    }
  688                    retu rn false;
  689                }
  690           }
  691       }
  692  
  693       public  boolean f inishConne ct() throw s IOExcept ion {
  694           sy nchronized  (readLock ) {
  695                synchron ized (writ eLock) {
  696                    sync hronized ( stateLock)  {
  697                         if (!isOpe n())
  698                             throw  new Closed ChannelExc eption();
  699                         if (state  == ST_CONN ECTED)
  700                             return  true;
  701                         if (state  != ST_PEND ING)
  702                             throw  new NoConn ectionPend ingExcepti on();
  703                    }
  704                    int  n = 0;
  705                    try  {
  706                         try {
  707                             begin( );
  708                             synchr onized (bl ockingLock ()) {
  709                                 sy nchronized  (stateLoc k) {
  710                                      if (!isO pen()) {
  711                                          retu rn false;
  712                                      }
  713                                      readerTh read = Nat iveThread. current();
  714                                 }
  715                                 if  (!isBlock ing()) {
  716                                      for (;;)  {
  717                                          n =  checkConne ct(fd, fal se,
  718                                                             readyTo Connect);
  719                                          if (   (n == IO Status.INT ERRUPTED)
  720                                                 && isOpe n())
  721                                               continue;
  722                                          brea k;
  723                                      }
  724                                 }  else {
  725                                      for (;;)  {
  726                                          n =  checkConne ct(fd, tru e,
  727                                                             readyTo Connect);
  728                                          if ( n == 0) {
  729                                               // Loop in  case of
  730                                               // spuriou s notifica tions
  731                                               continue;
  732                                          }
  733                                          if (   (n == IO Status.INT ERRUPTED)
  734                                                 && isOpe n())
  735                                               continue;
  736                                          brea k;
  737                                      }
  738                                 }
  739                             }
  740                         } finally  {
  741                             synchr onized (st ateLock) {
  742                                 re aderThread  = 0;
  743                                 if  (state ==  ST_KILLPE NDING) {
  744                                      kill();
  745                                      // poll( )/getsocko pt() does  not report
  746                                      // error  (throws e xception,  with n = 0 )
  747                                      // on Li nux platfo rm after d up2 and
  748                                      // signa l-wakeup.  Force n to  0 so the
  749                                      // end()  can throw  appropria te excepti on
  750                                      n = 0;
  751                                 }
  752                             }
  753                             end((n  > 0) || ( n == IOSta tus.UNAVAI LABLE));
  754                             assert  IOStatus. check(n);
  755                         }
  756                    } ca tch (IOExc eption x)  {
  757                         // If an e xception w as thrown,  close the  channel a fter
  758                         // invokin g end() so  as to avo id bogus
  759                         // Asynchr onousClose Exceptions
  760                         close();
  761                         throw x;
  762                    }
  763                    if ( n > 0) {
  764                         synchroniz ed (stateL ock) {
  765                             state  = ST_CONNE CTED;
  766                             if (is Open())
  767                                 lo calAddress  = Net.loc alAddress( fd);
  768                         }
  769                         return tru e;
  770                    }
  771                    retu rn false;
  772                }
  773           }
  774       }
  775  
  776       @Overr ide
  777       public  SocketCha nnel shutd ownInput()  throws IO Exception  {
  778           sy nchronized  (stateLoc k) {
  779                if (!isO pen())
  780                    thro w new Clos edChannelE xception() ;
  781                if (!isC onnected() )
  782                    thro w new NotY etConnecte dException ();
  783                if (isIn putOpen) {
  784                    Net. shutdown(f d, Net.SHU T_RD);
  785                    if ( readerThre ad != 0)
  786                         NativeThre ad.signal( readerThre ad);
  787                    isIn putOpen =  false;
  788                }
  789                return t his;
  790           }
  791       }
  792  
  793       @Overr ide
  794       public  SocketCha nnel shutd ownOutput( ) throws I OException  {
  795           sy nchronized  (stateLoc k) {
  796                if (!isO pen())
  797                    thro w new Clos edChannelE xception() ;
  798                if (!isC onnected() )
  799                    thro w new NotY etConnecte dException ();
  800                if (isOu tputOpen)  {
  801                    Net. shutdown(f d, Net.SHU T_WR);
  802                    if ( writerThre ad != 0)
  803                         NativeThre ad.signal( writerThre ad);
  804                    isOu tputOpen =  false;
  805                }
  806                return t his;
  807           }
  808       }
  809  
  810       public  boolean i sInputOpen () {
  811           sy nchronized  (stateLoc k) {
  812                return i sInputOpen ;
  813           }
  814       }
  815  
  816       public  boolean i sOutputOpe n() {
  817           sy nchronized  (stateLoc k) {
  818                return i sOutputOpe n;
  819           }
  820       }
  821  
  822       // Abs tractInter ruptibleCh annel sync hronizes i nvocations  of this m ethod
  823       // usi ng Abstrac tInterrupt ibleChanne l.closeLoc k, and als o ensures  that this
  824       // met hod is onl y ever inv oked once.   Before w e get to t his method , isOpen
  825       // (wh ich is vol atile) wil l have bee n set to f alse.
  826       //
  827       protec ted void i mplCloseSe lectableCh annel() th rows IOExc eption {
  828           sy nchronized  (stateLoc k) {
  829                isInputO pen = fals e;
  830                isOutput Open = fal se;
  831  
  832                // Close  the under lying file  descripto r and dup  it to a kn own fd
  833                // that' s already  closed.  T his preven ts other o perations  on this
  834                // chann el from us ing the ol d fd, whic h might be  recycled  in the
  835                // meant ime and al located to  an entire ly differe nt channel .
  836                //
  837                if (stat e != ST_KI LLED)
  838                    nd.p reClose(fd );
  839  
  840                // Signa l native t hreads, if  needed.   If a targe t thread i s not
  841                // curre ntly block ed in an I /O operati on then no  harm is d one since
  842                // the s ignal hand ler doesn' t actually  do anythi ng.
  843                //
  844                if (read erThread ! = 0)
  845                    Nati veThread.s ignal(read erThread);
  846  
  847                if (writ erThread ! = 0)
  848                    Nati veThread.s ignal(writ erThread);
  849  
  850                // If th is channel  is not re gistered t hen it's s afe to clo se the fd
  851                // immed iately sin ce we know  at this p oint that  no thread  is
  852                // block ed in an I /O operati on upon th e channel  and, since  the
  853                // chann el is mark ed closed,  no thread  will star t another  such
  854                // opera tion.  If  this chann el is regi stered the n we don't  close
  855                // the f d since it  might be  in use by  a selector .  In that  case
  856                // closi ng this ch annel caus ed its key s to be ca ncelled, s o the
  857                // last  selector t o deregist er a key f or this ch annel will  invoke
  858                // kill( ) to close  the fd.
  859                //
  860                if (!isR egistered( ))
  861                    kill ();
  862           }
  863       }
  864  
  865       public  void kill () throws  IOExceptio n {
  866           sy nchronized  (stateLoc k) {
  867                if (stat e == ST_KI LLED)
  868                    retu rn;
  869                if (stat e == ST_UN INITIALIZE D) {
  870                    stat e = ST_KIL LED;
  871                    retu rn;
  872                }
  873                assert ! isOpen() & & !isRegis tered();
  874  
  875                // Postp one the ki ll if ther e is a wai ting reade r
  876                // or wr iter threa d. See the  comments  in read()  for
  877                // more  detailed e xplanation .
  878                if (read erThread = = 0 && wri terThread  == 0) {
  879                    nd.c lose(fd);
  880                    stat e = ST_KIL LED;
  881                } else {
  882                    stat e = ST_KIL LPENDING;
  883                }
  884           }
  885       }
  886  
  887       /**
  888        * Tra nslates na tive poll  revent ops  into a re ady operat ion ops
  889        */
  890       public  boolean t ranslateRe adyOps(int  ops, int  initialOps ,
  891                                           Sel ectionKeyI mpl sk) {
  892           in t intOps =  sk.nioInt erestOps() ; // Do th is just on ce, it syn chronizes
  893           in t oldOps =  sk.nioRea dyOps();
  894           in t newOps =  initialOp s;
  895  
  896           if  ((ops & N et.POLLNVA L) != 0) {
  897                // This  should onl y happen i f this cha nnel is pr e-closed w hile a
  898                // selec tion opera tion is in  progress
  899                // ## Th row an err or if this  channel h as not bee n pre-clos ed
  900                return f alse;
  901           }
  902  
  903           if  ((ops & ( Net.POLLER R | Net.PO LLHUP)) !=  0) {
  904                newOps =  intOps;
  905                sk.nioRe adyOps(new Ops);
  906                // No ne ed to poll  again in  checkConne ct,
  907                // the e rror will  be detecte d there
  908                readyToC onnect = t rue;
  909                return ( newOps & ~ oldOps) !=  0;
  910           }
  911  
  912           if  (((ops &  Net.POLLIN ) != 0) &&
  913                ((intOps  & Selecti onKey.OP_R EAD) != 0)  &&
  914                (state = = ST_CONNE CTED))
  915                newOps | = Selectio nKey.OP_RE AD;
  916  
  917           if  (((ops &  Net.POLLCO NN) != 0)  &&
  918                ((intOps  & Selecti onKey.OP_C ONNECT) !=  0) &&
  919                ((state  == ST_UNCO NNECTED) | | (state = = ST_PENDI NG))) {
  920                newOps | = Selectio nKey.OP_CO NNECT;
  921                readyToC onnect = t rue;
  922           }
  923  
  924           if  (((ops &  Net.POLLOU T) != 0) & &
  925                ((intOps  & Selecti onKey.OP_W RITE) != 0 ) &&
  926                (state = = ST_CONNE CTED))
  927                newOps | = Selectio nKey.OP_WR ITE;
  928  
  929           sk .nioReadyO ps(newOps) ;
  930           re turn (newO ps & ~oldO ps) != 0;
  931       }
  932  
  933       public  boolean t ranslateAn dUpdateRea dyOps(int  ops, Selec tionKeyImp l sk) {
  934           re turn trans lateReadyO ps(ops, sk .nioReadyO ps(), sk);
  935       }
  936  
  937       public  boolean t ranslateAn dSetReadyO ps(int ops , Selectio nKeyImpl s k) {
  938           re turn trans lateReadyO ps(ops, 0,  sk);
  939       }
  940  
  941       // pac kage-priva te
  942       int po ll(int eve nts, long  timeout) t hrows IOEx ception {
  943           as sert Threa d.holdsLoc k(blocking Lock()) &&  !isBlocki ng();
  944  
  945           sy nchronized  (readLock ) {
  946                int n =  0;
  947                try {
  948                    begi n();
  949                    sync hronized ( stateLock)  {
  950                         if (!isOpe n())
  951                             return  0;
  952                         readerThre ad = Nativ eThread.cu rrent();
  953                    }
  954                    n =  Net.poll(f d, events,  timeout);
  955                } finall y {
  956                    read erCleanup( );
  957                    end( n > 0);
  958                }
  959                return n ;
  960           }
  961       }
  962  
  963       /**
  964        * Tra nslates an  interest  operation  set into a  native po ll event s et
  965        */
  966       public  void tran slateAndSe tInterestO ps(int ops , Selectio nKeyImpl s k) {
  967           in t newOps =  0;
  968           if  ((ops & S electionKe y.OP_READ)  != 0)
  969                newOps | = Net.POLL IN;
  970           if  ((ops & S electionKe y.OP_WRITE ) != 0)
  971                newOps | = Net.POLL OUT;
  972           if  ((ops & S electionKe y.OP_CONNE CT) != 0)
  973                newOps | = Net.POLL CONN;
  974           sk .selector. putEventOp s(sk, newO ps);
  975       }
  976  
  977       public  FileDescr iptor getF D() {
  978           re turn fd;
  979       }
  980  
  981       public  int getFD Val() {
  982           re turn fdVal ;
  983       }
  984  
  985       @Overr ide
  986       public  String to String() {
  987           St ringBuffer  sb = new  StringBuff er();
  988           sb .append(th is.getClas s().getSup erclass(). getName()) ;
  989           sb .append('[ ');
  990           if  (!isOpen( ))
  991                sb.appen d("closed" );
  992           el se {
  993                synchron ized (stat eLock) {
  994                    swit ch (state)  {
  995                    case  ST_UNCONN ECTED:
  996                         sb.append( "unconnect ed");
  997                         break;
  998                    case  ST_PENDIN G:
  999                         sb.append( "connectio n-pending" );
  1000                         break;
  1001                    case  ST_CONNEC TED:
  1002                         sb.append( "connected ");
  1003                         if (!isInp utOpen)
  1004                             sb.app end(" ishu t");
  1005                         if (!isOut putOpen)
  1006                             sb.app end(" oshu t");
  1007                         break;
  1008                    }
  1009                    Inet SocketAddr ess addr =  localAddr ess();
  1010                    if ( addr != nu ll) {
  1011                         sb.append( " local=") ;
  1012                         sb.append( Net.getRev ealedLocal AddressAsS tring(addr ));
  1013                    }
  1014                    if ( remoteAddr ess() != n ull) {
  1015                         sb.append( " remote=" );
  1016                         sb.append( remoteAddr ess().toSt ring());
  1017                    }
  1018                }
  1019           }
  1020           sb .append('] ');
  1021           re turn sb.to String();
  1022       }
  1023  
  1024  
  1025       // --  Native met hods --
  1026  
  1027       privat e static n ative int  checkConne ct(FileDes criptor fd ,
  1028                                                  boolean  block, bo olean read y)
  1029           th rows IOExc eption;
  1030  
  1031       privat e static n ative int  sendOutOfB andData(Fi leDescript or fd, byt e data)
  1032           th rows IOExc eption;
  1033  
  1034       static  {
  1035           IO Util.load( );
  1036           nd  = new Soc ketDispatc her();
  1037       }
  1038  
  1039   }