Example #1
0
        static NbtAddress()
        {
            IPAddress localInetAddress;
            string    localHostname;
            Name      localName;

            AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress
                                                         , Forever));
            localInetAddress = Client.laddr;
            if (localInetAddress == null)
            {
                try
                {
                    localInetAddress = Extensions.GetAddressByName("127.0.0.1");
                }
                catch (UnknownHostException)
                {
                }
            }
            localHostname = Config.GetProperty("jcifs.netbios.hostname", null);
            if (string.IsNullOrEmpty(localHostname))
            {
                byte[] addr = localInetAddress.GetAddressBytes();

                /*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked(
                 *  (int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked(
                 *                      (int)(0xFF))), 2);*/
                localHostname = "JCIFS_127_0_0_1";
            }
            localName = new Name(localHostname, unchecked (0x00), Config.GetProperty("jcifs.netbios.scope"
                                                                                     , null));
            Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode
                                       , false, false, true, false, UnknownMacAddress);
            CacheAddress(localName, Localhost, Forever);
        }
Example #2
0
        internal static void CacheAddress(Name hostName, NbtAddress addr)
        {
            if (CachePolicy == 0)
            {
                return;
            }
            long expiration = -1;

            if (CachePolicy != Forever)
            {
                expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
            }
            CacheAddress(hostName, addr, expiration);
        }
        /// <exception cref="System.IO.IOException"></exception>
        internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
                                                    )
        {
            if (@in.Read(buffer, bufferIndex, Length) != Length)
            {
                throw new IOException("unexpected EOF reading netbios retarget session response");
            }
            int addr = ReadInt4(buffer, bufferIndex);

            bufferIndex     += 4;
            _retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
            _retargetPort    = ReadInt2(buffer, bufferIndex);
            return(Length);
        }
Example #4
0
 /// <summary>Retrieve all addresses of a host by it's address.</summary>
 /// <remarks>
 /// Retrieve all addresses of a host by it's address. NetBIOS hosts can
 /// have many names for a given IP address. The name and IP address make the
 /// NetBIOS address. This provides a way to retrieve the other names for a
 /// host with the same IP address.
 /// </remarks>
 /// <param name="addr">the address to query</param>
 /// <exception cref="UnknownHostException">if address cannot be resolved</exception>
 public static NbtAddress[] GetAllByAddress(NbtAddress addr)
 {
     try
     {
         NbtAddress[] addrs = Client.GetNodeStatus(addr);
         CacheAddressArray(addrs);
         return(addrs);
     }
     catch (UnknownHostException)
     {
         throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr.
                                                                                     HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length
                                                                                                                                                == 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host "
                                        + addr.GetHostAddress());
     }
 }
Example #5
0
 internal static NbtAddress GetByName(Name name)
 {
     lock (typeof(Lmhosts))
     {
         NbtAddress result = null;
         try
         {
             if (Filename != null)
             {
                 FileInfo   fileInfo = new FileInfo(Filename);
                 long       lm       = fileInfo.LastAccessTimeUtc.ToMillisecondsSinceEpoch();
                 FileStream file     = fileInfo.OpenRead();
                 if (lm > _lastModified)
                 {
                     _lastModified = lm;
                     Tab.Clear();
                     _alt = 0;
                     Populate(new StreamReader(file));
                 }
                 result = (NbtAddress)Tab[name];
             }
         }
         catch (FileNotFoundException fnfe)
         {
             if (_log.Level > 1)
             {
                 _log.WriteLine("lmhosts file: " + Filename);
                 Runtime.PrintStackTrace(fnfe, _log);
             }
         }
         catch (IOException ioe)
         {
             if (_log.Level > 0)
             {
                 Runtime.PrintStackTrace(ioe, _log);
             }
         }
         return(result);
     }
 }
Example #6
0
 internal static void CacheAddress(Name hostName, NbtAddress addr, long expiration
                                   )
 {
     if (CachePolicy == 0)
     {
         return;
     }
     lock (AddressCache)
     {
         CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
         if (entry == null)
         {
             entry = new CacheEntry(hostName, addr, expiration);
             AddressCache.Put(hostName, entry);
         }
         else
         {
             entry.Address    = addr;
             entry.Expiration = expiration;
         }
     }
 }
Example #7
0
        /// <exception cref="UnknownHostException"></exception>
        internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr)
        {
            int n;
            NameQueryRequest  request  = new NameQueryRequest(name);
            NameQueryResponse response = new NameQueryResponse();

            request.Addr        = addr ?? NbtAddress.GetWinsAddress();
            request.IsBroadcast = request.Addr == null;
            if (request.IsBroadcast)
            {
                request.Addr = Baddr;
                n            = RetryCount;
            }
            else
            {
                request.IsBroadcast = false;
                n = 1;
            }
            do
            {
                try
                {
                    Send(request, response, RetryTimeout);
                }
                catch (IOException ioe)
                {
                    if (_log.Level > 1)
                    {
                        Runtime.PrintStackTrace(ioe, _log);
                    }
                    throw new UnknownHostException(ioe);
                }
                if (response.Received && response.ResultCode == 0)
                {
                    return(response.AddrEntry);
                }
            }while (--n > 0 && request.IsBroadcast);
            throw new UnknownHostException();
        }
Example #8
0
        /// <exception cref="UnknownHostException"></exception>
        internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr)
        {
            int n;
            int srcHashCode;
            NodeStatusRequest  request;
            NodeStatusResponse response;

            response     = new NodeStatusResponse(addr);
            request      = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked (0x00), null));
            request.Addr = addr.GetInetAddress();
            n            = RetryCount;
            while (n-- > 0)
            {
                try
                {
                    Send(request, response, RetryTimeout);
                }
                catch (IOException ioe)
                {
                    if (_log.Level > 1)
                    {
                        Runtime.PrintStackTrace(ioe, _log);
                    }
                    throw new UnknownHostException(ioe);
                }
                if (response.Received && response.ResultCode == 0)
                {
                    srcHashCode = request.Addr.GetHashCode();
                    for (int i = 0; i < response.AddressArray.Length; i++)
                    {
                        response.AddressArray[i].HostName.SrcHashCode = srcHashCode;
                    }
                    return(response.AddressArray);
                }
            }
            throw new UnknownHostException();
        }
Example #9
0
        /// <exception cref="System.IO.IOException"></exception>
        internal static void Populate(StreamReader br)
        {
            string line;

            //BufferedReader br = new BufferedReader((InputStreamReader)r);
            while ((line = br.ReadLine()) != null)
            {
                line = line.ToUpper().Trim();
                if (line.Length == 0)
                {
                }
                else
                {
                    if (line[0] == '#')
                    {
                        if (line.StartsWith("#INCLUDE "))
                        {
                            line = Runtime.Substring(line, line.IndexOf('\\'));
                            string url = "smb:" + line.Replace('\\', '/');
                            if (_alt > 0)
                            {
                                try
                                {
                                    Populate(new InputStreamReader(new SmbFileInputStream(url)));
                                }
                                catch (IOException ioe)
                                {
                                    _log.WriteLine("lmhosts URL: " + url);
                                    Runtime.PrintStackTrace(ioe, _log);
                                    continue;
                                }
                                _alt--;
                                while ((line = br.ReadLine()) != null)
                                {
                                    line = line.ToUpper().Trim();
                                    if (line.StartsWith("#END_ALTERNATE"))
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                Populate(new InputStreamReader(new SmbFileInputStream(url)));
                            }
                        }
                        else
                        {
                            if (line.StartsWith("#BEGIN_ALTERNATE"))
                            {
                                _alt++;
                            }
                            else
                            {
                                if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
                                {
                                    _alt--;
                                    throw new IOException("no lmhosts alternate includes loaded");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (char.IsDigit(line[0]))
                        {
                            char[]     data = line.ToCharArray();
                            int        ip;
                            int        i;
                            int        j;
                            Name       name;
                            NbtAddress addr;
                            char       c;
                            c  = '.';
                            ip = i = 0;
                            for (; i < data.Length && c == '.'; i++)
                            {
                                int b = unchecked (0x00);
                                for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
                                {
                                    b = b * 10 + c - '0';
                                }
                                ip = (ip << 8) + b;
                            }
                            while (i < data.Length && char.IsWhiteSpace(data[i]))
                            {
                                i++;
                            }
                            j = i;
                            while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
                            {
                                j++;
                            }
                            name = new Name(Runtime.Substring(line, i, j), unchecked (0x20), null
                                            );
                            addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
                                                  , NbtAddress.UnknownMacAddress);
                            Tab.Put(name, addr);
                        }
                    }
                }
            }
        }
Example #10
0
 internal CacheEntry(Name hostName, NbtAddress address, long expiration)
 {
     this.HostName   = hostName;
     this.Address    = address;
     this.Expiration = expiration;
 }
Example #11
0
        /// <exception cref="UnknownHostException"></exception>
        internal virtual NbtAddress GetByName(Name name, IPAddress addr)
        {
            int n;

            NameQueryRequest  request  = new NameQueryRequest(name);
            NameQueryResponse response = new NameQueryResponse();

            if (addr != null)
            {
                request.Addr        = addr;
                request.IsBroadcast = (addr.GetAddressBytes()[3] == unchecked (unchecked (0xFF)));
                n = RetryCount;
                do
                {
                    try
                    {
                        Send(request, response, RetryTimeout);
                    }
                    catch (IOException ioe)
                    {
                        if (_log.Level > 1)
                        {
                            Runtime.PrintStackTrace(ioe, _log);
                        }
                        throw new UnknownHostException(ioe);
                    }
                    if (response.Received && response.ResultCode == 0 &&
                        response.IsResponse)
                    {
                        int last = response.AddrEntry.Length - 1;
                        response.AddrEntry[last].HostName.SrcHashCode = addr.GetHashCode();
                        return(response.AddrEntry[last]);
                    }
                }while (--n > 0 && request.IsBroadcast);
                throw new UnknownHostException();
            }
            for (int i = 0; i < _resolveOrder.Length; i++)
            {
                try
                {
                    switch (_resolveOrder[i])
                    {
                    case ResolverLmhosts:
                    {
                        NbtAddress ans = Lmhosts.GetByName(name);
                        if (ans != null)
                        {
                            ans.HostName.SrcHashCode = 0;
                            // just has to be different
                            // from other methods
                            return(ans);
                        }
                        break;
                    }

                    case ResolverWins:
                    case ResolverBcast:
                    {
                        if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName &&
                            name.HexCode != unchecked (0x1d))
                        {
                            request.Addr        = NbtAddress.GetWinsAddress();
                            request.IsBroadcast = false;
                        }
                        else
                        {
                            request.Addr        = Baddr;
                            request.IsBroadcast = true;
                        }
                        n = RetryCount;
                        while (n-- > 0)
                        {
                            try
                            {
                                Send(request, response, RetryTimeout);
                            }
                            catch (IOException ioe)
                            {
                                if (_log.Level > 1)
                                {
                                    Runtime.PrintStackTrace(ioe, _log);
                                }
                                throw new UnknownHostException(ioe);
                            }
                            if (response.Received && response.ResultCode == 0 &&
                                response.IsResponse)
                            {
                                response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode();
                                return(response.AddrEntry[0]);
                            }
                            if (_resolveOrder[i] == ResolverWins)
                            {
                                break;
                            }
                        }
                        break;
                    }
                    }
                }
                catch (IOException)
                {
                }
            }
            throw new UnknownHostException();
        }
Example #12
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void Send(NameServicePacket request, NameServicePacket response,
                                   int timeout)
        {
            int nid = 0;
            int max = NbtAddress.Nbns.Length;

            if (max == 0)
            {
                max = 1;
            }

            lock (response)
            {
                while (max-- > 0)
                {
                    try
                    {
                        lock (_lock)
                        {
                            request.NameTrnId = GetNextNameTrnId();
                            nid = request.NameTrnId;
                            response.Received = false;
                            _responseTable.Put(nid, response);
                            EnsureOpen(timeout + 1000);

                            int requestLenght = request.WriteWireFormat(_sndBuf, 0);
                            //NEW SOCKET
                            _socket.Send(_sndBuf, 0, requestLenght, SocketFlags.None);
                            //_socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport));
                            if (_log.Level > 3)
                            {
                                _log.WriteLine(request);
                                Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght);
                            }
                        }
                        if (_waitResponse)
                        {
                            long start = Runtime.CurrentTimeMillis();
                            while (timeout > 0)
                            {
                                Runtime.Wait(response, timeout);
                                if (response.Received && request.QuestionType == response.RecordType)
                                {
                                    return;
                                }
                                response.Received = false;
                                timeout          -= (int)(Runtime.CurrentTimeMillis() - start);
                            }
                        }
                    }
                    catch (Exception ie)
                    {
                        throw new IOException(ie.Message);
                    }
                    finally
                    {
                        //Sharpen.Collections.Remove(responseTable, nid);
                        if (_waitResponse)
                        {
                            _responseTable.Remove(nid);
                        }
                    }
                    if (_waitResponse)
                    {
                        lock (_lock)
                        {
                            if (NbtAddress.IsWins(request.Addr) == false)
                            {
                                break;
                            }
                            if (request.Addr == NbtAddress.GetWinsAddress())
                            {
                                NbtAddress.SwitchWins();
                            }
                            request.Addr = NbtAddress.GetWinsAddress();
                        }
                    }
                }
            }
        }
Example #13
0
        internal NameServiceClient(int lport, IPAddress laddr)
        {
            this._lport = lport;
            this.laddr  = laddr;

            try
            {
                Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255"));
            }
            catch (Exception e)
            {
                LogStream.GetInstance().WriteLine(e);
            }

            _sndBuf = new byte[SndBufSize];
            _rcvBuf = new byte[RcvBufSize];


            if (string.IsNullOrEmpty(Ro))
            {
                if (NbtAddress.GetWinsAddress() == null)
                {
                    _resolveOrder    = new int[2];
                    _resolveOrder[0] = ResolverLmhosts;
                    _resolveOrder[1] = ResolverBcast;
                }
                else
                {
                    _resolveOrder    = new int[3];
                    _resolveOrder[0] = ResolverLmhosts;
                    _resolveOrder[1] = ResolverWins;
                    _resolveOrder[2] = ResolverBcast;
                }
            }
            else
            {
                int[]           tmp = new int[3];
                StringTokenizer st  = new StringTokenizer(Ro, ",");
                int             i   = 0;
                while (st.HasMoreTokens())
                {
                    string s = st.NextToken().Trim();
                    if (Runtime.EqualsIgnoreCase(s, "LMHOSTS"))
                    {
                        tmp[i++] = ResolverLmhosts;
                    }
                    else
                    {
                        if (Runtime.EqualsIgnoreCase(s, "WINS"))
                        {
                            if (NbtAddress.GetWinsAddress() == null)
                            {
                                if (_log.Level > 1)
                                {
                                    _log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
                                                   );
                                }
                                continue;
                            }
                            tmp[i++] = ResolverWins;
                        }
                        else
                        {
                            if (Runtime.EqualsIgnoreCase(s, "BCAST"))
                            {
                                tmp[i++] = ResolverBcast;
                            }
                            else
                            {
                                if (Runtime.EqualsIgnoreCase(s, "DNS"))
                                {
                                }
                                else
                                {
                                    // skip
                                    if (_log.Level > 1)
                                    {
                                        _log.WriteLine("unknown resolver method: " + s);
                                    }
                                }
                            }
                        }
                    }
                }
                _resolveOrder = new int[i];
                Array.Copy(tmp, 0, _resolveOrder, 0, i);
            }
        }
Example #14
0
        private int ReadNodeNameArray(byte[] src, int srcIndex)
        {
            int start = srcIndex;

            AddressArray = new NbtAddress[_numberOfNames];
            string n;
            int    hexCode;
            string scope = _queryAddress.HostName.Scope;
            bool   groupName;
            int    ownerNodeType;
            bool   isBeingDeleted;
            bool   isInConflict;
            bool   isActive;
            bool   isPermanent;
            int    j;
            bool   addrFound = false;

            try
            {
                for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
                {
                    for (j = srcIndex + 14; src[j] == unchecked (0x20); j--)
                    {
                    }
                    n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
                                                  );
                    hexCode        = src[srcIndex + 15] & unchecked (0xFF);
                    groupName      = ((src[srcIndex + 16] & unchecked (0x80)) == unchecked (0x80)) ? true : false;
                    ownerNodeType  = (src[srcIndex + 16] & unchecked (0x60)) >> 5;
                    isBeingDeleted = ((src[srcIndex + 16] & unchecked (0x10)) == unchecked (0x10)) ? true : false;
                    isInConflict   = ((src[srcIndex + 16] & unchecked (0x08)) == unchecked (0x08)) ? true : false;
                    isActive       = ((src[srcIndex + 16] & unchecked (0x04)) == unchecked (0x04)) ? true : false;
                    isPermanent    = ((src[srcIndex + 16] & unchecked (0x02)) == unchecked (0x02)) ? true : false;
                    if (!addrFound && _queryAddress.HostName.HexCode == hexCode && (_queryAddress.HostName
                                                                                    == NbtAddress.UnknownName || _queryAddress.HostName.name.Equals(n)))
                    {
                        if (_queryAddress.HostName == NbtAddress.UnknownName)
                        {
                            _queryAddress.HostName = new Name(n, hexCode, scope);
                        }
                        _queryAddress.GroupName            = groupName;
                        _queryAddress.NodeType             = ownerNodeType;
                        _queryAddress.isBeingDeleted       = isBeingDeleted;
                        _queryAddress.isInConflict         = isInConflict;
                        _queryAddress.isActive             = isActive;
                        _queryAddress.isPermanent          = isPermanent;
                        _queryAddress.MacAddress           = _macAddress;
                        _queryAddress.IsDataFromNodeStatus = true;
                        addrFound       = true;
                        AddressArray[i] = _queryAddress;
                    }
                    else
                    {
                        AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
                                                         , groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent,
                                                         _macAddress);
                    }
                }
            }
            catch (UnsupportedEncodingException)
            {
            }
            return(srcIndex - start);
        }
Example #15
0
 internal NodeStatusResponse(NbtAddress queryAddress)
 {
     this._queryAddress = queryAddress;
     RecordName         = new Name();
     _macAddress        = new byte[6];
 }