public void TestConstructor()
 {
     List<Variable> list = new List<Variable>(1)
                               {
                                   new Variable(new ObjectIdentifier(new uint[] {1, 3, 6, 1, 2, 1, 1, 6, 0}),
                                                new Null())
                               };
     GetRequestMessage message = new GetRequestMessage(0, VersionCode.V2, new OctetString("public"), list);
     Assert.GreaterOrEqual(Resources.get.Length, message.ToBytes().Length);
 }
예제 #2
0
        public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

            using (var udp = new UdpClient(addressFamily))
            {
                #if (!CF)
                udp.EnableBroadcast = true;
                #endif
                udp.Send(bytes, bytes.Length, broadcastAddress);

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

                _bufferSize = udp.Client.ReceiveBufferSize = Messenger.MaxMessageSize;

                #if ASYNC
                Task.Factory.StartNew(() => AsyncBeginReceive(udp.Client));
                #else
                Task.Factory.StartNew(() => AsyncReceive(udp.Client));
                #endif

                Thread.Sleep(interval);
                Interlocked.CompareExchange(ref _active, Inactive, Active);
                udp.Close();
            }
        }
예제 #3
0
파일: Messenger.cs 프로젝트: xxjeng/nuxleus
        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }
        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <returns></returns>
        public static async Task <IList <Variable> > GetAsync(VersionCode version, IPEndPoint endpoint, OctetString community, IList <Variable> variables)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            if (community == null)
            {
                throw new ArgumentNullException("community");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message  = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = await message.GetResponseAsync(endpoint).ConfigureAwait(false);

            var pdu = response.Pdu();

            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create("error in response", endpoint.Address, response);
            }

            return(pdu.Variables);
        }
예제 #5
0
        /// <summary>
        /// Discovers agents of the specified version in a specific time interval.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="interval">The discovering time interval, in milliseconds.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public async Task DiscoverAsync(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

            using (var udp = new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp))
            {
                var info = SocketExtension.EventArgsFactory.Create();
                info.RemoteEndPoint = broadcastAddress;
                info.SetBuffer(bytes, 0, bytes.Length);
                using (var awaitable1 = new SocketAwaitable(info))
                {
                    await udp.SendToAsync(awaitable1);
                }

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

                _bufferSize = udp.ReceiveBufferSize;
                await ReceiveAsync(udp).ConfigureAwait(false);

                await Task.Delay(interval).ConfigureAwait(false);

                Interlocked.CompareExchange(ref _active, Inactive, Active);
                udp.Shutdown(SocketShutdown.Both);
            }
        }
예제 #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Discovery"/> class.
 /// </summary>
 /// <param name="requestId">The request id.</param>
 /// <param name="messageId">The message id.</param>
 /// <param name="maxMessageSize">The max size of message.</param>
 public Discovery(int messageId, int requestId, int maxMessageSize)
 {
     _discovery = new GetRequestMessage(
         VersionCode.V3,
         new Header(
             new Integer32(messageId),
             new Integer32(maxMessageSize),
             Levels.Reportable),
         DefaultSecurityParameters,
         new Scope(
             OctetString.Empty,
             OctetString.Empty,
             new GetRequestPdu(requestId, new List <Variable>())),
         DefaultPrivacyProvider.DefaultPair);
 }
예제 #7
0
파일: Discovery.cs 프로젝트: xxjeng/nuxleus
 /// <summary>
 /// Initializes a new instance of the <see cref="Discovery"/> class.
 /// </summary>
 /// <param name="requestId">The request id.</param>
 /// <param name="messageId">The message id.</param>
 /// <param name="maxMessageSize">The max size of message.</param>
 public Discovery(int messageId, int requestId, int maxMessageSize)
 {
     _discovery = new GetRequestMessage(
         VersionCode.V3,
         new Header(
             new Integer32(messageId),
             new Integer32(maxMessageSize),
             Levels.Reportable),
         DefaultSecurityParameters,
         new Scope(
             OctetString.Empty,
             OctetString.Empty,
             new GetRequestPdu(requestId, new List<Variable>())),
         DefaultPrivacyProvider.DefaultPair,
         null);
 }
        public void Test()
        {
            var message = new GetRequestMessage(0, VersionCode.V1, new OctetString("public"), new List<Variable>());
            var bindingMock = new Mock<IListenerBinding>();
            bindingMock.Setup(foo => foo.SendResponse(It.IsAny<ISnmpMessage>(), It.IsAny<EndPoint>())).AtMostOnce();
            var context = new NormalSnmpContext(message, new IPEndPoint(IPAddress.Loopback, 0),
                                                new UserRegistry(), bindingMock.Object);
            context.GenerateResponse(new List<Variable>());
            Assert.IsNotNull(context.Response);
            context.SendResponse();
            Assert.IsFalse(context.HandleMembership());

            var list = new List<Variable>();
            for (int i = 0; i < 5000; i++)
            {
                list.Add(new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.4.0"), new OctetString("test")));
            }

            context.GenerateResponse(list);
            Assert.AreEqual(ErrorCode.TooBig, context.Response.Pdu().ErrorStatus.ToErrorCode());
        }
예제 #9
0
        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList <Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList <Variable> variables, int timeout)
        {
            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            GetRequestMessage message  = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            ISnmpMessage      response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();

            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw Error.Create(
                          "error in response",
                          endpoint.Address,
                          response);
            }

            return(pdu.Variables);
        }
예제 #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Discovery"/> class.
 /// </summary>
 /// <param name="requestId">The request id.</param>
 /// <param name="messageId">The message id.</param>
 /// <param name="maxMessageSize">The max size of message.</param>
 public Discovery(int messageId, int requestId, int maxMessageSize)
 {
     _discovery = new GetRequestMessage(
         VersionCode.V3,
         new Header(
             new Integer32(messageId),
             new Integer32(maxMessageSize),
             new OctetString(new[] { (byte)Levels.Reportable }),
             new Integer32(3)),
         new SecurityParameters(
             OctetString.Empty,
             new Integer32(0),
             new Integer32(0),
             OctetString.Empty,
             OctetString.Empty,
             OctetString.Empty),
         new Scope(
             OctetString.Empty,
             OctetString.Empty,
             new GetRequestPdu(requestId, ErrorCode.NoError, 0, new List<Variable>())),
         DefaultPrivacyProvider.DefaultPair);
 }
예제 #11
0
        /// <summary>
        /// Discovers the specified version.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int timeout)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                Discovery discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                Variable        v         = new Variable(new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 1, 0 }));
                List <Variable> variables = new List <Variable> {
                    v
                };
                GetRequestMessage message = new GetRequestMessage(_requestId, version, community, variables);
                bytes = message.ToBytes();
            }

# if !SILVERLIGHT  // mc++
            using (UdpClient udp = new UdpClient(addressFamily))
        internal override void Get(Variable variable)
        {
            if (string.IsNullOrEmpty(UserName))
            {
                Logger.Info("User name need to be specified for v3.");
                return;
            }

            Discovery discovery = Messenger.NextDiscovery;
            ReportMessage report = discovery.GetResponse(Timeout, Agent);
            GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(UserName), new List<Variable> { variable }, _privacy, Messenger.MaxMessageSize, report);
            ISnmpMessage response = request.GetResponse(Timeout, Agent);
            if (response.Pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    Agent.Address,
                    response);
            }

            Logger.Info(response.Pdu.Variables[0].ToString(Objects));
        }
예제 #13
0
        /// <summary>
        /// Discovers agents of the specified version in a specific time interval.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="interval">The discovering time interval, in milliseconds.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

#if SSHARP
            using (var udp = new UdpClient())
#else
            using (var udp = new UdpClient(addressFamily))
#endif
            {
#if !CF && !NETCF
                udp.EnableBroadcast = true;
#endif
#if !NETSTANDARD
                udp.Send(bytes, bytes.Length, broadcastAddress);
#else
                AsyncHelper.RunSync(() => udp.SendAsync(bytes, bytes.Length, broadcastAddress));
#endif

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

#if CF
                _bufferSize = 8192;
#elif SSHARP
                _bufferSize = 16384;
#else
                _bufferSize = udp.Client.ReceiveBufferSize = Messenger.MaxMessageSize;
#endif

#if ASYNC
#if SSHARP
                ThreadPool.QueueUserWorkItem(AsyncBeginReceive, udp);
#else
                Task.Factory.StartNew(() => AsyncBeginReceive(udp.Client));
#endif
#else
                Task.Factory.StartNew(() => AsyncReceive(udp.Client));
#endif

#if SSHARP
                CrestronEnvironment.Sleep(interval);
#else
                Thread.Sleep(interval);
#endif
                Interlocked.CompareExchange(ref _active, Inactive, Active);
                udp.Close();
            }
        }
예제 #14
0
        public static void Main(string[] args)
        {
            string community = "public";
            bool showHelp   = false;
            bool showVersion = false;
            VersionCode version = VersionCode.V1;
            int timeout = 1000;
            int retry = 0;
            Levels level = Levels.Reportable;
            string user = string.Empty;
            string authentication = string.Empty;
            string authPhrase = string.Empty;
            string privacy = string.Empty;
            string privPhrase = string.Empty;
            bool dump = false;

            OptionSet p = new OptionSet()
                .Add("c:", "-c for community name, (default is public)", delegate (string v) { if (v != null) community = v; })
                .Add("l:", "-l for security level, (default is noAuthNoPriv)", delegate (string v)
                                                                                   {
                                                                                       if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                                                                                       }
                                                                                       else
                                                                                       {
                                                                                           throw new ArgumentException("no such security mode: " + v);
                                                                                       }
                                                                                   })
                .Add("a:", "-a for authentication method (MD5 or SHA)", delegate (string v) { authentication = v; })
                .Add("A:", "-A for authentication passphrase", delegate(string v) { authPhrase = v; })
                .Add("x:", "-x for privacy method", delegate (string v) { privacy = v; })
                .Add("X:", "-X for privacy passphrase", delegate (string v) { privPhrase = v; })
                .Add("u:", "-u for security name", delegate(string v) { user = v; })
                .Add("h|?|help", "-h, -?, -help for help.", delegate (string v) { showHelp = v != null; })
                .Add("V", "-V to display version number of this application.", delegate (string v) { showVersion = v != null; })
                .Add("d", "-d to display message dump", delegate(string v) { dump = true; })
                .Add("t:", "-t for timeout value (unit is second).", delegate (string v) { timeout = int.Parse(v) * 1000; })
                .Add("r:", "-r for retry count (default is 0)", delegate (string v) { retry = int.Parse(v); })
                .Add("v|version:", "-v for SNMP version (1, 2, and 3 are currently supported)", delegate (string v)
                                                                                               {
                                                                                                   switch (int.Parse(v))
                                                                                                   {
                                                                                                       case 1:
                                                                                                           version = VersionCode.V1;
                                                                                                           break;
                                                                                                       case 2:
                                                                                                           version = VersionCode.V2;
                                                                                                           break;
                                                                                                       case 3:
                                                                                                           version = VersionCode.V3;
                                                                                                           break;
                                                                                                       default:
                                                                                                           throw new ArgumentException("no such version: " + v);
                                                                                                   }
                                                                                               });
            
            List<string> extra = p.Parse (args);
            
            if (showHelp)
            {
                ShowHelp();   
                return;
            }
            
            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            if (extra.Count < 2)
            {
                ShowHelp();
                return;
            }
            
            IPAddress ip;
            bool parsed = IPAddress.TryParse(extra[0], out ip);
            if (!parsed)
            {
                foreach (IPAddress address in Dns.GetHostAddresses(extra[0]))
                {
                    if (address.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    ip = address;
                    break;
                }
                
                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List<Variable> vList = new List<Variable>();
                for (int i = 1; i < extra.Count; i++)
                {
                    Variable test = new Variable(new ObjectIdentifier(extra[i]));
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (
                        Variable variable in
                            Messenger.Get(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }
                
                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery discovery = Messenger.NextDiscovery;
                ReportMessage report = discovery.GetResponse(timeout, receiver);

                GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);

                ISnmpMessage response = request.GetResponse(timeout, receiver);
                if (dump)
                {
                    Console.WriteLine(ByteTool.Convert(request.ToBytes()));
                }

                if (response.Pdu.ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                        "error in response",
                        receiver.Address,
                        response);
                }

                foreach (Variable v in response.Pdu.Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
예제 #15
0
        /// <summary>
        /// Discovers agents of the specified version in a specific time interval.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="interval">The discovering time interval, in milliseconds.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }
            
            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;
            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

            using (var udp = new UdpClient(addressFamily))
            {
                #if (!CF)
                udp.EnableBroadcast = true;
                #endif
                udp.Send(bytes, bytes.Length, broadcastAddress);

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

                #if CF
                _bufferSize = 8192;
                #else
                _bufferSize = udp.Client.ReceiveBufferSize;
                #endif

                #if ASYNC
                ThreadPool.QueueUserWorkItem(AsyncBeginReceive);
                #else
                ThreadPool.QueueUserWorkItem(AsyncReceive, udp.Client);
                #endif

                Thread.Sleep(interval);                
                Interlocked.CompareExchange(ref _active, Inactive, Active);
                udp.Close();
            }
        }
 public void TestConstructorV2AuthMd5PrivDes()
 {
     const string bytes = "30 81 80 02  01 03 30 0F  02 02 6C 99  02 03 00 FF" +
                          "E3 04 01 07  02 01 03 04  38 30 36 04  0D 80 00 1F" +
                          "88 80 E9 63  00 00 D6 1F  F4 49 02 01  14 02 01 35" +
                          "04 07 6C 65  78 6D 61 72  6B 04 0C 80  50 D9 A1 E7" +
                          "81 B6 19 80  4F 06 C0 04  08 00 00 00  01 44 2C A3" +
                          "B5 04 30 4B  4F 10 3B 73  E1 E4 BD 91  32 1B CB 41" +
                          "1B A1 C1 D1  1D 2D B7 84  16 CA 41 BF  B3 62 83 C4" +
                          "29 C5 A4 BC  32 DA 2E C7  65 A5 3D 71  06 3C 5B 56" +
                          "FB 04 A4";
     MD5AuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString("testpass"));
     IPrivacyProvider privacy = new DESPrivacyProvider(new OctetString("passtest"), auth);
     GetRequestMessage request = new GetRequestMessage(
         VersionCode.V3,
         new Header(
             new Integer32(0x6C99),
             new Integer32(0xFFE3),
             new OctetString(new byte[] { 0x7 }),
             new Integer32(3)),
         new SecurityParameters(
             new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
             new Integer32(0x14),
             new Integer32(0x35),
             new OctetString("lexmark"),
             new OctetString(ByteTool.Convert("80  50 D9 A1 E7 81 B6 19 80  4F 06 C0")),
             new OctetString(ByteTool.Convert("00 00 00  01 44 2C A3 B5"))),
         new Scope(
             new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
             OctetString.Empty,
             new GetRequestPdu(
                 0x3A25,
                 ErrorCode.NoError,
                 0,
                 new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) })),
         privacy);
     Assert.AreEqual(Levels.Authentication | Levels.Privacy, request.Level);
     Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
 }
 public void TestConstructorV3AuthSha()
 {
     const string bytes = "30 77 02 01  03 30 0F 02  02 47 21 02  03 00 FF E3" +
                          "04 01 05 02  01 03 04 32  30 30 04 0D  80 00 1F 88" +
                          "80 E9 63 00  00 D6 1F F4  49 02 01 15  02 02 01 5B" +
                          "04 08 6C 65  78 74 75 64  69 6F 04 0C  7B 62 65 AE" +
                          "D3 8F E3 7D  58 45 5C 6C  04 00 30 2D  04 0D 80 00" +
                          "1F 88 80 E9  63 00 00 D6  1F F4 49 04  00 A0 1A 02" +
                          "02 56 FF 02  01 00 02 01  00 30 0E 30  0C 06 08 2B" +
                          "06 01 02 01  01 03 00 05  00";
     IPrivacyProvider pair = new DefaultPrivacyProvider(new SHA1AuthenticationProvider(new OctetString("password")));
     GetRequestMessage request = new GetRequestMessage(
         VersionCode.V3,
         new Header(
             new Integer32(0x4721),
             new Integer32(0xFFE3),
             new OctetString(new byte[] { 0x5 }),
             new Integer32(3)),
         new SecurityParameters(
             new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
             new Integer32(0x15),
             new Integer32(0x015B),
             new OctetString("lextudio"),
             new OctetString(ByteTool.Convert("7B 62 65 AE D3 8F E3 7D  58 45 5C 6C")),
             OctetString.Empty),
         new Scope(
             new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
             OctetString.Empty,
             new GetRequestPdu(
                 0x56FF,
                 ErrorCode.NoError,
                 0,
                 new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"), new Null()) })),
         pair);
     Assert.AreEqual(Levels.Authentication, request.Level);
     Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
 }
예제 #18
0
        /// <summary>
        /// Discovers agents of the specified version in a specific time interval.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="interval">The discovering time interval, in milliseconds.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public async Task DiscoverAsync(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException(nameof(broadcastAddress));
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported.", nameof(broadcastAddress));
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

            using (var udp = new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp))
            {
                udp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
                udp.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
                var info = SocketExtension.EventArgsFactory.Create();
                info.RemoteEndPoint = broadcastAddress;
                info.SetBuffer(bytes, 0, bytes.Length);

                using (var awaitable1 = new SocketAwaitable(info))
                {
                    await udp.SendToAsync(awaitable1);
                }

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

                _bufferSize = udp.ReceiveBufferSize;
                await Task.WhenAny(
                    ReceiveAsync(udp),
                    Task.Delay(interval));

                Interlocked.CompareExchange(ref _active, Inactive, Active);
                try
                {
                    udp.Shutdown(SocketShutdown.Both);
                }
                catch (SocketException ex)
                {
                    // This exception is thrown in .NET Core <=2.1.4 on non-Windows systems.
                    // However, the shutdown call is necessary to release the socket binding.
                    if (!SnmpMessageExtension.IsRunningOnWindows && ex.SocketErrorCode == SocketError.NotConnected)
                    {
                    }
                }
            }
        }
 public void TestDiscoveryV3()
 {
     const string bytes = "30 3A 02 01 03 30 0F 02 02 6A 09 02 03 00 FF E3" +
                          " 04 01 04 02 01 03 04 10 30 0E 04 00 02 01 00 02" +
                          " 01 00 04 00 04 00 04 00 30 12 04 00 04 00 A0 0C" +
                          " 02 02 2C 6B 02 01 00 02 01 00 30 00";
     GetRequestMessage request = new GetRequestMessage(
         VersionCode.V3,
         new Header(
             new Integer32(0x6A09),
             new Integer32(0xFFE3),
             new OctetString(new byte[] { 0x4 }),
             new Integer32(3)),
         new SecurityParameters(
             OctetString.Empty,
             new Integer32(0),
             new Integer32(0),
             OctetString.Empty,
             OctetString.Empty,
             OctetString.Empty),
         new Scope(
             OctetString.Empty,
             OctetString.Empty,
             new GetRequestPdu(0x2C6B, ErrorCode.NoError, 0, new List<Variable>())),
         DefaultPrivacyProvider.DefaultPair
        );
     string test = ByteTool.Convert(request.ToBytes());
     Assert.AreEqual(bytes, test);
 }
예제 #20
0
		/// <summary>
		/// Discovers the specified version.
		/// </summary>
		/// <param name="version">The version.</param>
		/// <param name="broadcastAddress">The broadcast address.</param>
		/// <param name="community">The community.</param>
		/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
		/// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
		public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int timeout)
		{
			if (broadcastAddress == null)
			{
				throw new ArgumentNullException("broadcastAddress");
			}
			
			if (version != VersionCode.V3 && community == null)
			{
				throw new ArgumentNullException("community");
			}

			var addressFamily = broadcastAddress.AddressFamily;
			if (addressFamily == AddressFamily.InterNetworkV6)
			{
				throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
			}

			byte[] bytes;
			_requestId = Messenger.NextRequestId;
			if (version == VersionCode.V3)
			{
				// throw new NotSupportedException("SNMP v3 is not supported");
				Discovery discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
				bytes = discovery.ToBytes();
			}
			else
			{
				Variable v = new Variable(new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 1, 0 }));
				List<Variable> variables = new List<Variable> { v };
				GetRequestMessage message = new GetRequestMessage(_requestId, version, community, variables);
				bytes = message.ToBytes();
			}

# if ! SILVERLIGHT // mc++
			using (UdpClient udp = new UdpClient(addressFamily))
			{
				#if (!CF)
				udp.EnableBroadcast = true;
				#endif
				udp.Send(bytes, bytes.Length, broadcastAddress);

				long activeBefore = Interlocked.CompareExchange(ref _active, 1, 0);
				if (activeBefore == 1)
				{
					// If already started, we've nothing to do.
					return;
				}

				#if CF
				_bufferSize = 8192;
				#else
				_bufferSize = udp.Client.ReceiveBufferSize;
				#endif

				#if ASYNC
				ThreadPool.QueueUserWorkItem(AsyncBeginReceive);
				#else
				ThreadPool.QueueUserWorkItem(AsyncReceive, udp.Client);
				#endif

				Thread.Sleep(timeout);                
				Interlocked.CompareExchange(ref _active, 0, 1);
				udp.Close();
			}
# endif 
			return;
		}
        internal override string GetValue(Variable variable)
        {
            Discovery discovery = Messenger.NextDiscovery;
            ReportMessage report = discovery.GetResponse(Timeout, Agent);
            GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(UserName), new List<Variable> { variable }, _privacy, Messenger.MaxMessageSize, report);
            ISnmpMessage response = request.GetResponse(Timeout, Agent);
            if (response.Pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    Agent.Address,
                    response);
            }

            return response.Pdu.Variables[0].Data.ToString();
        }
 public void TestToBytes()
 {
     const string s = "30 27 02 01  01 04 06 70  75 62 6C 69  63 A0 1A 02" +
                      "02 4B ED 02  01 00 02 01  00 30 0E 30  0C 06 08 2B" +
                      "06 01 02 01  01 01 00 05  00                      ";
     byte[] expected = ByteTool.Convert(s);
     GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
     Assert.AreEqual(expected, message.ToBytes());
 }
 public void TestConstructorV3Auth1()
 {
     const string bytes = "30 73" +
                          "02 01  03 " +
                          "30 0F " +
                          "02  02 35 41 " +
                          "02  03 00 FF E3" +
                          "04 01 05" +
                          "02  01 03" +
                          "04 2E  " +
                          "30 2C" +
                          "04 0D  80 00 1F 88 80 E9 63 00  00 D6 1F F4  49 " +
                          "02 01 0D  " +
                          "02 01 57 " +
                          "04 05 6C 65 78  6C 69 " +
                          "04 0C  1C 6D 67 BF  B2 38 ED 63 DF 0A 05 24  " +
                          "04 00 " +
                          "30 2D  " +
                          "04 0D 80 00  1F 88 80 E9 63 00 00 D6  1F F4 49 " +
                          "04  00 " +
                          "A0 1A 02  02 01 AF 02 01 00 02 01  00 30 0E 30  0C 06 08 2B  06 01 02 01 01 03 00 05  00";
     ReportMessage report = new ReportMessage(
         VersionCode.V3,
         new Header(
             new Integer32(13633),
             new Integer32(0xFFE3),
             new OctetString(new byte[] { 0x0 }),
             new Integer32(3)),
         new SecurityParameters(
             new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
             new Integer32(0x0d),
             new Integer32(0x57),
             new OctetString("lexli"),
             new OctetString(new byte[12]),
             OctetString.Empty),
         new Scope(
             new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
             OctetString.Empty,
             new ReportPdu(
                 0x01AF,
                 ErrorCode.NoError,
                 0,
                 new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) })),
         DefaultPrivacyProvider.DefaultPair);
     
     IPrivacyProvider privacy = new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("testpass")));
     GetRequestMessage request = new GetRequestMessage(
         VersionCode.V3,
         13633,
         0x01AF,
         new OctetString("lexli"),
         new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) },
         privacy,
         Messenger.MaxMessageSize,
         report);
     
     Assert.AreEqual(Levels.Authentication, request.Level);
     Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
 }
        public void TestTimeOut()
        {
            // IMPORTANT: this test case requires a local SNMP agent such as 
            //   #SNMP Agent (snmpd), 
            //   Windows SNMP agent service, 
            //   Net-SNMP agent, or 
            //   snmp4j agent.
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
            
            const int time = 1500;
            bool hasException = false;
            try
            {
                message.GetResponse(time, new IPEndPoint(IPAddress.Loopback, 161), socket);
            }
            catch (TimeoutException)
            {
                hasException = true;
            }

            Assert.IsFalse(hasException);

            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            
            try
            {
                timer.Start();
                //IMPORTANT: test against an agent that doesn't exist.
// ReSharper disable AssignNullToNotNullAttribute
                message.GetResponse(time, new IPEndPoint(IPAddress.Parse("192.168.0.233"), 161), socket);
// ReSharper restore AssignNullToNotNullAttribute
            }
            catch (TimeoutException)
            {
                hasException = true;
            }
            catch (SocketException)
            {
                hasException = true;
            }

            timer.Stop();            
            
            long elapsedMilliseconds = timer.ElapsedMilliseconds;
            Console.WriteLine(@"elapsed: " + elapsedMilliseconds);
            Console.WriteLine(@"timeout: " + time);
            Assert.LessOrEqual(time, elapsedMilliseconds);
            Assert.IsTrue(hasException);

            // FIXME: these values are valid on my machine openSUSE 11.2. (lex)
            // This test case usually fails on Windows, as strangely WinSock API call adds an extra 500-ms.
            if (SnmpMessageExtension.IsRunningOnMono)
            {
                Assert.LessOrEqual(elapsedMilliseconds, time + 100);
            }
        }