初始化版本

This commit is contained in:
冯佳
2026-02-09 10:27:21 +08:00
commit 64d767932f
4467 changed files with 2486822 additions and 0 deletions

View File

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Collections;
namespace Lextm.SharpSnmpLib.Mib
{
public class DisplayHint
{
private enum NumType {
dec,
hex,
oct,
bin,
str
}
private string _str;
private NumType _type;
private int _decimalPoints = 0;
public DisplayHint(string str)
{
_str = str;
if (str.StartsWith("d"))
{
_type = NumType.dec;
if (str.StartsWith("d-"))
{
_decimalPoints = Convert.ToInt32(str.Substring(2));
}
}
else if (str.StartsWith("o"))
{
_type = NumType.oct;
}
else if (str.StartsWith("h"))
{
_type = NumType.hex;
}
else if (str.StartsWith("b"))
{
_type = NumType.bin;
}
else
{
_type = NumType.str;
foreach (char c in str)
{
}
}
}
public override string ToString()
{
return _str;
}
internal object Decode(int i)
{
switch (_type)
{
case NumType.dec:
if (_decimalPoints == 0)
{
return i;
}
else
{
return i / Math.Pow(10.0, _decimalPoints);
}
case NumType.hex:
return System.Convert.ToString(i, 16);
case NumType.oct:
return System.Convert.ToString(i, 8);
case NumType.bin:
return System.Convert.ToString(i, 2);
default:
return null;
}
}
}
}

View File

@ -0,0 +1,29 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 13:18
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// The AGENT-CAPABILITIES construct is used to specify implementation characteristics of an SNMP agent sub-system with respect to object types and events.
/// </summary>
public sealed class AgentCapabilities : EntityBase
{
/// <summary>
/// Creates an <see cref="AgentCapabilities"/> instance.
/// </summary>
/// <param name="module"></param>
/// <param name="header"></param>
/// <param name="lexer"></param>
public AgentCapabilities(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,46 @@
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public abstract class EntityBase: IEntity
{
private readonly IModule _module;
private string _parent;
private readonly uint _value;
private readonly string _name;
public EntityBase(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
_module = module;
_name = preAssignSymbols[0].ToString();
Lexer.ParseOidValue(symbols, out _parent, out _value);
}
public IModule Module
{
get { return _module; }
}
public string Parent
{
get { return _parent; }
set { _parent = value; }
}
public uint Value
{
get { return _value; }
}
public string Name
{
get { return _name; }
}
public virtual string Description
{
get { return string.Empty; }
}
}
}

View File

@ -0,0 +1,62 @@
// Entity interface.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/19
* Time: 20:10
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Basic interface for all elements building up the MIB tree, thus having an OID as value.
/// </summary>
public interface IEntity : IDeclaration
{
/// <summary>
/// Parent name.
/// </summary>
string Parent
{
get;
set;
}
/// <summary>
/// Value.
/// </summary>
uint Value
{
get;
}
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
string Description
{
get;
}
}
}

View File

@ -0,0 +1,23 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:35
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Description of ModuleComplianceNode.
/// </summary>
public sealed class ModuleCompliance : EntityBase
{
public ModuleCompliance(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,10 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public sealed class ModuleIdentity : EntityBase
{
public ModuleIdentity(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,22 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:34
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Description of NotificationGroupNode.
/// </summary>
public sealed class NotificationGroup : EntityBase
{
public NotificationGroup(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,11 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public sealed class NotificationType : EntityBase
{
public NotificationType(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,22 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:27
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Description of ObjectGroupNode.
/// </summary>
public sealed class ObjectGroup : EntityBase
{
public ObjectGroup(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,21 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Object identifier node.
/// </summary>
public sealed class ObjectIdentity : EntityBase
{
/// <summary>
/// Creates a <see cref="ObjectIdentity"/>.
/// </summary>
/// <param name="module">Module name</param>
/// <param name="header">Header</param>
/// <param name="lexer">Lexer</param>
public ObjectIdentity(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,336 @@
using System;
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public sealed class ObjectType : EntityBase, ITypeReferrer
{
private ITypeAssignment _syntax;
private string _units;
private MaxAccess _access;
private Status _status;
private string _description;
private string _reference;
private IList<string> _indices;
private string _augments;
private string _defVal;
public ObjectType(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
ParseProperties(preAssignSymbols);
}
private void ParseProperties(SymbolList header)
{
ISymbolEnumerator headerSymbols = header.GetSymbolEnumerator();
Symbol temp = headerSymbols.NextNonEOLSymbol();
// Skip name
temp = headerSymbols.NextNonEOLSymbol();
temp.Expect(Symbol.ObjectType);
_syntax = ParseSyntax (Module, headerSymbols);
_units = ParseUnits (headerSymbols);
_access = ParseAccess (headerSymbols);
_status = ParseStatus (headerSymbols);
_description = ParseDescription (headerSymbols);
_reference = ParseReference (headerSymbols);
_indices = ParseIndices (headerSymbols);
_augments = ParseAugments (headerSymbols);
_defVal = ParseDefVal (headerSymbols);
}
private static string ParseAugments(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Augments)
{
string augment = null;
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
current = symbols.NextNonEOLSymbol();
augment = current.ToString();
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseBracket);
return augment;
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static string ParseDefVal(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.DefVal)
{
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
string defVal = null;
current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenBracket)
{
int depth = 1;
// TODO: decode this.
while (depth > 0)
{
current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenBracket)
{
depth++;
}
else if (current == Symbol.CloseBracket)
{
depth--;
}
}
}
else
{
defVal = current.ToString();
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseBracket);
}
return defVal;
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static IList<string> ParseIndices(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Index)
{
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
List<string> indices = new List<string>();
while (current != Symbol.CloseBracket)
{
current = symbols.NextNonEOLSymbol();
bool lastIndex = false;
if (current == Symbol.Implied)
{
current = symbols.NextNonEOLSymbol();
lastIndex = true; // 'IMPLIED' may only be used for last index
}
current.Assert((current != Symbol.Comma) && (current != Symbol.CloseBracket), "Expected index name but found symbol!");
indices.Add(current.ToString());
current = symbols.NextNonEOLSymbol();
if (lastIndex)
{
current.Expect(Symbol.CloseBracket);
}
else
{
current.Expect(Symbol.Comma, Symbol.CloseBracket);
}
}
return indices;
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static string ParseReference(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Reference)
{
return symbols.NextNonEOLSymbol().ToString();
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static string ParseDescription(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Description)
{
return symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' });
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static Status ParseStatus(ISymbolEnumerator symbols)
{
Status status = Status.obsolete;
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Status);
current = symbols.NextNonEOLSymbol();
try
{
status = (Status)Enum.Parse(typeof(Status), current.ToString());
}
catch (ArgumentException)
{
current.Assert(false, "Invalid/Unknown status");
}
return status;
}
private static MaxAccess ParseAccess(ISymbolEnumerator symbols)
{
MaxAccess access = MaxAccess.notAccessible;
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.MaxAccess, Symbol.Access);
current = symbols.NextNonEOLSymbol();
switch (current.ToString())
{
case "not-accessible":
access = MaxAccess.notAccessible;
break;
case "accessible-for-notify":
access = MaxAccess.accessibleForNotify;
break;
case "read-only":
access = MaxAccess.readOnly;
break;
case "read-write":
access = MaxAccess.readWrite;
break;
case "read-create":
access = MaxAccess.readCreate;
break;
case "write-only":
access = MaxAccess.readWrite;
break;
default:
current.Assert(false, "Invalid/Unknown access");
break;
}
return access;
}
private static string ParseUnits(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Units)
{
return symbols.NextNonEOLSymbol().ToString();
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static ITypeAssignment ParseSyntax(IModule module, ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Syntax);
return Lexer.ParseBasicTypeDef(module, String.Empty, symbols, isMacroSyntax: true);
}
private static bool IsProperty(Symbol sym)
{
string s = sym.ToString();
return s == "SYNTAX" || s == "MAX-ACCESS" || s == "STATUS" || s == "DESCRIPTION";
}
public ITypeAssignment Syntax
{
get { return _syntax; }
internal set { _syntax = value; }
}
public override string Description
{
get { return _description; }
}
public MaxAccess Access
{
get { return _access; }
}
public IList<string> Indices
{
get { return _indices; }
}
public string Augments
{
get { return _augments; }
}
#region ITypeReferrer Member
public ITypeAssignment ReferredType
{
get { return _syntax; }
set { _syntax = value; }
}
public ITypeAssignment BaseType
{
get
{
ITypeReferrer tr = this;
ITypeAssignment result = null;
while ((tr != null) && (tr.ReferredType != null))
{
result = tr.ReferredType;
tr = tr.ReferredType as ITypeReferrer;
}
return result;
}
}
#endregion
}
}

View File

@ -0,0 +1,30 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 20:49
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Object identifier node.
/// </summary>
public sealed class OidValueAssignment : EntityBase
{
/// <summary>
/// Creates a <see cref="OidValueAssignment"/>.
/// </summary>
/// <param name="module">Module</param>
/// <param name="name">Name</param>
/// <param name="lexer">Lexer</param>
public OidValueAssignment(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,56 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/6/7
* Time: 17:34
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
/// <summary>
/// Description of Exports.
/// </summary>
public sealed class Exports: IElement
{
private IModule _module;
private readonly IList<string> _types = new List<string>();
public Exports(IModule module, ISymbolEnumerator s)
{
_module = module;
Symbol previous = null;
Symbol current;
do
{
current = s.NextSymbol();
if (current == Symbol.EOL)
{
continue;
}
else if (((current == Symbol.Comma) || (current == Symbol.Semicolon)) && (previous != null))
{
previous.AssertIsValidIdentifier();
_types.Add(previous.ToString());
}
previous = current;
}
while (current != Symbol.Semicolon);
}
#region IElement Member
public IModule Module
{
get { return _module; }
}
#endregion
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public interface IDeclaration: IElement
{
/// <summary>
/// Name.
/// </summary>
string Name
{
get;
}
}
}

View File

@ -0,0 +1,35 @@
// Construct interface.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace Lextm.SharpSnmpLib.Mib.Elements
{
/// <summary>
/// Construct interface.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")]
public interface IElement
{
/// <summary>
/// Containing module.
/// </summary>
IModule Module
{
get;
}
}
}

View File

@ -0,0 +1,10 @@
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public interface ITypeReferrer
{
ITypeAssignment ReferredType { get; set; }
ITypeAssignment BaseType { get; }
}
}

View File

@ -0,0 +1,81 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 12:07
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
/// <summary>
/// The IMPORTS construct is used to specify items used in the current MIB module which are defined in another MIB module or ASN.1 module.
/// </summary>
public sealed class Imports : List<ImportsFrom>, IElement
{
private IModule _module;
/// <summary>
/// Creates an <see cref="Imports"/> instance.
/// </summary>
/// <param name="lexer"></param>
public Imports(IModule module, ISymbolEnumerator symbols)
{
_module = module;
Symbol current;
while ((current = symbols.NextSymbol()) != Symbol.Semicolon)
{
if (current == Symbol.EOL)
{
continue;
}
ImportsFrom imports = new ImportsFrom(current, symbols);
this.Add(imports);
}
}
public IList<string> Dependents
{
get
{
List<string> result = new List<string>();
foreach (ImportsFrom import in this)
{
result.Add(import.Module);
}
return result;
}
}
public ImportsFrom GetImportFromType(string type)
{
foreach (ImportsFrom import in this)
{
if (import.Types.Contains(type))
{
return import;
}
}
return null;
}
#region IElement Member
public IModule Module
{
get { return _module; }
}
#endregion
}
}

View File

@ -0,0 +1,60 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 12:07
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public sealed class ImportsFrom
{
private readonly string _module;
private readonly List<string> _types = new List<string>();
public ImportsFrom(Symbol last, ISymbolEnumerator symbols)
{
Symbol previous = last;
Symbol current;
while ((current = symbols.NextSymbol()) != Symbol.From)
{
if (current == Symbol.EOL)
{
continue;
}
if (current == Symbol.Comma)
{
previous.AssertIsValidIdentifier();
_types.Add(previous.ToString());
}
previous = current;
}
previous.AssertIsValidIdentifier();
_types.Add(previous.ToString());
_module = symbols.NextSymbol().ToString().ToUpperInvariant(); // module names are uppercase
}
public string Module
{
get { return _module; }
}
public IList<string> Types
{
get { return _types; }
}
public override string ToString()
{
return string.Join(", ", _types.ToArray()) + " FROM " + _module;
}
}
}

View File

@ -0,0 +1,48 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 12:20
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public sealed class TrapType : IDeclaration
{
private readonly IModule _module;
private readonly string _name;
private readonly int _value;
public TrapType(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
_module = module;
_name = preAssignSymbols[0].ToString();
Symbol valueSymbol = symbols.NextNonEOLSymbol();
bool succeeded = int.TryParse(valueSymbol.ToString(), out _value);
valueSymbol.Assert(succeeded, "not a decimal");
}
public int Value
{
get { return _value; }
}
#region IDeclaration Member
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
#endregion
}
}

View File

@ -0,0 +1,54 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public abstract class BaseType : ITypeAssignment
{
private IModule _module;
private string _name;
protected BaseType(IModule module, string name)
{
_module = module;
_name = name;
}
public virtual IModule Module
{
// differentiate between:
// FddiTimeNano ::= INTEGER (0..2147483647)
// which is an IntegerType which appears under Types in a MibModule and therefore has a name and module
// and
// SYNTAX INTEGER (0..2147483647)
// which is also an IntegerType but not defined as a separate type and therefore has NO name and NO module
get
{
if (!string.IsNullOrEmpty(_name))
{
return _module;
}
else
{
return null;
}
}
protected set { _module = value; }
}
public virtual string Name
{
get
{
if (!string.IsNullOrEmpty(_name))
{
return _name;
}
else
{
return "{ Implicit Base Type }";
}
}
protected set { _name = value; }
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class BitsType : BaseType
{
private ValueMap _map;
public BitsType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
_map = Lexer.DecodeEnumerations(symbols);
}
public ValueMap Map
{
get { return _map; }
}
public string this[int value]
{
get { return _map[value]; }
}
}
}

View File

@ -0,0 +1,35 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 11:39
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The CHOICE type represents a list of alternatives..
/// </summary>
public sealed class Choice : BaseType
{
/// <summary>
/// Creates a <see cref="Choice"/> instance.
/// </summary>
/// <param name="module"></param>
/// <param name="name"></param>
/// <param name="lexer"></param>
public Choice(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
while (symbols.NextNonEOLSymbol() != Symbol.OpenBracket)
{
}
while (symbols.NextNonEOLSymbol() != Symbol.CloseBracket)
{
}
}
}
}

View File

@ -0,0 +1,6 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public interface ITypeAssignment : IDeclaration
{
}
}

View File

@ -0,0 +1,117 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/7/25
* Time: 20:41
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The INTEGER type represents a list of alternatives, or a range of numbers..
/// Includes Integer32 as it's indistinguishable from INTEGER.
/// </summary>
/**
* As this type is used for Integer32 as well as INTEGER it incorrectly
* allows enumeration sub-typing of Integer32. This is ok as currently we
* do not care about detecting incorrect MIBs and this doesn't block the
* decoding of correct MIBs.
*/
public sealed class IntegerType : BaseType
{
public enum Types
{
Integer,
Integer32
}
private Types _type;
private bool _isEnumeration;
private ValueMap _map;
private ValueRanges _ranges;
/// <summary>
/// Creates an <see cref="IntegerType"/> instance.
/// </summary>
/// <param name="module"></param>
/// <param name="name"></param>
/// <param name="enumerator"></param>
public IntegerType(IModule module, string name, Symbol type, ISymbolEnumerator symbols)
: base (module, name)
{
Types? t = GetExactType(type);
type.Assert(t.HasValue, "Unknown symbol for unsigned type!");
_type = t.Value;
_isEnumeration = false;
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenBracket)
{
_isEnumeration = true;
symbols.PutBack(current);
_map = Lexer.DecodeEnumerations(symbols);
}
else if (current == Symbol.OpenParentheses)
{
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
current.Assert(!_ranges.IsSizeDeclaration, "SIZE keyword is not allowed for ranges of integer types!");
}
else
{
symbols.PutBack(current);
}
}
public Types Type
{
get { return _type; }
}
public ValueRanges Ranges
{
get { return _ranges; }
}
public bool IsEnumeration
{
get
{
return _isEnumeration;
}
}
public ValueMap Enumeration
{
get { return _isEnumeration ? _map : null; }
}
internal static Types? GetExactType(Symbol symbol)
{
if (symbol == Symbol.Integer)
{
// represents the ASN.1 builtin INTEGER type:
// may be represent any arbitrary (signed/unsigned) integer (in theory may have any size)
return Types.Integer;
}
else if (symbol == Symbol.Integer32)
{
// Integer32 ::= INTEGER (-2147483648..2147483647) // from SNMPv2-SMI
return Types.Integer32;
}
return null;
}
internal static bool IsIntegerType(Symbol symbol)
{
return GetExactType(symbol).HasValue;
}
}
}

View File

@ -0,0 +1,21 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class IpAddressType : OctetStringType
{
public IpAddressType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name, symbols)
{
if (this.Size.Count != 0)
{
throw new MibException("Size definition not allowed for IpAddress type!");
}
// IpAddress type is defined as:
// IpAddress ::=
// [APPLICATION 0]
// IMPLICIT OCTET STRING (SIZE (4))
this.Size.Add(new ValueRange(4, null));
}
}
}

View File

@ -0,0 +1,34 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public sealed class Macro : ITypeAssignment
{
private IModule _module;
private string _name;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "temp")]
public Macro(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
_module = module;
_name = preAssignSymbols[0].ToString();
while (symbols.NextNonEOLSymbol() != Symbol.Begin)
{
}
while (symbols.NextNonEOLSymbol() != Symbol.End)
{
}
}
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
}
}

View File

@ -0,0 +1,11 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class ObjectIdentifierType : BaseType
{
public ObjectIdentifierType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
}
}
}

View File

@ -0,0 +1,31 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class OctetStringType : BaseType
{
private ValueRanges _size;
public OctetStringType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenParentheses)
{
symbols.PutBack(current);
_size = Lexer.DecodeRanges(symbols);
current.Assert(_size.IsSizeDeclaration, "SIZE keyword is required for ranges of octet string!");
}
else
{
symbols.PutBack(current);
_size = new ValueRanges(isSizeDecl: true);
}
}
public ValueRanges Size
{
get { return _size; }
}
}
}

View File

@ -0,0 +1,11 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class OpaqueType : OctetStringType
{
public OpaqueType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name, symbols)
{
}
}
}

View File

@ -0,0 +1,46 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:43
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The SEQUENCE type represents a set of specified types. This is roughly analogous to a <code>struct</code> in C.
/// </summary>
public sealed class Sequence : BaseType
{
/// <summary>
/// Creates a <see cref="Sequence" /> instance.
/// </summary>
/// <param name="module">The module.</param>
/// <param name="name">The name.</param>
/// <param name="symbols">The enumerator.</param>
public Sequence(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
// parse between ( )
Symbol temp = symbols.NextNonEOLSymbol();
int bracketSection = 0;
temp.Expect(Symbol.OpenBracket);
bracketSection++;
while (bracketSection > 0)
{
temp = symbols.NextNonEOLSymbol();
if (temp == Symbol.OpenBracket)
{
bracketSection++;
}
else if (temp == Symbol.CloseBracket)
{
bracketSection--;
}
}
}
}
}

View File

@ -0,0 +1,23 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The SEQUENCE OF type represents a list of data sets..
/// </summary>
public sealed class SequenceOf : BaseType
{
private string _type;
public SequenceOf(IModule module, string name, ISymbolEnumerator sym)
: base(module, name)
{
_type = sym.NextNonEOLSymbol().ToString();
}
public string Type
{
get { return _type; }
}
}
}

View File

@ -0,0 +1,238 @@
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public sealed class TextualConvention : ITypeAssignment, ITypeReferrer
{
private IModule _module;
private string _name;
private DisplayHint _displayHint;
private Status _status;
private string _description;
private string _reference;
private ITypeAssignment _syntax;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "module")]
public TextualConvention(IModule module, string name, ISymbolEnumerator symbols)
{
_module = module;
_name = name;
_displayHint = ParseDisplayHint(symbols);
_status = ParseStatus(symbols);
_description = ParseDescription(symbols);
_reference = ParseReference(symbols);
_syntax = ParseSyntax(module, symbols);
}
private static DisplayHint ParseDisplayHint(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.DisplayHint)
{
return new DisplayHint(symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' }));
}
symbols.PutBack(current);
return null;
}
private static Status ParseStatus(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Status);
try
{
return (Status)Enum.Parse(typeof(Status), symbols.NextNonEOLSymbol().ToString());
}
catch (ArgumentException)
{
current.Assert(false, "Invalid/Unknown status");
}
return Status.current;
}
private static string ParseDescription(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Description);
return symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' });
}
private static string ParseReference(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Reference)
{
string reference = symbols.NextNonEOLSymbol().ToString();
if ((reference.Length >= 2) && reference.StartsWith("\"") && reference.EndsWith("\""))
{
return reference.Substring(1, reference.Length-2);
}
return reference;
}
symbols.PutBack(current);
return null;
}
private static ITypeAssignment ParseSyntax(IModule module, ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Syntax);
/*
* RFC2579 definition:
* Syntax ::= -- Must be one of the following:
* -- a base type (or its refinement), or
* -- a BITS pseudo-type
* type
* | "BITS" "{" NamedBits "}"
*
* From section 3.5:
* The data structure must be one of the alternatives defined
* in the ObjectSyntax CHOICE or the BITS construct. Note
* that this means that the SYNTAX clause of a Textual
* Convention can not refer to a previously defined Textual
* Convention.
*
* The SYNTAX clause of a TEXTUAL CONVENTION macro may be
* sub-typed in the same way as the SYNTAX clause of an
* OBJECT-TYPE macro.
*
* Therefore the possible values are (grouped by underlying type):
* INTEGER, Integer32
* OCTET STRING, Opaque
* OBJECT IDENTIFIER
* IpAddress
* Counter64
* Unsigned32, Counter32, Gauge32, TimeTicks
* BITS
* With appropriate sub-typing.
*/
return Lexer.ParseBasicTypeDef(module, String.Empty, symbols, isMacroSyntax: true);
}
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
public string DisplayHint
{
get { return _displayHint == null ? null : _displayHint.ToString(); }
}
public Status Status
{
get { return _status; }
}
public string Description
{
get { return _description; }
}
public string Reference
{
get { return _reference; }
}
public ITypeAssignment Syntax
{
get { return _syntax; }
}
//internal object Decode(Variable v)
//{
// if (_syntax is IntegerType)
// {
// Integer32 i = v.Data as Integer32;
// if (i == null || (_syntax as IntegerType).IsEnumeration)
// {
// return null;
// }
// else if (_displayHint != null)
// {
// return _displayHint.Decode(i.ToInt32());
// }
// else
// {
// return i.ToInt32();
// }
// }
// else if (_syntax is UnsignedType)
// {
// Integer32 i = v.Data as Integer32;
// if (i == null)
// {
// return null;
// }
// else if (_displayHint != null)
// {
// return _displayHint.Decode(i.ToInt32());
// }
// else
// {
// return i.ToInt32();
// }
// }
// else if (_syntax is OctetStringType)
// {
// OctetString o = v.Data as OctetString;
// if (o == null)
// {
// return null;
// }
// else
// {
// // TODO: Follow the format specifier for octet strings.
// return null;
// }
// }
// else
// {
// return null;
// }
//}
#region ITypeReferrer Member
public ITypeAssignment ReferredType
{
get { return _syntax; }
set { _syntax = value; }
}
public ITypeAssignment BaseType
{
get
{
ITypeReferrer tr = this;
ITypeAssignment result = this;
while ((tr != null) && (tr.ReferredType != null))
{
result = tr.ReferredType;
tr = tr.ReferredType as ITypeReferrer;
}
return result;
}
}
#endregion
}
}

View File

@ -0,0 +1,147 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/18
* Time: 13:24
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/* Please be aware of the following possible constructs:
*
* isnsRegEntityIndex OBJECT-TYPE
* SYNTAX IsnsEntityIndexIdOrZero
* ( 1 .. 4294967295 )
* MAX-ACCESS not-accessible
*
*
*/
/// <summary/>
/// </summary>
public sealed class TypeAssignment : ITypeAssignment
{
private IModule _module;
private string _name;
private string _type;
private ValueRanges _ranges;
private ValueMap _map;
/// <summary>
/// Creates an <see cref="TypeAssignment" />.
/// </summary>
/// <param name="module">The module.</param>
/// <param name="name">The name.</param>
/// <param name="type">The type.</param>
/// <param name="symbols">The symbols.</param>
/// <param name="isMacroSyntax">if set to <c>true</c> indicates that the syntax clause of a macro is parsed (e.g. OBJECT-TYPE, TEXTUAL-CONVENTION).</param>
public TypeAssignment(IModule module, string name, Symbol type, ISymbolEnumerator symbols, bool isMacroSyntax)
{
_module = module;
_name = name;
SymbolList typeSymbols = new SymbolList();
typeSymbols.Add(type);
Symbol current = symbols.NextSymbol();
while (current != Symbol.EOL)
{
if (current == Symbol.OpenParentheses)
{
// parse range of unknown type
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
break;
}
else if (current == Symbol.OpenBracket)
{
symbols.PutBack(current);
_map = Lexer.DecodeEnumerations(symbols);
break;
}
typeSymbols.Add(current);
current = symbols.NextSymbol();
}
_type = typeSymbols.Join(" ");
if ((_ranges == null) && (_map == null))
{
current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenParentheses)
{
// parse range of unknown type
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
}
else if (current == Symbol.OpenBracket)
{
symbols.PutBack(current);
_map = Lexer.DecodeEnumerations(symbols);
}
else if (current != null)
{
symbols.PutBack(current);
}
}
if (isMacroSyntax)
{
// inside a macro the syntax is limited to one line, except there are brackets used for ranges/enums
return;
}
// outside macro Syntax clause we wait for two consecutive linebreaks with a following valid identifier as end condition
Symbol previous = current;
Symbol veryPrevious = null;
while ((current = symbols.NextSymbol()) != null)
{
if ((veryPrevious == Symbol.EOL) && (previous == Symbol.EOL) && current.IsValidIdentifier())
{
symbols.PutBack(current);
return;
}
veryPrevious = previous;
previous = current;
}
previous.Assert(false, "end of file reached");
}
public string Type
{
get { return _type; }
}
public ValueRanges Ranges
{
get { return _ranges; }
}
public IDictionary<long, string> Map
{
get { return _map; }
}
#region ITypeAssignment Member
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
#endregion
}
}

View File

@ -0,0 +1,103 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/**
* As this type is used for Counter32 and TimeTicks as well as Unsigned32
* and Gauge32 it incorrectly allows range restrictions of Counter32 and
* TimeTicks. This is ok as currently we do not care about detecting
* incorrect MIBs and this doesn't block the decoding of correct MIBs.
*/
public class UnsignedType : BaseType
{
public enum Types
{
Unsigned32,
Gauge32,
Counter32,
TimeTicks,
Counter64,
}
private Types _type;
private ValueRanges _ranges;
public UnsignedType(IModule module, string name, Symbol type, ISymbolEnumerator symbols)
: base(module, name)
{
Types? t = GetExactType(type);
type.Assert(t.HasValue, "Unknown symbol for unsigned type!");
_type = t.Value;
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenParentheses)
{
current.Assert((_type != Types.Counter64), "Ranges are not supported for Counter64 type!"); // our internal struct can only hold int64 values
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
current.Assert(!_ranges.IsSizeDeclaration, "SIZE keyword is not allowed for ranges of unsigned types!");
}
else
{
symbols.PutBack(current);
}
}
public Types Type
{
get { return _type; }
}
public ValueRanges Ranges
{
get { return _ranges; }
}
internal static Types? GetExactType(Symbol symbol)
{
if (symbol == Symbol.Unsigned32)
{
// [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI
return Types.Unsigned32;
}
else if (symbol == Symbol.Gauge32)
{
// [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI
return Types.Gauge32;
}
else if (symbol == Symbol.Counter32)
{
// [APPLICATION 1] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI
return Types.Counter32;
}
else if (symbol == Symbol.TimeTicks)
{
// [APPLICATION 3] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI + RFC1155-SMI
return Types.TimeTicks;
}
else if (symbol == Symbol.Gauge)
{
// [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) // from RFC1155-SMI
return Types.Gauge32;
}
else if (symbol == Symbol.Counter)
{
// [APPLICATION 1] IMPLICIT INTEGER (0..4294967295) // from RFC1155-SMI
return Types.Counter32;
}
else if (symbol == Symbol.Counter64)
{
// [APPLICATION 6] IMPLICIT INTEGER (0..18446744073709551615) // from SNMPv2-SMI
return Types.Counter64;
}
return null;
}
internal static bool IsUnsignedType(Symbol symbol)
{
return GetExactType(symbol).HasValue;
}
}
}

View File

@ -0,0 +1,81 @@
// Module interface.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/*
* Created by SharpDevelop.
* User: lextm
* Date: 5/1/2009
* Time: 10:40 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
using Lextm.SharpSnmpLib.Mib.Elements;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// MIB Module interface.
/// </summary>
public interface IModule
{
/// <summary>
/// Module name.
/// </summary>
string Name
{
get;
}
Exports Exports
{
get;
}
Imports Imports
{
get;
}
/// <summary>
/// Entities + Types + all other elements implementing IDeclaration
/// </summary>
IList<IDeclaration> Declarations
{
get;
}
/// <summary>
/// Entities.
/// </summary>
IList<IEntity> Entities
{
get;
}
/// <summary>
/// Known types.
/// </summary>
IList<ITypeAssignment> Types
{
get;
}
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib
{
public interface ISymbolEnumerator: IEnumerator<Symbol>
{
bool PutBack(Symbol item);
}
}

View File

@ -0,0 +1,581 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 16:50
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Lexer class that parses MIB files into symbol list.
/// </summary>
public sealed class Lexer
{
private readonly SymbolList _symbols = new SymbolList();
public Lexer(string file)
: this(file, new StreamReader(file))
{
}
public Lexer(string file, TextReader stream)
{
this.Parse(file, stream);
}
public ISymbolEnumerator GetEnumerator()
{
return _symbols.GetSymbolEnumerator();
}
#region Parsing of MIB File
private class ParseParams
{
public string File;
public StringBuilder Temp = new StringBuilder();
public bool StringSection = false;
public bool AssignSection = false;
public bool AssignAhead = false;
public bool DotSection = false;
}
/// <summary>
/// Parses MIB file to symbol list.
/// </summary>
/// <param name="file">File</param>
/// <param name="stream">File stream</param>
private void Parse(string file, TextReader stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
ParseParams pp = new ParseParams();
pp.File = file;
string line;
int row = 0;
while ((line = stream.ReadLine()) != null)
{
if (!pp.StringSection && line.TrimStart().StartsWith("--", StringComparison.Ordinal))
{
row++;
continue; // commented line
}
ParseLine(pp, line, row);
row++;
}
}
private void ParseLine(ParseParams pp, string line, int row)
{
line = line + "\n";
int count = line.Length;
for (int i = 0; i < count; i++)
{
char current = line[i];
bool moveNext = Parse(pp, current, row, i);
if (moveNext)
{
break;
}
}
}
private bool Parse(ParseParams pp, char current, int row, int column)
{
switch (current)
{
case '\n':
case '{':
case '}':
case '(':
case ')':
case '[':
case ']':
case ';':
case ',':
case '|':
if (!pp.StringSection)
{
bool moveNext = ParseLastSymbol(pp, row, column);
if (moveNext)
{
_symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
return true;
}
_symbols.Add(CreateSpecialSymbol(pp.File, current, row, column));
return false;
}
break;
case '"':
pp.StringSection = !pp.StringSection;
break;
case '\r':
return false;
default:
if ((int)current == 0x1A)
{
// IMPORTANT: ignore invisible characters such as SUB.
return false;
}
if (Char.IsWhiteSpace(current) && !pp.AssignSection && !pp.StringSection)
{
bool moveNext = ParseLastSymbol(pp, row, column);
if (moveNext)
{
_symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
return true;
}
return false;
}
if (pp.AssignAhead)
{
pp.AssignAhead = false;
ParseLastSymbol(pp, row, column);
break;
}
if (pp.DotSection && current != '.')
{
ParseLastSymbol(pp, row, column);
pp.DotSection = false;
}
if (current == '.' && !pp.StringSection)
{
if (!pp.DotSection)
{
ParseLastSymbol(pp, row, column);
pp.DotSection = true;
}
}
if (current == ':' && !pp.StringSection)
{
if (!pp.AssignSection)
{
ParseLastSymbol(pp, row, column);
}
pp.AssignSection = true;
}
if (current == '=' && !pp.StringSection)
{
pp.AssignSection = false;
pp.AssignAhead = true;
}
break;
}
pp.Temp.Append(current);
return false;
}
private bool ParseLastSymbol(ParseParams pp, int row, int column)
{
if (pp.Temp.Length > 0)
{
Symbol s = new Symbol(pp.File, pp.Temp.ToString(), row, column);
pp.Temp.Length = 0;
if (s.ToString().StartsWith(Symbol.Comment.ToString()))
{
// ignore the rest symbols on this line because they are in comment.
return true;
}
_symbols.Add(s);
}
return false;
}
private static Symbol CreateSpecialSymbol(string file, char value, int row, int column)
{
string str;
switch (value)
{
case '\n':
str = Environment.NewLine;
break;
case '{':
str = "{";
break;
case '}':
str = "}";
break;
case '(':
str = "(";
break;
case ')':
str = ")";
break;
case '[':
str = "[";
break;
case ']':
str = "]";
break;
case ';':
str = ";";
break;
case ',':
str = ",";
break;
case '|':
str = "|";
break;
default:
throw new ArgumentException("value is not a special character");
}
return new Symbol(file, str, row, column);
}
#endregion
#region Static Parse Helper
public static ITypeAssignment ParseBasicTypeDef(IModule module, string name, ISymbolEnumerator symbols, bool isMacroSyntax = false)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Bits)
{
return new BitsType(module, name, symbols);
}
if (IntegerType.IsIntegerType(current))
{
return new IntegerType(module, name, current, symbols);
}
if (UnsignedType.IsUnsignedType(current))
{
return new UnsignedType(module, name, current, symbols);
}
if (current == Symbol.Opaque)
{
return new OpaqueType(module, name, symbols);
}
if (current == Symbol.IpAddress)
{
return new IpAddressType(module, name, symbols);
}
if (current == Symbol.TextualConvention)
{
return new TextualConvention(module, name, symbols);
}
if (current == Symbol.Octet)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.String)
{
return new OctetStringType(module, name, symbols);
}
symbols.PutBack(next);
}
if (current == Symbol.Object)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.Identifier)
{
return new ObjectIdentifierType(module, name, symbols);
}
symbols.PutBack(next);
}
if (current == Symbol.Sequence)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.Of)
{
return new SequenceOf(module, name, symbols);
}
else
{
symbols.PutBack(next);
return new Sequence(module, name, symbols);
}
}
if (current == Symbol.Choice)
{
return new Choice(module, name, symbols);
}
return new TypeAssignment(module, name, current, symbols, isMacroSyntax);
}
public static void ParseOidValue(ISymbolEnumerator symbols, out string parent, out uint value)
{
parent = null;
value = 0;
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
Symbol previous = null;
StringBuilder longParent = new StringBuilder();
current = symbols.NextNonEOLSymbol();
longParent.Append(current);
while ((current = symbols.NextNonEOLSymbol()) != null)
{
bool succeeded;
if (current == Symbol.OpenParentheses)
{
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
longParent.Append(current);
continue;
}
if (current == Symbol.CloseBracket)
{
parent = longParent.ToString();
return;
}
succeeded = UInt32.TryParse(current.ToString(), out value);
if (succeeded)
{
// numerical way
while ((current = symbols.NextNonEOLSymbol()) != Symbol.CloseBracket)
{
longParent.Append(".").Append(value);
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
}
current.Expect(Symbol.CloseBracket);
parent = longParent.ToString();
return;
}
longParent.Append(".");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenParentheses);
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
longParent.Append(current);
previous = current;
}
throw MibException.Create("end of file reached", previous);
}
public static ValueRanges DecodeRanges(ISymbolEnumerator symbols)
{
ValueRanges result = new ValueRanges();
Symbol startSymbol = symbols.NextNonEOLSymbol();
Symbol current = startSymbol;
current.Expect(Symbol.OpenParentheses);
while (current != Symbol.CloseParentheses)
{
Symbol value1Symbol = symbols.NextNonEOLSymbol();
if ((value1Symbol == Symbol.Size) && !result.IsSizeDeclaration)
{
result.IsSizeDeclaration = true;
symbols.NextNonEOLSymbol().Expect(Symbol.OpenParentheses);
continue;
}
// check for valid number
Int64? value1 = DecodeNumber(value1Symbol);
if (!value1.HasValue)
{
value1Symbol.Assert(false, "Invalid range declaration!");
}
// process next symbol
ValueRange range;
current = symbols.NextNonEOLSymbol();
if (current == Symbol.DoubleDot)
{
// its a continuous range
Symbol value2Symbol = symbols.NextNonEOLSymbol();
Int64? value2 = DecodeNumber(value2Symbol);
value2Symbol.Assert(value2.HasValue && (value2.Value >= value1.Value), "Invalid range declaration!");
if (value2.Value == value1.Value)
{
range = new ValueRange(value1.Value, null);
}
else
{
range = new ValueRange(value1.Value, value2.Value);
}
current = symbols.NextNonEOLSymbol();
}
else
{
// its a single number
range = new ValueRange(value1.Value, null);
}
// validate range
if (result.IsSizeDeclaration)
{
value1Symbol.Assert(range.Start >= 0, "Invalid range declaration! Size must be greater than 0");
}
result.Add(range);
// check next symbol
current.Expect(Symbol.Pipe, Symbol.CloseParentheses);
}
if (result.IsSizeDeclaration)
{
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
}
// validate ranges in between
for (int i=0; i<result.Count; i++)
{
for (int k=i+1; k<result.Count; k++)
{
startSymbol.Assert(!result[i].IntersectsWith(result[k]), "Invalid range declaration! Overlapping of ranges!");
}
}
return result;
}
public static Int64? DecodeNumber(Symbol number)
{
Int64 result;
string numString = (number != null) ? number.ToString() : null;
if (!String.IsNullOrEmpty(numString))
{
if (numString.StartsWith("'") && (numString.Length > 3))
{
// search second apostrophe
int end = numString.IndexOf('\'', 1);
if (end == (numString.Length - 2))
{
try
{
switch (numString[numString.Length - 1])
{
case 'b':
case 'B':
result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 2);
return result;
case 'h':
case 'H':
result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 16);
return result;
}
}
catch
{
}
}
}
else if (Int64.TryParse(numString, out result))
{
return result;
}
}
return null;
}
public static ValueMap DecodeEnumerations(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
ValueMap map = new ValueMap();
do
{
current = symbols.NextNonEOLSymbol();
string identifier = current.ToString();
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenParentheses);
current = symbols.NextNonEOLSymbol();
Int64 enumValue;
if (Int64.TryParse(current.ToString(), out enumValue))
{
try
{
// Have to include the number as it seems repeated identifiers are allowed ??
map.Add(enumValue, String.Format("{0}({1})", identifier, enumValue));
}
catch (ArgumentException ex)
{
current.Assert(false, ex.Message);
}
}
else
{
// Need to get "DefinedValue".
}
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
current = symbols.NextNonEOLSymbol();
} while (current == Symbol.Comma);
current.Expect(Symbol.CloseBracket);
return map;
}
#endregion
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib
{
public enum MaxAccess
{
notAccessible,
accessibleForNotify,
readOnly,
readWrite,
readCreate
}
}

View File

@ -0,0 +1,57 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 17:38
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// MIB document.
/// </summary>
public sealed class MibDocument
{
private readonly List<IModule> _modules = new List<IModule>();
/// <summary>
/// Initializes a new instance of the <see cref="MibDocument" /> class.
/// </summary>
/// <param name="file">The file.</param>
public MibDocument(string file)
: this(new Lexer(file))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MibDocument"/> class.
/// </summary>
/// <param name="lexer">The lexer.</param>
public MibDocument(Lexer lexer)
{
ISymbolEnumerator symbols = lexer.GetEnumerator();
Symbol current;
while ((current = symbols.NextNonEOLSymbol()) != null)
{
symbols.PutBack(current);
_modules.Add(new MibModule(symbols));
}
}
/// <summary>
/// <see cref="MibModule"/> containing in this document.
/// </summary>
public IList<IModule> Modules
{
get
{
return _modules;
}
}
}
}

View File

@ -0,0 +1,113 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 16:33
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Globalization;
#if (!SILVERLIGHT)
using System.Runtime.Serialization;
using System.Security.Permissions;
#endif
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Description of MibException.
/// </summary>
[Serializable]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mib")]
public sealed class MibException : Exception
{
/// <summary>
/// Symbol.
/// </summary>
public Symbol Symbol { get; private set; }
/// <summary>
/// Creates a <see cref="MibException"/>.
/// </summary>
public MibException()
{
}
/// <summary>
/// Creates a <see cref="SnmpException"/> instance with a specific <see cref="string"/>.
/// </summary>
/// <param name="message">Message</param>
public MibException(string message) : base(message)
{
}
/// <summary>
/// Creates a <see cref="MibException"/> instance with a specific <see cref="string"/> and an <see cref="Exception"/>.
/// </summary>
/// <param name="message">Message</param>
/// <param name="inner">Inner exception</param>
public MibException(string message, Exception inner)
: base(message, inner)
{
}
#if (!SILVERLIGHT)
/// <summary>
/// Creates a <see cref="MibException"/> instance.
/// </summary>
/// <param name="info">Info</param>
/// <param name="context">Context</param>
private MibException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Symbol = (Symbol)info.GetValue("Symbol", typeof(Symbol));
}
/// <summary>
/// Gets object data.
/// </summary>
/// <param name="info">Info</param>
/// <param name="context">Context</param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Symbol", Symbol);
}
#endif
/// <summary>
/// Creates a <see cref="MibException"/> with a specific <see cref="Symbol"/>.
/// </summary>
/// <param name="message">Message</param>
/// <param name="symbol">Symbol</param>
/// <returns></returns>
public static MibException Create(string message, Symbol symbol)
{
if (symbol == null)
{
throw new ArgumentNullException("symbol");
}
if (String.IsNullOrEmpty(message))
{
message = "Unknown MIB Exception";
}
message = String.Format(
"{0} (file: \"{1}\"; row: {2}; column: {3})",
message,
symbol.File,
symbol.Row + 1,
symbol.Column + 1);
MibException ex = new MibException(message) { Symbol = symbol };
return ex;
}
}
}

View File

@ -0,0 +1,294 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 17:38
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// MIB module class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mib")]
public sealed class MibModule : IModule
{
private readonly string _name;
private readonly Imports _imports;
private readonly Exports _exports;
private readonly List<IElement> _tokens = new List<IElement>();
/// <summary>
/// Creates a <see cref="MibModule"/> with a specific <see cref="Lexer"/>.
/// </summary>
/// <param name="name">Module name</param>
/// <param name="symbols">Lexer</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "lexer")]
public MibModule(ISymbolEnumerator symbols)
{
if (symbols == null)
{
throw new ArgumentNullException("lexer");
}
Symbol temp = symbols.NextNonEOLSymbol();
temp.AssertIsValidIdentifier();
_name = temp.ToString().ToUpperInvariant(); // all module names are uppercase
temp = symbols.NextNonEOLSymbol();
temp.Expect(Symbol.Definitions);
temp = symbols.NextNonEOLSymbol();
temp.Expect(Symbol.Assign);
temp = symbols.NextSymbol();
temp.Expect(Symbol.Begin);
temp = symbols.NextNonEOLSymbol();
if (temp == Symbol.Imports)
{
_imports = ParseDependents(symbols);
}
else if (temp == Symbol.Exports)
{
_exports = ParseExports(symbols);
}
else
{
symbols.PutBack(temp);
}
ParseEntities(symbols);
}
#region Accessors
/// <summary>
/// Module name.
/// </summary>
public string Name
{
get { return _name; }
}
public Exports Exports
{
get { return _exports; }
}
public Imports Imports
{
get { return _imports; }
}
public List<IElement> Tokens
{
get { return this._tokens; }
}
/// <summary>
/// Entities + Types + all other elements implementing IDeclaration
/// </summary>
public IList<IDeclaration> Declarations
{
get
{
IList<IDeclaration> result = new List<IDeclaration>();
foreach (IElement e in _tokens)
{
IDeclaration decl = e as IDeclaration;
if (decl != null)
{
result.Add(decl);
}
}
return result;
}
}
/// <summary>
/// OID nodes.
/// </summary>
public IList<IEntity> Entities
{
get
{
IList<IEntity> result = new List<IEntity>();
foreach (IElement e in _tokens)
{
IEntity entity = e as IEntity;
if (entity != null)
{
result.Add(entity);
}
}
return result;
}
}
public IList<ITypeAssignment> Types
{
get
{
IList<ITypeAssignment> result = new List<ITypeAssignment>();
foreach (IElement e in _tokens)
{
ITypeAssignment type = e as ITypeAssignment;
if (type != null)
{
result.Add(type);
}
}
return result;
}
}
#endregion
#region Parsing of Symbols
private Exports ParseExports(ISymbolEnumerator symbols)
{
return new Exports(this, symbols);
}
private Imports ParseDependents(ISymbolEnumerator symbols)
{
return new Imports(this, symbols);
}
private void ParseEntities(ISymbolEnumerator symbols)
{
Symbol temp = symbols.NextNonEOLSymbol();
SymbolList buffer = new SymbolList();
while (temp != Symbol.End)
{
if (temp == Symbol.Assign)
{
ParseEntity(buffer, symbols);
buffer.Clear();
// skip linebreaks behind an entity
temp = symbols.NextNonEOLSymbol();
}
else
{
buffer.Add(temp);
temp = symbols.NextSymbol();
}
}
}
private void ParseEntity(SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
if ((preAssignSymbols == null) || (preAssignSymbols.Count == 0))
{
Symbol s = symbols.NextSymbol();
if (s != null)
{
s.Assert(false, "Invalid Entity declaration");
}
else
{
throw new MibException("Invalid Entity declaration");
}
}
// check for a valid identifier
preAssignSymbols[0].AssertIsValidIdentifier();
if (preAssignSymbols.Count == 1)
{
// its a typedef
_tokens.Add(Lexer.ParseBasicTypeDef(this, preAssignSymbols[0].ToString(), symbols, isMacroSyntax: false));
return;
}
ISymbolEnumerator preAssignSymbolsEnumerator = preAssignSymbols.GetSymbolEnumerator();
preAssignSymbolsEnumerator.NextNonEOLSymbol(); // returns identifier
Symbol type = preAssignSymbolsEnumerator.NextNonEOLSymbol();
// parse declarations
if (type == Symbol.Object)
{
Symbol next = preAssignSymbolsEnumerator.NextNonEOLSymbol();
if (next == Symbol.Identifier)
{
_tokens.Add(new OidValueAssignment(this, preAssignSymbols, symbols));
return;
}
else if (next != null)
{
preAssignSymbolsEnumerator.PutBack(next);
}
}
if (type == Symbol.ModuleIdentity)
{
_tokens.Add(new ModuleIdentity(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ObjectType)
{
_tokens.Add(new ObjectType(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ObjectGroup)
{
_tokens.Add(new ObjectGroup(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.NotificationGroup)
{
_tokens.Add(new NotificationGroup(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ModuleCompliance)
{
_tokens.Add(new ModuleCompliance(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.NotificationType)
{
_tokens.Add(new NotificationType(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ObjectIdentity)
{
_tokens.Add(new ObjectIdentity(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.Macro)
{
_tokens.Add(new Macro(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.TrapType)
{
_tokens.Add(new TrapType(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.AgentCapabilities)
{
_tokens.Add(new AgentCapabilities(this, preAssignSymbols, symbols));
return;
}
preAssignSymbols[1].Assert(false, "Unknown/Invalid declaration");
}
#endregion
}
}

View File

@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
namespace Lextm.SharpSnmpLib.Mib
{
public interface IMibResolver
{
IModule Resolve(string moduleName);
}
public class FileSystemMibResolver : IMibResolver
{
private string _path;
private bool _recursive;
public FileSystemMibResolver(string path, bool recursive)
{
_path = path;
_recursive = recursive;
}
#region IMibResolver Member
public IModule Resolve(string moduleName)
{
if (Directory.Exists(_path))
{
string[] matchedFiles = Directory.GetFiles(
_path,
"*",
(_recursive) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
if ((matchedFiles != null) && (matchedFiles.Length >= 1))
{
foreach (string matchedFile in matchedFiles)
{
if (Path.GetFileNameWithoutExtension(matchedFile.ToLowerInvariant()) == moduleName.ToLowerInvariant())
{
try
{
MibDocument md = new MibDocument (matchedFile);
if (md.Modules.Count > 0)
{
return md.Modules [0];
}
} catch
{
}
}
}
}
}
return null;
}
#endregion
}
// earlier code for search of versioned MIBs:
//
//private const string Pattern = "-V[0-9]+$";
//public static bool AllDependentsAvailable(MibModule module, IDictionary<string, MibModule> modules)
//{
// foreach (string dependent in module.Dependents)
// {
// if (!DependentFound(dependent, modules))
// {
// return false;
// }
// }
// return true;
//}
//private static bool DependentFound(string dependent, IDictionary<string, MibModule> modules)
//{
// if (!Regex.IsMatch(dependent, Pattern))
// {
// return modules.ContainsKey(dependent);
// }
// if (modules.ContainsKey(dependent))
// {
// return true;
// }
// string dependentNonVersion = Regex.Replace(dependent, Pattern, string.Empty);
// return modules.ContainsKey(dependentNonVersion);
//}
}

View File

@ -0,0 +1,130 @@
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Builds up a tree from a single MIB
/// </summary>
public class MibTree
{
private readonly List<MibTreeNode> _root = new List<MibTreeNode>();
public MibTree(MibModule module)
{
IList<IEntity> entities = module.Entities;
if (entities.Count > 0)
{
// try to find module identity as root
foreach (IEntity element in entities)
{
ModuleIdentity mi = element as ModuleIdentity;
if (mi != null)
{
_root.Add(new MibTreeNode(null, mi));
}
}
// find OID assignments as root, if there are any that are not below ModuleIdentity
foreach (IEntity element in entities)
{
OidValueAssignment oa = element as OidValueAssignment;
if (oa != null)
{
_root.Add(new MibTreeNode(null, oa));
}
}
FilterRealRoots (entities);
foreach (MibTreeNode mibTreeNode in _root)
{
entities.Remove (mibTreeNode.Entity);
}
if (_root.Count == 0)
{
//no module identity, assume first entity is root
_root.Add(new MibTreeNode(null, entities[0]));
}
foreach (MibTreeNode mibTreeNode in _root)
{
if (entities.Contains (mibTreeNode.Entity))
{
entities.Remove (mibTreeNode.Entity);
}
BuildTree(mibTreeNode, entities);
UpdateTreeNodeTypes(mibTreeNode);
}
}
}
public IList<MibTreeNode> Root
{
get { return _root; }
}
private bool EntityExists(IList<IEntity> entities, string name)
{
foreach(IEntity entity in entities)
{
if (entity.Name == name)
{
return true;
}
}
return false;
}
private void FilterRealRoots(IList<IEntity> entities)
{
int i = 0;
while (i < _root.Count)
{
if (EntityExists(entities, _root[i].Entity.Parent))
{
_root.RemoveAt(i);
}
else
{
i++;
}
}
}
private void BuildTree(MibTreeNode node, IList<IEntity> entities)
{
int i = 0;
while (i < entities.Count)
{
if (entities[i].Parent == node.Entity.Name)
{
node.AddChild(entities[i]);
entities.RemoveAt(i);
}
else
{
i++;
}
}
foreach (MibTreeNode childNode in node.ChildNodes)
{
BuildTree(childNode, entities);
}
}
private void UpdateTreeNodeTypes(MibTreeNode node)
{
node.UpdateNodeType();
foreach (MibTreeNode childNode in node.ChildNodes)
{
UpdateTreeNodeTypes(childNode);
}
}
}
}

View File

@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib
{
[Flags]
public enum MibTreeNodeType
{
Unknown = 0,
Container = (1 << 0),
Scalar = (1 << 1),
Table = (1 << 2),
TableRow = (1 << 3),
TableCell = (1 << 4),
NotificationRelated = (1 << 5),
ConformanceRelated = (1 << 6)
}
public class MibTreeNode
{
private MibTreeNode _parent = null;
private List<MibTreeNode> _childNodes = new List<MibTreeNode>();
private IEntity _entity = null;
private MibTreeNodeType _nodeType = MibTreeNodeType.Unknown;
public MibTreeNode(MibTreeNode parent, IEntity entity)
{
_parent = parent;
_entity = entity;
}
public MibTreeNode Parent
{
get { return _parent; }
}
public IEntity Entity
{
get { return _entity; }
}
public MibTreeNodeType NodeType
{
get { return _nodeType; }
}
public List<MibTreeNode> ChildNodes
{
get { return _childNodes; }
}
public MibTreeNode AddChild(IEntity element)
{
MibTreeNode result = new MibTreeNode(this, element);
this.ChildNodes.Add(result);
return result;
}
public void UpdateNodeType()
{
_nodeType = MibTreeNodeType.Unknown;
if (_entity != null)
{
if ((_entity is OidValueAssignment) || (_entity is ObjectIdentity))
{
_nodeType |= MibTreeNodeType.Container;
return;
}
else if (_childNodes.Count > 0)
{
_nodeType |= MibTreeNodeType.Container;
}
if (_entity is ObjectType)
{
ObjectType ot = _entity as ObjectType;
if (ot.Syntax is SequenceOf)
{
_nodeType |= MibTreeNodeType.Table;
}
else if (ot.Syntax is Sequence)
{
_nodeType |= MibTreeNodeType.TableRow;
}
else if ((_parent != null) && ((_parent.NodeType & MibTreeNodeType.TableRow) != 0))
{
_nodeType |= MibTreeNodeType.TableCell;
_nodeType |= MibTreeNodeType.Scalar;
}
else
{
_nodeType |= MibTreeNodeType.Scalar;
}
}
else if ((_entity is ModuleCompliance) || (_entity is ObjectGroup) || (_entity is NotificationGroup))
{
_nodeType |= MibTreeNodeType.ConformanceRelated;
}
else if ((_entity is NotificationGroup) || (_entity is NotificationType))
{
_nodeType |= MibTreeNodeType.NotificationRelated;
}
}
}
}
}

View File

@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Lextm.SharpSnmpLib.Mib.Elements;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib
{
public static class MibTypesResolver
{
private static readonly Regex _namedOidPathRegex = new Regex(@"^(?<Name>[^\(]+)\((?<Value>\d+)\)$");
private static readonly List<IMibResolver> _resolver = new List<IMibResolver>();
private static readonly List<IModule> _cachedModules = new List<IModule>();
public static void RegisterResolver(IMibResolver resolver)
{
if (resolver != null)
{
_resolver.Add(resolver);
}
}
public static IModule ResolveModule(string moduleName)
{
// check if module is already cached
foreach (MibModule cachedModule in _cachedModules)
{
if (cachedModule.Name == moduleName)
{
return cachedModule;
}
}
foreach (IMibResolver resolver in _resolver)
{
IModule resolvedModule = resolver.Resolve(moduleName);
if (resolvedModule != null)
{
ResolveTypes(resolvedModule);
_cachedModules.Add(resolvedModule);
return resolvedModule;
}
}
return null;
}
public static void ResolveTypes(IModule module)
{
foreach (IEntity entity in module.Entities)
{
ITypeReferrer typeReferringEntity = entity as ITypeReferrer;
if (typeReferringEntity != null)
{
CheckTypeReferrer(module, typeReferringEntity);
}
}
if (!_cachedModules.Contains(module))
{
_cachedModules.Add(module);
}
}
private static void CheckTypeReferrer(IModule module, ITypeReferrer typeReferringEntity)
{
TypeAssignment unknownType = typeReferringEntity.ReferredType as TypeAssignment;
if (unknownType != null)
{
typeReferringEntity.ReferredType = ResolveType(module, unknownType);
if (typeReferringEntity.ReferredType is TypeAssignment)
{
Console.WriteLine(String.Format("Could not resolve type '{0}' declared in module '{1}'", (typeReferringEntity.ReferredType as TypeAssignment).Type, typeReferringEntity.ReferredType.Module.Name));
}
}
ITypeReferrer nextTypeReferringEntity = typeReferringEntity.ReferredType as ITypeReferrer;
if (nextTypeReferringEntity != null)
{
CheckTypeReferrer(module, nextTypeReferringEntity);
}
}
public static ITypeAssignment ResolveType(IModule module, TypeAssignment type)
{
ITypeAssignment result = ResolveDeclaration(module, type.Type) as ITypeAssignment;
return (result != null) ? result : type;
}
public static IDeclaration ResolveDeclaration(IModule module, string name)
{
if ((module == null) || String.IsNullOrEmpty(name))
{
return null;
}
// check module internal types
foreach (IDeclaration decl in module.Declarations)
{
if (decl.Name == name)
{
return decl;
}
}
// check if type is imported
if (module.Imports != null)
{
ImportsFrom imports = module.Imports.GetImportFromType(name);
if (imports != null)
{
IModule importedModule = ResolveModule(imports.Module);
if (importedModule != null)
{
return ResolveDeclaration(importedModule, name);
}
}
}
return null;
}
public static ObjectIdentifier ResolveOid(IEntity entity)
{
ObjectIdentifier result = new ObjectIdentifier();
if (entity != null)
{
ResolveOid(entity, result);
}
return result;
}
private static void ResolveOid(IEntity entity, ObjectIdentifier result)
{
result.Prepend(entity.Name, entity.Value);
// check parent
if (!String.IsNullOrEmpty(entity.Parent))
{
string[] pathParts = entity.Parent.Split('.');
uint value;
// all parts except the first should have their value directly or indirectly with them
if (pathParts.Length > 1)
{
for (int i=pathParts.Length-1; i>=1; i--)
{
if (uint.TryParse(pathParts[i], out value))
{
result.Prepend("", value);
}
else
{
Match m = _namedOidPathRegex.Match(pathParts[i]);
if (m.Success)
{
result.Prepend(m.Groups["Name"].Value, uint.Parse(m.Groups["Value"].Value));
}
else
{
throw new MibException("Invalid OID path detected for entity '" + entity.Name + "' in module '" + entity.Module + "'!");
}
}
}
}
// parse root part: either another entity or a standard root object
if (IsOidRoot(pathParts[0], out value))
{
result.Prepend(pathParts[0], value);
}
else
{
// try to find entity inside this module
if (entity.Module != null)
{
entity = ResolveDeclaration(entity.Module, pathParts[0]) as IEntity;
if (entity != null)
{
ResolveOid(entity, result);
}
else
{
result.Prepend("", uint.MaxValue);
}
}
else
{
result.Prepend("", uint.MaxValue);
}
}
}
}
public static bool IsOidRoot(string name, out uint value)
{
value = uint.MaxValue;
switch (name)
{
case "ccitt": value = 0; return true;
case "iso": value = 1; return true;
case "joint-iso-ccitt": value = 2; return true;
}
return false;
}
}
}

View File

@ -0,0 +1,54 @@
using System.Collections.Generic;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib
{
public class ObjectIdentifier: List<KeyValuePair<string, uint>>
{
public void Add(string name, uint oid)
{
this.Add(new KeyValuePair<string, uint>(name, oid));
}
public void Prepend(string name, uint oid)
{
this.Insert(0, new KeyValuePair<string, uint>(name, oid));
}
public void Insert(int index, string name, uint oid)
{
this.Insert(index, new KeyValuePair<string, uint>(name, oid));
}
public string GetOidString()
{
StringBuilder result = new StringBuilder();
foreach (KeyValuePair<string, uint> level in this)
{
result.Append(level.Value);
result.Append('.');
}
if (result.Length > 0)
{
result.Length--;
}
return result.ToString();
}
public uint[] GetOidValues()
{
List<uint> result = new List<uint>();
foreach (KeyValuePair<string, uint> level in this)
{
result.Add(level.Value);
}
return result.ToArray();
}
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib
{
public enum Status
{
current,
deprecated,
obsolete,
mandatory,
optional
}
}

View File

@ -0,0 +1,357 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 17:14
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Configuration;
using System.Globalization;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Description of Symbol.
/// </summary>
public sealed class Symbol : IEquatable<Symbol>
{
private readonly string _text;
private readonly int _row;
private readonly int _column;
private readonly string _file;
private Symbol(string text) : this(null, text, -1, -1)
{
}
/// <summary>
/// Creates a <see cref="Symbol"/>.
/// </summary>
/// <param name="file">File</param>
/// <param name="text">Text</param>
/// <param name="row">Row number</param>
/// <param name="column">column number</param>
public Symbol(string file, string text, int row, int column)
{
_file = file;
_text = text;
_row = row;
_column = column;
}
/// <summary>
/// File.
/// </summary>
public string File
{
get
{
return _file;
}
}
/// <summary>
/// Row number.
/// </summary>
public int Row
{
get
{
return _row;
}
}
/// <summary>
/// Column number.
/// </summary>
public int Column
{
get
{
return _column;
}
}
/// <summary>
/// Returns a <see cref="String"/> that represents this <see cref="Symbol"/>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _text;
}
/// <summary>
/// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Symbol"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="Symbol"/>. </param>
/// <returns><value>true</value> if the specified <see cref="Object"/> is equal to the current <see cref="Symbol"/>; otherwise, <value>false</value>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return GetType() == obj.GetType() && Equals((Symbol)obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>A hash code for the current <see cref="Symbol"/>.</returns>
public override int GetHashCode()
{
return _text.GetHashCode();
}
/// <summary>
/// The equality operator.
/// </summary>
/// <param name="left">Left <see cref="Symbol"/> object</param>
/// <param name="right">Right <see cref="Symbol"/> object</param>
/// <returns>
/// Returns <c>true</c> if the values of its operands are equal, <c>false</c> otherwise.</returns>
public static bool operator ==(Symbol left, Symbol right)
{
return Equals(left, right);
}
/// <summary>
/// Determines whether the specified <see cref="Symbol"/> is equal to the current <see cref="Symbol"/>.
/// </summary>
/// <param name="left">Left <see cref="Symbol"/> object</param>
/// <param name="right">Right <see cref="Symbol"/> object</param>
/// <returns>
/// Returns <c>true</c> if the values of its operands are equal, <c>false</c> otherwise.</returns>
public static bool Equals(Symbol left, Symbol right)
{
object l = left;
object r = right;
if (l == r)
{
return true;
}
if (l == null || r == null)
{
return false;
}
return left._text.Equals(right._text);
}
/// <summary>
/// The inequality operator.
/// </summary>
/// <param name="left">Left <see cref="Symbol"/> object</param>
/// <param name="right">Right <see cref="Symbol"/> object</param>
/// <returns>
/// Returns <c>true</c> if the values of its operands are not equal, <c>false</c> otherwise.</returns>
public static bool operator !=(Symbol left, Symbol right)
{
return !(left == right);
}
#region IEquatable<Symbol> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns><value>true</value> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <value>false</value>.
/// </returns>
public bool Equals(Symbol other)
{
return Equals(this, other);
}
#endregion
public static readonly Symbol Definitions = new Symbol("DEFINITIONS");
public static readonly Symbol Begin = new Symbol("BEGIN");
public static readonly Symbol Object = new Symbol("OBJECT");
public static readonly Symbol Identifier = new Symbol("IDENTIFIER");
public static readonly Symbol Assign = new Symbol("::=");
public static readonly Symbol OpenBracket = new Symbol("{");
public static readonly Symbol CloseBracket = new Symbol("}");
public static readonly Symbol Comment = new Symbol("--");
public static readonly Symbol Imports = new Symbol("IMPORTS");
public static readonly Symbol Semicolon = new Symbol(";");
public static readonly Symbol From = new Symbol("FROM");
public static readonly Symbol ModuleIdentity = new Symbol("MODULE-IDENTITY");
public static readonly Symbol ObjectType = new Symbol("OBJECT-TYPE");
public static readonly Symbol ObjectGroup = new Symbol("OBJECT-GROUP");
public static readonly Symbol NotificationGroup = new Symbol("NOTIFICATION-GROUP");
public static readonly Symbol ModuleCompliance = new Symbol("MODULE-COMPLIANCE");
public static readonly Symbol Sequence = new Symbol("SEQUENCE");
public static readonly Symbol NotificationType = new Symbol("NOTIFICATION-TYPE");
public static readonly Symbol EOL = new Symbol(Environment.NewLine);
public static readonly Symbol ObjectIdentity = new Symbol("OBJECT-IDENTITY");
public static readonly Symbol End = new Symbol("END");
public static readonly Symbol Macro = new Symbol("MACRO");
public static readonly Symbol Choice = new Symbol("CHOICE");
public static readonly Symbol TrapType = new Symbol("TRAP-TYPE");
public static readonly Symbol AgentCapabilities = new Symbol("AGENT-CAPABILITIES");
public static readonly Symbol Comma = new Symbol(",");
public static readonly Symbol TextualConvention = new Symbol("TEXTUAL-CONVENTION");
public static readonly Symbol Syntax = new Symbol("SYNTAX");
public static readonly Symbol Bits = new Symbol("BITS");
public static readonly Symbol Octet = new Symbol("OCTET");
public static readonly Symbol String = new Symbol("STRING");
public static readonly Symbol OpenParentheses = new Symbol("(");
public static readonly Symbol CloseParentheses = new Symbol(")");
public static readonly Symbol Exports = new Symbol("EXPORTS");
public static readonly Symbol DisplayHint = new Symbol("DISPLAY-HINT");
public static readonly Symbol Status = new Symbol("STATUS");
public static readonly Symbol Description = new Symbol("DESCRIPTION");
public static readonly Symbol Reference = new Symbol("REFERENCE");
public static readonly Symbol DoubleDot = new Symbol("..");
public static readonly Symbol Pipe = new Symbol("|");
public static readonly Symbol Size = new Symbol("SIZE");
public static readonly Symbol Units = new Symbol("UNITS");
public static readonly Symbol MaxAccess = new Symbol("MAX-ACCESS");
public static readonly Symbol Access = new Symbol("ACCESS");
public static readonly Symbol Index = new Symbol("INDEX");
public static readonly Symbol Augments = new Symbol("AUGMENTS");
public static readonly Symbol DefVal = new Symbol("DEFVAL");
public static readonly Symbol Of = new Symbol("OF");
public static readonly Symbol Integer = new Symbol("INTEGER");
public static readonly Symbol Integer32 = new Symbol("Integer32");
public static readonly Symbol IpAddress = new Symbol("IpAddress");
public static readonly Symbol Counter32 = new Symbol("Counter32");
public static readonly Symbol Counter = new Symbol("Counter");
public static readonly Symbol TimeTicks = new Symbol("TimeTicks");
public static readonly Symbol Opaque = new Symbol("Opaque");
public static readonly Symbol Counter64 = new Symbol("Counter64");
public static readonly Symbol Unsigned32 = new Symbol("Unsigned32");
public static readonly Symbol Gauge32 = new Symbol("Gauge32");
public static readonly Symbol Gauge = new Symbol("Gauge");
public static readonly Symbol TruthValue = new Symbol("TruthValue");
public static readonly Symbol Implied = new Symbol("IMPLIED");
internal void Expect(Symbol expected, params Symbol[] orExpected)
{
bool isExpected = (this == expected);
if (!isExpected && (orExpected != null) && (orExpected.Length > 0))
{
// check the alternatives
for (int i=0; i<orExpected.Length; i++)
{
if (this == orExpected[i])
{
isExpected = true;
break;
}
}
}
if (!isExpected)
{
if ((orExpected == null) || (orExpected.Length == 0))
{
Assert(false, "Unexpected symbol found! Expected '" + expected.ToString() + "'");
}
else
{
StringBuilder msg = new StringBuilder("Unexpected symbol found! Expected one of the following: '");
msg.Append(expected);
// check the alternatives
for (int i=0; i<orExpected.Length; i++)
{
msg.Append("', '");
msg.Append(expected);
}
msg.Append("'");
Assert(false, msg.ToString());
}
}
}
internal void Assert(bool condition, string message)
{
if (!condition)
{
throw MibException.Create(message, this);
}
}
internal void AssertIsValidIdentifier()
{
string message;
bool isValid = IsValidIdentifier(ToString(), out message);
Assert(isValid, message);
}
internal bool IsValidIdentifier()
{
string message;
return IsValidIdentifier(ToString(), out message);
}
private static bool IsValidIdentifier(string name, out string message)
{
if (UseStricterValidation && (name.Length < 1 || name.Length > 64))
{
message = "an identifier must consist of 1 to 64 letters, digits, and hyphens";
return false;
}
if (!Char.IsLetter(name[0]))
{
message = "the initial character must be a letter";
return false;
}
if (name.EndsWith("-", StringComparison.Ordinal))
{
message = "a hyphen cannot be the last character of an identifier";
return false;
}
if (name.Contains("--"))
{
message = "a hyphen cannot be immediately followed by another hyphen in an identifier";
return false;
}
if (UseStricterValidation && name.Contains("_"))
{
message = "underscores are not allowed in identifiers";
return false;
}
// TODO: SMIv2 forbids "-" except in module names and keywords
message = null;
return true;
}
private static bool? _useStricterValidation;
private static bool UseStricterValidation
{
get
{
if (_useStricterValidation == null)
{
object setting = ConfigurationManager.AppSettings["StricterValidationEnabled"];
_useStricterValidation = setting != null && Convert.ToBoolean(setting.ToString(), CultureInfo.InvariantCulture);
}
return _useStricterValidation.Value;
}
}
}
}

View File

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib
{
public class SymbolList : List<Symbol>
{
public class SymbolEnumerator : ISymbolEnumerator
{
private SymbolList _list = null;
private int _index = -1;
internal SymbolEnumerator(SymbolList list)
{
if (list == null)
{
throw new ArgumentNullException("lexer");
}
_list = list;
}
#region ISymbolEnumerator Member
public bool PutBack(Symbol item)
{
if ((_index < 0) || (_index >= _list.Count) || (item != _list[_index]))
{
throw new ArgumentException(@"wrong last symbol", "last");
//return false;
}
_index--;
return true;
}
#endregion
#region IEnumerator<Symbol> Member
public Symbol Current
{
get
{
if ((_index >= 0) && (_index <= _list.Count))
{
return _list[_index];
}
return null;
}
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
#region IEnumerator Member
object System.Collections.IEnumerator.Current
{
get { return this.Current; }
}
public bool MoveNext()
{
_index++;
return (_index >= 0) && (_index < _list.Count);
}
public void Reset()
{
_index = -1;
}
#endregion
}
/// <summary>
/// Initializes a new instance of the <see cref="SymbolList"/> class.
/// </summary>
public SymbolList()
{
}
public ISymbolEnumerator GetSymbolEnumerator()
{
return new SymbolEnumerator(this);
}
public string Join(string separator)
{
if (separator == null)
separator = "";
StringBuilder result = new StringBuilder();
foreach (Symbol s in this)
{
result.Append(s);
result.Append(separator);
}
if (result.Length > 0)
{
result.Length -= separator.Length;
}
return result.ToString();
}
}
public static class SymbolEnumeratorExtension
{
public static Symbol NextSymbol(this IEnumerator<Symbol> enumerator)
{
if (enumerator.MoveNext())
{
return enumerator.Current;
}
return null;
}
public static Symbol NextNonEOLSymbol(this IEnumerator<Symbol> enumerator)
{
while (enumerator.MoveNext())
{
if (enumerator.Current != Symbol.EOL)
{
return enumerator.Current;
}
}
return null;
}
}
}

View File

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib
{
public class ValueMap : Dictionary<Int64, string>
{
public ValueMap()
{
}
/// <summary>
/// Returns the values of the map as continuous range. At best as one range.
/// </summary>
/// <returns></returns>
public ValueRanges GetContinousRanges()
{
ValueRanges result = new ValueRanges();
if (this.Count > 0)
{
List<Int64> values = new List<long>(this.Keys);
values.Sort();
Int64 last = values[0];
Int64 offset = values[0];
for (int i=1; i<values.Count; i++)
{
if (values[i] != last + 1)
{
if (last == offset)
{
result.Add(new ValueRange(offset, null));
}
else
{
result.Add(new ValueRange(offset, last));
}
offset = values[i];
}
last = values[i];
}
if (last == offset)
{
result.Add(new ValueRange(offset, null));
}
else
{
result.Add(new ValueRange(offset, last));
}
}
return result;
}
/// <summary>
/// Gets the highest value contained in this value map.
/// </summary>
/// <returns></returns>
public Int64 GetHighestValue()
{
Int64 result = 0;
foreach (Int64 value in this.Keys)
{
if (value > result)
{
result = value;
}
}
return result;
}
/// <summary>
/// Interprets the single values as bit positions and creates a mask of it.
/// </summary>
/// <returns></returns>
public UInt32 GetBitMask()
{
UInt32 result = 0;
foreach (Int64 key in this.Keys)
{
if (key < 0)
{
throw new NotSupportedException("Negative numbers are not allowed for Bits!");
}
if (key > 31)
{
throw new NotSupportedException("Bits with more than 32 bits are not supported!");
}
result |= (UInt32)(1 << (int)key);
}
return result;
}
}
}

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib
{
public class ValueRanges: List<ValueRange>
{
public bool IsSizeDeclaration { get; internal set; }
public ValueRanges(bool isSizeDecl = false)
{
IsSizeDeclaration = isSizeDecl;
}
public bool Contains(Int64 value)
{
foreach (ValueRange range in this)
{
if (range.Contains(value))
{
return true;
}
}
return false;
}
}
public class ValueRange
{
private readonly Int64 _start;
private readonly Int64? _end;
public ValueRange(Int64 first, Int64? second)
{
_start = first;
_end = second;
}
public Int64 Start
{
get { return _start; }
}
public Int64? End
{
get { return _end; }
}
public bool IntersectsWith(ValueRange other)
{
if (this._end == null)
{
return other.Contains(this._start);
}
else if (other._end == null)
{
return this.Contains(other._start);
}
return (this._start <= other.End) && (this._end >= other._start);
}
public bool Contains(Int64 value)
{
if (_end == null)
{
return value == _start;
}
else
{
return (_start <= value) && (value <= _end);
}
}
}
}