121. EPMO Open Source Coordination Office Redaction File Detail Report

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

121.1 Files compared

# Location File Last Modified
1 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\com\sun\jndi\dns DnsClient.java Mon Jan 22 14:46:50 2018 UTC
2 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\com\sun\jndi\dns DnsClient.java Wed Sep 12 16:27:24 2018 UTC

121.2 Comparison summary

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

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

121.4 Active regular expressions

No regular expressions were active.

121.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 200 0, 2015, 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 co m.sun.jndi .dns;
  27  
  28   import jav a.io.IOExc eption;
  29   import jav a.net.Data gramSocket ;
  30   import jav a.net.Data gramPacket ;
  31   import jav a.net.Inet Address;
  32   import jav a.net.Sock et;
  33   import jav a.security .SecureRan dom;
  34   import jav ax.naming. *;
  35  
  36   import jav a.util.Col lections;
  37   import jav a.util.Map ;
  38   import jav a.util.Has hMap;
  39  
  40   import sun .security. jca.JCAUti l;
  41  
  42   // Some of  this code  began lif e as part  of sun.jav aos.net.Dn sClient
  43   // origina lly by sri tchie@eng  1/96.  It  was first  hacked up  for JNDI
  44   // use by  caveh@eng  6/97.
  45  
  46  
  47   /**
  48    * The Dns Client cla ss perform s DNS clie nt operati ons in sup port of Dn sContext.
  49    *
  50    */
  51  
  52   public cla ss DnsClie nt {
  53  
  54       // DNS  packet he ader field  offsets
  55       privat e static f inal int I DENT_OFFSE T = 0;
  56       privat e static f inal int F LAGS_OFFSE T = 2;
  57       privat e static f inal int N UMQ_OFFSET   = 4;
  58       privat e static f inal int N UMANS_OFFS ET = 6;
  59       privat e static f inal int N UMAUTH_OFF SET = 8;
  60       privat e static f inal int N UMADD_OFFS ET = 10;
  61       privat e static f inal int D NS_HDR_SIZ E = 12;
  62  
  63       // DNS  response  codes
  64       privat e static f inal int N O_ERROR        = 0;
  65       privat e static f inal int F ORMAT_ERRO R   = 1;
  66       privat e static f inal int S ERVER_FAIL URE = 2;
  67       privat e static f inal int N AME_ERROR      = 3;
  68       privat e static f inal int N OT_IMPL        = 4;
  69       privat e static f inal int R EFUSED         = 5;
  70  
  71       privat e static f inal Strin g[] rcodeD escription  = {
  72           "N o error",
  73           "D NS format  error",
  74           "D NS server  failure",
  75           "D NS name no t found",
  76           "D NS operati on not sup ported",
  77           "D NS service  refused"
  78       };
  79  
  80         private st atic final  int DEFAU LT_PORT      
;
  81       privat e static f inal int T RANSACTION _ID_BOUND  = 0x10000;
  82       privat e static f inal Secur eRandom ra ndom = JCA Util.getSe cureRandom ();
  83       privat e InetAddr ess[] serv ers;
  84       privat e int[] se rverPorts;
  85       privat e int time out;                  // initial  timeout o n UDP quer ies in ms
  86       privat e int retr ies;                  // number  of UDP ret ries
  87  
  88       privat e final Ob ject udpSo cketLock =  new Objec t();
  89       privat e static f inal DNSDa tagramSock etFactory  factory =
  90                new DNSD atagramSoc ketFactory (random);
  91  
  92       // Req uests sent
  93       privat e Map<Inte ger, Resou rceRecord>  reqs;
  94  
  95       // Res ponses rec eived
  96       privat e Map<Inte ger, byte[ ]> resps;
  97  
  98       //---- ---------- ---------- ---------- ---------- ---------- ---------- ---------
  99  
  100       /*
  101        * Eac h server i s of the f orm "serve r[:port]".   IPv6 lit eral host  names
  102        * inc lude delim iting brac kets.
  103        * "ti meout" is  the initia l timeout  interval ( in ms) for  UDP queri es,
  104        * and  "retries"  gives the  number of  retries p er server.
  105        */
  106       public  DnsClient (String[]  servers, i nt timeout , int retr ies)
  107                throws N amingExcep tion {
  108           th is.timeout  = timeout ;
  109           th is.retries  = retries ;
  110           th is.servers  = new Ine tAddress[s ervers.len gth];
  111           se rverPorts  = new int[ servers.le ngth];
  112  
  113           fo r (int i =  0; i < se rvers.leng th; i++) {
  114  
  115                // Is op tional por t given?
  116                int colo n = server s[i].index Of(':',
  117                                                  servers [i].indexO f(']') + 1 );
  118  
  119                serverPo rts[i] = ( colon < 0)
  120                    ? DE FAULT_PORT
  121                    : In teger.pars eInt(serve rs[i].subs tring(colo n + 1));
  122                String s erver = (c olon < 0)
  123                    ? se rvers[i]
  124                    : se rvers[i].s ubstring(0 , colon);
  125                try {
  126                    this .servers[i ] = InetAd dress.getB yName(serv er);
  127                } catch  (java.net. UnknownHos tException  e) {
  128                    Nami ngExceptio n ne = new  Configura tionExcept ion(
  129                             "Unkno wn DNS ser ver: " + s erver);
  130                    ne.s etRootCaus e(e);
  131                    thro w ne;
  132                }
  133           }
  134           re qs = Colle ctions.syn chronizedM ap(
  135                new Hash Map<Intege r, Resourc eRecord>() );
  136           re sps = Coll ections.sy nchronized Map(new Ha shMap<Inte ger, byte[ ]>());
  137       }
  138  
  139       Datagr amSocket g etDatagram Socket() t hrows Nami ngExceptio n {
  140           tr y {
  141                return f actory.ope n();
  142           }  catch (jav a.net.Sock etExceptio n e) {
  143                NamingEx ception ne  = new Con figuration Exception( );
  144                ne.setRo otCause(e) ;
  145                throw ne ;
  146           }
  147       }
  148  
  149       protec ted void f inalize()  {
  150           cl ose();
  151       }
  152  
  153       // A l ock to acc ess the re quest and  response q ueues in t andem.
  154       privat e Object q ueuesLock  = new Obje ct();
  155  
  156       public  void clos e() {
  157           sy nchronized  (queuesLo ck) {
  158                reqs.cle ar();
  159                resps.cl ear();
  160           }
  161       }
  162  
  163       /*
  164        * If  recursion  is true, r ecursion i s requeste d on the q uery.
  165        * If  auth is tr ue, only a uthoritati ve respons es are acc epted; oth er
  166        * res ponses thr ow NameNot FoundExcep tion.
  167        */
  168       Resour ceRecords  query(DnsN ame fqdn,  int qclass , int qtyp e,
  169                               bool ean recurs ion, boole an auth)
  170                throws N amingExcep tion {
  171  
  172           in t xid;
  173           Pa cket pkt;
  174           Re sourceReco rd collisi on;
  175  
  176           do  {
  177                // Gener ate a rand om transac tion ID
  178                xid = ra ndom.nextI nt(TRANSAC TION_ID_BO UND);
  179                pkt = ma keQueryPac ket(fqdn,  xid, qclas s, qtype,  recursion) ;
  180  
  181                // enque ue the out standing r equest
  182                collisio n = reqs.p utIfAbsent (xid, new  ResourceRe cord(pkt.g etData(),
  183                    pkt. length(),  Header.HEA DER_SIZE,  true, fals e));
  184  
  185           }  while (col lision !=  null);
  186  
  187           Ex ception ca ughtExcept ion = null ;
  188           bo olean[] do NotRetry =  new boole an[servers .length];
  189  
  190           tr y {
  191                //
  192                // The U DP retry s trategy is  to try th e 1st serv er, and th en
  193                // each  server in  order. If  no answer,  double th e timeout
  194                // and t ry each se rver again .
  195                //
  196                for (int  retry = 0 ; retry <  retries; r etry++) {
  197  
  198                    // T ry each na me server.
  199                    for  (int i = 0 ; i < serv ers.length ; i++) {
  200                         if (doNotR etry[i]) {
  201                             contin ue;
  202                         }
  203  
  204                         // send th e request  packet and  wait for  a response .
  205                         try {
  206                             if (de bug) {
  207                                 dp rint("SEND  ID (" + ( retry + 1)  + "): " +  xid);
  208                             }
  209  
  210                             byte[]  msg = nul l;
  211                             msg =  doUdpQuery (pkt, serv ers[i], se rverPorts[ i],
  212                                                   retry,  xid);
  213                             //
  214                             // If  the matchi ng respons e is not g ot within  the
  215                             // giv en timeout , check if  the respo nse was en queued
  216                             // by  some other  thread, i f not proc eed with t he next
  217                             // ser ver or ret ry.
  218                             //
  219                             if (ms g == null)  {
  220                                 if  (resps.si ze() > 0)  {
  221                                      msg = lo okupRespon se(xid);
  222                                 }
  223                                 if  (msg == n ull) { //  try next s erver or r etry
  224                                      continue ;
  225                                 }
  226                             }
  227                             Header  hdr = new  Header(ms g, msg.len gth);
  228  
  229                             if (au th && !hdr .authorita tive) {
  230                                 ca ughtExcept ion = new  NameNotFou ndExceptio n(
  231                                          "DNS  response  not author itative");
  232                                 do NotRetry[i ] = true;
  233                                 co ntinue;
  234                             }
  235                             if (hd r.truncate d) {  // m essage is  truncated  -- try TCP
  236  
  237                                 //  Try each  server, st arting wit h the one  that just
  238                                 //  provided  the trunca ted messag e.
  239                                 fo r (int j =  0; j < se rvers.leng th; j++) {
  240                                      int ij =  (i + j) %  servers.l ength;
  241                                      if (doNo tRetry[ij] ) {
  242                                          cont inue;
  243                                      }
  244                                      try {
  245                                          Tcp  tcp =
  246                                               new Tcp(se rvers[ij],  serverPor ts[ij]);
  247                                          byte [] msg2;
  248                                          try  {
  249                                               msg2 = doT cpQuery(tc p, pkt);
  250                                          } fi nally {
  251                                               tcp.close( );
  252                                          }
  253                                          Head er hdr2 =  new Header (msg2, msg 2.length);
  254                                          if ( hdr2.query ) {
  255                                               throw new  Communicat ionExcepti on(
  256                                                   "DNS e rror: expe cting resp onse");
  257                                          }
  258                                          chec kResponseC ode(hdr2);
  259  
  260                                          if ( !auth || h dr2.author itative) {
  261                                               // Got a v alid respo nse
  262                                               hdr = hdr2 ;
  263                                               msg = msg2 ;
  264                                               break;
  265                                          } el se {
  266                                               doNotRetry [ij] = tru e;
  267                                          }
  268                                      } catch  (Exception  e) {
  269                                          // T ry next se rver, or u se UDP res ponse
  270                                      }
  271                                 }  // servers
  272                             }
  273                             return  new Resou rceRecords (msg, msg. length, hd r, false);
  274  
  275                         } catch (I OException  e) {
  276                             if (de bug) {
  277                                 dp rint("Caug ht IOExcep tion:" + e );
  278                             }
  279                             if (ca ughtExcept ion == nul l) {
  280                                 ca ughtExcept ion = e;
  281                             }
  282                             // Use  reflectio n to allow  pre-1.4 c ompilation .
  283                             // Thi s won't be  needed mu ch longer.
  284                             if (e. getClass() .getName() .equals(
  285                                      "java.ne t.PortUnre achableExc eption"))  {
  286                                 do NotRetry[i ] = true;
  287                             }
  288                         } catch (N ameNotFoun dException  e) {
  289                             // Thi s is autho ritative,  so return  immediatel y
  290                             throw  e;
  291                         } catch (C ommunicati onExceptio n e) {
  292                             if (ca ughtExcept ion == nul l) {
  293                                 ca ughtExcept ion = e;
  294                             }
  295                         } catch (N amingExcep tion e) {
  296                             if (ca ughtExcept ion == nul l) {
  297                                 ca ughtExcept ion = e;
  298                             }
  299                             doNotR etry[i] =  true;
  300                         }
  301                    } //  servers
  302                } // ret ries
  303  
  304           }  finally {
  305                reqs.rem ove(xid);  // cleanup
  306           }
  307  
  308           if  (caughtEx ception in stanceof N amingExcep tion) {
  309                throw (N amingExcep tion) caug htExceptio n;
  310           }
  311           //  A network  timeout o r other er ror occurr ed.
  312           Na mingExcept ion ne = n ew Communi cationExce ption("DNS  error");
  313           ne .setRootCa use(caught Exception) ;
  314           th row ne;
  315       }
  316  
  317       Resour ceRecords  queryZone( DnsName zo ne, int qc lass, bool ean recurs ion)
  318                throws N amingExcep tion {
  319  
  320           in t xid = ra ndom.nextI nt(TRANSAC TION_ID_BO UND);
  321  
  322           Pa cket pkt =  makeQuery Packet(zon e, xid, qc lass,
  323                                           Res ourceRecor d.QTYPE_AX FR, recurs ion);
  324           Ex ception ca ughtExcept ion = null ;
  325  
  326           //  Try each  name serve r.
  327           fo r (int i =  0; i < se rvers.leng th; i++) {
  328                try {
  329                    Tcp  tcp = new  Tcp(server s[i], serv erPorts[i] );
  330                    byte [] msg;
  331                    try  {
  332                         msg = doTc pQuery(tcp , pkt);
  333                         Header hdr  = new Hea der(msg, m sg.length) ;
  334                         // Check o nly rcode  as per
  335                         // draft-i etf-dnsext -axfr-clar ify-04
  336                         checkRespo nseCode(hd r);
  337                         ResourceRe cords rrs  =
  338                             new Re sourceReco rds(msg, m sg.length,  hdr, true );
  339                         if (rrs.ge tFirstAnsT ype() != R esourceRec ord.TYPE_S OA) {
  340                             throw  new Commun icationExc eption(
  341                                      "DNS err or: zone x fer doesn' t begin wi th SOA");
  342                         }
  343  
  344                         if (rrs.an swer.size( ) == 1 ||
  345                                 rr s.getLastA nsType() ! = Resource Record.TYP E_SOA) {
  346                             // The  response  is split i nto multip le DNS mes sages.
  347                             do {
  348                                 ms g = contin ueTcpQuery (tcp);
  349                                 if  (msg == n ull) {
  350                                      throw ne w Communic ationExcep tion(
  351                                               "DNS error : incomple te zone tr ansfer");
  352                                 }
  353                                 hd r = new He ader(msg,  msg.length );
  354                                 ch eckRespons eCode(hdr) ;
  355                                 rr s.add(msg,  msg.lengt h, hdr);
  356                             } whil e (rrs.get LastAnsTyp e() !=
  357                                       Resourc eRecord.TY PE_SOA);
  358                         }
  359  
  360                         // Delete  the duplic ate SOA re cord.
  361                         rrs.answer .removeEle mentAt(rrs .answer.si ze() - 1);
  362                         return rrs ;
  363  
  364                    } fi nally {
  365                         tcp.close( );
  366                    }
  367  
  368                } catch  (IOExcepti on e) {
  369                    caug htExceptio n = e;
  370                } catch  (NameNotFo undExcepti on e) {
  371                    thro w e;
  372                } catch  (NamingExc eption e)  {
  373                    caug htExceptio n = e;
  374                }
  375           }
  376           if  (caughtEx ception in stanceof N amingExcep tion) {
  377                throw (N amingExcep tion) caug htExceptio n;
  378           }
  379           Na mingExcept ion ne = n ew Communi cationExce ption(
  380                    "DNS  error dur ing zone t ransfer");
  381           ne .setRootCa use(caught Exception) ;
  382           th row ne;
  383       }
  384  
  385  
  386       /**
  387        * Tri es to retr eive an UD P packet m atching th e given xi d
  388        * rec eived with in the tim eout.
  389        * If  a packet w ith differ ent xid is  received,  the recei ved packet
  390        * is  enqueued w ith the co rrespondin g xid in ' resps'.
  391        */
  392       privat e byte[] d oUdpQuery( Packet pkt , InetAddr ess server ,
  393                                           int  port, int  retry, in t xid)
  394                throws I OException , NamingEx ception {
  395  
  396           in t minTimeo ut = 50; / / msec aft er which t here are n o retries.
  397  
  398           sy nchronized  (udpSocke tLock) {
  399                try (Dat agramSocke t udpSocke t = getDat agramSocke t()) {
  400                    Data gramPacket  opkt = ne w Datagram Packet(
  401                             pkt.ge tData(), p kt.length( ), server,  port);
  402                    Data gramPacket  ipkt = ne w Datagram Packet(new  byte[8000 ], 8000);
  403                    // P ackets may  only be s ent to or  received f rom this s erver addr ess
  404                    udpS ocket.conn ect(server , port);
  405                    int  pktTimeout  = (timeou t * (1 <<  retry));
  406                    try  {
  407                         udpSocket. send(opkt) ;
  408  
  409                         // timeout  remaining  after suc cessive 'r eceive()'
  410                         int timeou tLeft = pk tTimeout;
  411                         int cnt =  0;
  412                         do {
  413                             if (de bug) {
  414                                cnt ++;
  415                                 dp rint("Tryi ng RECEIVE (" +
  416                                          cnt  + ") retry (" + (retr y + 1) +
  417                                          ") f or:" + xid   + "    s ock-timeou t:" +
  418                                          time outLeft +  " ms.");
  419                             }
  420                             udpSoc ket.setSoT imeout(tim eoutLeft);
  421                             long s tart = Sys tem.curren tTimeMilli s();
  422                             udpSoc ket.receiv e(ipkt);
  423                             long e nd = Syste m.currentT imeMillis( );
  424  
  425                             byte[]  data = ip kt.getData ();
  426                             if (is MatchRespo nse(data,  xid)) {
  427                                 re turn data;
  428                             }
  429                             timeou tLeft = pk tTimeout -  ((int) (e nd - start ));
  430                         } while (t imeoutLeft  > minTime out);
  431  
  432                    } fi nally {
  433                         udpSocket. disconnect ();
  434                    }
  435                    retu rn null; / / no match ing packet  received  within the  timeout
  436                }
  437           }
  438       }
  439  
  440       /*
  441        * Sen ds a TCP q uery, and  returns th e first DN S message  in the res ponse.
  442        */
  443       privat e byte[] d oTcpQuery( Tcp tcp, P acket pkt)  throws IO Exception  {
  444  
  445           in t len = pk t.length() ;
  446           //  Send 2-by te message  length, t hen send m essage.
  447           tc p.out.writ e(len >> 8 );
  448           tc p.out.writ e(len);
  449           tc p.out.writ e(pkt.getD ata(), 0,  len);
  450           tc p.out.flus h();
  451  
  452           by te[] msg =  continueT cpQuery(tc p);
  453           if  (msg == n ull) {
  454                throw ne w IOExcept ion("DNS e rror: no r esponse");
  455           }
  456           re turn msg;
  457       }
  458  
  459       /*
  460        * Ret urns the n ext DNS me ssage from  the TCP s ocket, or  null on EO F.
  461        */
  462       privat e byte[] c ontinueTcp Query(Tcp  tcp) throw s IOExcept ion {
  463  
  464           in t lenHi =  tcp.in.rea d();       // high-or der byte o f response  length
  465           if  (lenHi ==  -1) {
  466                return n ull;         // EOF
  467           }
  468           in t lenLo =  tcp.in.rea d();       // low-ord er byte of  response  length
  469           if  (lenLo ==  -1) {
  470                throw ne w IOExcept ion("Corru pted DNS r esponse: b ad length" );
  471           }
  472           in t len = (l enHi << 8)  | lenLo;
  473           by te[] msg =  new byte[ len];
  474           in t pos = 0;                       // next un filled pos ition in m sg
  475           wh ile (len >  0) {
  476                int n =  tcp.in.rea d(msg, pos , len);
  477                if (n ==  -1) {
  478                    thro w new IOEx ception(
  479                             "Corru pted DNS r esponse: t oo little  data");
  480                }
  481                len -= n ;
  482                pos += n ;
  483           }
  484           re turn msg;
  485       }
  486  
  487       privat e Packet m akeQueryPa cket(DnsNa me fqdn, i nt xid,
  488                                         int q class, int  qtype, bo olean recu rsion) {
  489           in t qnameLen  = fqdn.ge tOctets();
  490           in t pktLen =  DNS_HDR_S IZE + qnam eLen + 4;
  491           Pa cket pkt =  new Packe t(pktLen);
  492  
  493           sh ort flags  = recursio n ? Header .RD_BIT :  0;
  494  
  495           pk t.putShort (xid, IDEN T_OFFSET);
  496           pk t.putShort (flags, FL AGS_OFFSET );
  497           pk t.putShort (1, NUMQ_O FFSET);
  498           pk t.putShort (0, NUMANS _OFFSET);
  499           pk t.putInt(0 , NUMAUTH_ OFFSET);
  500  
  501           ma keQueryNam e(fqdn, pk t, DNS_HDR _SIZE);
  502           pk t.putShort (qtype, DN S_HDR_SIZE  + qnameLe n);
  503           pk t.putShort (qclass, D NS_HDR_SIZ E + qnameL en + 2);
  504  
  505           re turn pkt;
  506       }
  507  
  508       // Bui lds a quer y name in  pkt accord ing to the  RFC spec.
  509       privat e void mak eQueryName (DnsName f qdn, Packe t pkt, int  off) {
  510  
  511           //  Loop thro ugh labels , least-si gnificant  first.
  512           fo r (int i =  fqdn.size () - 1; i  >= 0; i--)  {
  513                String l abel = fqd n.get(i);
  514                int len  = label.le ngth();
  515  
  516                pkt.putB yte(len, o ff++);
  517                for (int  j = 0; j  < len; j++ ) {
  518                    pkt. putByte(la bel.charAt (j), off++ );
  519                }
  520           }
  521           if  (!fqdn.ha sRootLabel ()) {
  522                pkt.putB yte(0, off );
  523           }
  524       }
  525  
  526       //---- ---------- ---------- ---------- ---------- ---------- ---------- ---------
  527  
  528       privat e byte[] l ookupRespo nse(Intege r xid) thr ows Naming Exception  {
  529           //
  530           //  Check the  queued re sponses: s ome other  thread in  between
  531           //  received  the respon se for thi s request.
  532           //
  533           if  (debug) {
  534                dprint(" LOOKUP for : " + xid  +
  535                    "\tR esponse Q: " + resps) ;
  536           }
  537           by te[] pkt;
  538           if  ((pkt = r esps.get(x id)) != nu ll) {
  539                checkRes ponseCode( new Header (pkt, pkt. length));
  540                synchron ized (queu esLock) {
  541                    resp s.remove(x id);
  542                    reqs .remove(xi d);
  543                }
  544  
  545                if (debu g) {
  546                    dpri nt("FOUND  (" + Threa d.currentT hread() +
  547                         ") for:" +  xid);
  548                }
  549           }
  550           re turn pkt;
  551       }
  552  
  553       /*
  554        * Che cks the he ader of an  incoming  DNS respon se.
  555        * Ret urns true  if it matc hes the gi ven xid an d throws a  naming
  556        * exc eption, if  appropria te, based  on the res ponse code .
  557        *
  558        * Als o checks t hat the do main name,  type and  class in t he respons e
  559        * mat ch those i n the orig inal query .
  560        */
  561       privat e boolean  isMatchRes ponse(byte [] pkt, in t xid)
  562                    thro ws NamingE xception {
  563  
  564           He ader hdr =  new Heade r(pkt, pkt .length);
  565           if  (hdr.quer y) {
  566                throw ne w Communic ationExcep tion("DNS  error: exp ecting res ponse");
  567           }
  568  
  569           if  (!reqs.co ntainsKey( xid)) { //  already r eceived, i gnore the  response
  570                return f alse;
  571           }
  572  
  573           //  common ca se- the re quest sent  matches t he subsequ ent respon se read
  574           if  (hdr.xid  == xid) {
  575                if (debu g) {
  576                    dpri nt("XID MA TCH:" + xi d);
  577                }
  578                checkRes ponseCode( hdr);
  579                if (!hdr .query &&  hdr.numQue stions ==  1) {
  580  
  581                    Reso urceRecord  rr = new  ResourceRe cord(pkt,  pkt.length ,
  582                         Header.HEA DER_SIZE,  true, fals e);
  583  
  584                    // R etrieve th e original  query
  585                    Reso urceRecord  query = r eqs.get(xi d);
  586                    int  qtype = qu ery.getTyp e();
  587                    int  qclass = q uery.getRr class();
  588                    DnsN ame qname  = query.ge tName();
  589  
  590                    // C heck that  the type/c lass/name  in the que ry section  of the
  591                    // r esponse ma tch those  in the ori ginal quer y
  592                    if ( (qtype ==  ResourceRe cord.QTYPE _STAR ||
  593                         qtype == r r.getType( )) &&
  594                         (qclass ==  ResourceR ecord.QCLA SS_STAR ||
  595                         qclass ==  rr.getRrcl ass()) &&
  596                         qname.equa ls(rr.getN ame())) {
  597  
  598                         if (debug)  {
  599                             dprint ("MATCH NA ME:" + qna me + " QTY PE:" + qty pe +
  600                                 "  QCLASS:" +  qclass);
  601                         }
  602  
  603                         // Remove  the respon se for the  xid if re ceived by  some other
  604                         // thread.
  605                         synchroniz ed (queues Lock) {
  606                             resps. remove(xid );
  607                             reqs.r emove(xid) ;
  608                         }
  609                         return tru e;
  610  
  611                    } el se {
  612                         if (debug)  {
  613                             dprint ("NO-MATCH  NAME:" +  qname + "  QTYPE:" +  qtype +
  614                                 "  QCLASS:" +  qclass);
  615                         }
  616                    }
  617                }
  618                return f alse;
  619           }
  620  
  621           //
  622           //  xid mis-m atch: enqu eue the re sponse, it  may belon g to some  other
  623           //  thread th at has not  yet had a  chance to  read its  response.
  624           //  enqueue o nly the fi rst respon se, respon ses for re tries are  ignored.
  625           //
  626           sy nchronized  (queuesLo ck) {
  627                if (reqs .containsK ey(hdr.xid )) { // en queue only  the first  response
  628                    resp s.put(hdr. xid, pkt);
  629                }
  630           }
  631  
  632           if  (debug) {
  633                dprint(" NO-MATCH S END ID:" +
  634                                      xid + "  RECVD ID:"  + hdr.xid  +
  635                                      "    Res ponse Q:"  + resps +
  636                                      "    Req s size:" +  reqs.size ());
  637           }
  638           re turn false ;
  639       }
  640  
  641       /*
  642        * Thr ows an exc eption if  appropriat e for the  response c ode of a
  643        * giv en header.
  644        */
  645       privat e void che ckResponse Code(Heade r hdr) thr ows Naming Exception  {
  646  
  647           in t rcode =  hdr.rcode;
  648           if  (rcode ==  NO_ERROR)  {
  649                return;
  650           }
  651           St ring msg =  (rcode <  rcodeDescr iption.len gth)
  652                ? rcodeD escription [rcode]
  653                : "DNS e rror";
  654           ms g += " [re sponse cod e " + rcod e + "]";
  655  
  656           sw itch (rcod e) {
  657           ca se SERVER_ FAILURE:
  658                throw ne w ServiceU navailable Exception( msg);
  659           ca se NAME_ER ROR:
  660                throw ne w NameNotF oundExcept ion(msg);
  661           ca se NOT_IMP L:
  662           ca se REFUSED :
  663                throw ne w Operatio nNotSuppor tedExcepti on(msg);
  664           ca se FORMAT_ ERROR:
  665           de fault:
  666                throw ne w NamingEx ception(ms g);
  667           }
  668       }
  669  
  670       //---- ---------- ---------- ---------- ---------- ---------- ---------- ---------
  671  
  672       privat e static f inal boole an debug =  false;
  673  
  674       privat e static v oid dprint (String me ss) {
  675           if  (debug) {
  676                System.e rr.println ("DNS: " +  mess);
  677           }
  678       }
  679  
  680   }
  681  
  682   class Tcp  {
  683  
  684       privat e Socket s ock;
  685       java.i o.InputStr eam in;
  686       java.i o.OutputSt ream out;
  687  
  688       Tcp(In etAddress  server, in t port) th rows IOExc eption {
  689           so ck = new S ocket(serv er, port);
  690           so ck.setTcpN oDelay(tru e);
  691           ou t = new ja va.io.Buff eredOutput Stream(soc k.getOutpu tStream()) ;
  692           in  = new jav a.io.Buffe redInputSt ream(sock. getInputSt ream());
  693       }
  694  
  695       void c lose() thr ows IOExce ption {
  696           so ck.close() ;
  697       }
  698   }
  699  
  700   /*
  701    * javaos  emulation  -cj
  702    */
  703   class Pack et {
  704           by te buf[];
  705  
  706           Pa cket(int l en) {
  707                    buf  = new byte [len];
  708           }
  709  
  710           Pa cket(byte  data[], in t len) {
  711                    buf  = new byte [len];
  712                    Syst em.arrayco py(data, 0 , buf, 0,  len);
  713           }
  714  
  715           vo id putInt( int x, int  off) {
  716                    buf[ off + 0] =  (byte)(x  >> 24);
  717                    buf[ off + 1] =  (byte)(x  >> 16);
  718                    buf[ off + 2] =  (byte)(x  >> 8);
  719                    buf[ off + 3] =  (byte)x;
  720           }
  721  
  722           vo id putShor t(int x, i nt off) {
  723                    buf[ off + 0] =  (byte)(x  >> 8);
  724                    buf[ off + 1] =  (byte)x;
  725           }
  726  
  727           vo id putByte (int x, in t off) {
  728                    buf[ off] = (by te)x;
  729           }
  730  
  731           vo id putByte s(byte src [], int sr c_offset,  int dst_of fset, int  len) {
  732                    Syst em.arrayco py(src, sr c_offset,  buf, dst_o ffset, len );
  733           }
  734  
  735           in t length()  {
  736                    retu rn buf.len gth;
  737           }
  738  
  739           by te[] getDa ta() {
  740                    retu rn buf;
  741           }
  742   }