diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CCodeGeneration.csproj b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CCodeGeneration.csproj new file mode 100644 index 00000000..06d5075e --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CCodeGeneration.csproj @@ -0,0 +1,67 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {7DA7C0AB-0982-4BF5-9324-F59A7A08D65B} + Library + Properties + CCodeGeneration + CCodeGeneration + v4.0 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CFile.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CFile.cs new file mode 100644 index 00000000..6f122742 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CFile.cs @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; + +namespace CCodeGeneration +{ + public class CFile: CodeContainerBase + { + public CFile() + { + base.IncreaseLevel = false; + } + + public void Save(CGenerator generator) + { + if (generator == null) + { + throw new ArgumentNullException("generator"); + } + + this.GenerateCode(0, generator); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CGenerator.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CGenerator.cs new file mode 100644 index 00000000..4e8dfbc7 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CGenerator.cs @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.IO; + +namespace CCodeGeneration +{ + public class CGenerator + { + public TextWriter OutputStream { get; private set; } + public string File { get; private set; } + public uint IndentCount { get; private set; } + public string IndentChar { get; private set; } + public string NewLine { get; private set; } + + public CGenerator(System.IO.TextWriter outputStream, string file, uint indentCount, string indentChar, string newLine) + { + this.OutputStream = outputStream; + this.File = file; + this.IndentCount = indentCount; + this.IndentChar = indentChar; + this.NewLine = newLine; + } + + public string FileName + { + get + { + if (!String.IsNullOrWhiteSpace(this.File)) + { + return Path.GetFileName(this.File); + } + + return null; + } + } + + public void WriteSequence(string value, uint repetitions) + { + while (repetitions > 0) + { + this.OutputStream.Write(value); + repetitions--; + } + } + + public void IndentLine(int level) + { + while (level > 0) + { + WriteSequence(this.IndentChar, this.IndentCount); + level--; + } + } + + public void WriteNewLine() + { + this.OutputStream.Write(this.NewLine); + } + + public void WriteMultilineString(string value, int level = 0) + { + if (String.IsNullOrEmpty(value)) + { + return; + } + + // only \n and \r\n are recognized as linebreaks + string[] lines = value.Split(new char[] { '\n' }, StringSplitOptions.None); + + for (int l = 0; l < (lines.Length - 1); l++) + { + if (lines[l].EndsWith("\r")) + { + this.OutputStream.Write(lines[l].Substring(0, lines[l].Length-1)); + } + else + { + this.OutputStream.Write(lines[l]); + } + + this.WriteNewLine(); + this.IndentLine(level); + } + + this.OutputStream.Write(lines[lines.Length - 1]); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Code.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Code.cs new file mode 100644 index 00000000..4834508a --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Code.cs @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +namespace CCodeGeneration +{ + public class Code: CodeElement + { + public string Code_ { get; set; } + + public Code() + { + } + + public Code(string code) + { + this.Code_ = code; + } + + public override void GenerateCode(int level, CGenerator generator) + { + generator.IndentLine(level); + generator.WriteMultilineString(this.Code_, level); + generator.WriteNewLine(); + } + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CodeContainerBase.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CodeContainerBase.cs new file mode 100644 index 00000000..4327d92d --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CodeContainerBase.cs @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System.Collections.Generic; +using System; + +namespace CCodeGeneration +{ + public class CodeContainerBase: CodeElement + { + private readonly List declarations = new List(); + private readonly List innerElements = new List(); + private bool increaseLevel = true; + + public List Declarations + { + get { return this.declarations; } + } + + public List InnerElements + { + get { return this.innerElements; } + } + + protected bool IncreaseLevel + { + get { return this.increaseLevel; } + set { this.increaseLevel = value; } + } + + public void AddElements(IList elements, params CodeElement[] spacerElements) + { + if (elements != null) + { + if ((spacerElements == null) || (spacerElements.Length == 0)) + { + this.innerElements.AddRange(elements); + } + else + { + bool spacerAdded = false; + + foreach (CodeElement element in elements) + { + this.innerElements.Add(element); + this.innerElements.AddRange(spacerElements); + spacerAdded = true; + } + + if (spacerAdded) + { + // remove last spacer again + this.innerElements.RemoveRange(this.innerElements.Count - spacerElements.Length, spacerElements.Length); + } + } + } + } + + public CodeElement AddElement(CodeElement element) + { + if (element != null) + { + this.innerElements.Add(element); + } + + return element; + } + + public Code AddCode(string code) + { + return this.AddElement(new Code(code)) as Code; + } + + public Code AddCodeFormat(string codeFormat, params object[] args) + { + return this.AddElement(new Code(String.Format(codeFormat, args))) as Code; + } + + public CodeElement AddDeclaration(CodeElement declaration) + { + if (declaration != null) + { + this.declarations.Add(declaration); + } + + return declaration; + } + + public override void GenerateCode(int level, CGenerator generator) + { + if (this.increaseLevel) + level++; + + if (this.declarations.Count > 0) + { + foreach (CodeElement element in this.declarations) + { + element.GenerateCode(level, generator); + } + + EmptyLine.SingleLine.GenerateCode(level, generator); + } + + foreach (CodeElement element in this.innerElements) + { + element.GenerateCode(level, generator); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CodeElement.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CodeElement.cs new file mode 100644 index 00000000..51cf2d24 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/CodeElement.cs @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +namespace CCodeGeneration +{ + public class CodeElement + { + public virtual void GenerateCode(int level, CGenerator generator) + { + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Comment.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Comment.cs new file mode 100644 index 00000000..51779bea --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Comment.cs @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +namespace CCodeGeneration +{ + public class Comment: CodeElement + { + public const string CommentStart = "/*"; + public const string CommentEnd = "*/"; + + public string Comment_ { get; set; } + public bool SingleLine { get; set; } + + public Comment() + { + } + + public Comment(string comment, bool singleLine = false) + { + this.Comment_ = comment; + this.SingleLine = singleLine; + } + + public override void GenerateCode(int level, CGenerator generator) + { + generator.IndentLine(level); + generator.OutputStream.Write(CommentStart); + + if (!this.SingleLine) + { + generator.WriteNewLine(); + generator.IndentLine(level); + generator.WriteMultilineString(this.Comment_, level); + generator.WriteNewLine(); + generator.IndentLine(level); + } + else + { + generator.OutputStream.Write(" " + Comment_ + " "); + } + + generator.OutputStream.Write(CommentEnd); + generator.WriteNewLine(); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/EmptyLine.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/EmptyLine.cs new file mode 100644 index 00000000..604c9477 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/EmptyLine.cs @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +namespace CCodeGeneration +{ + public class EmptyLine : CodeElement + { + public static readonly EmptyLine SingleLine = new EmptyLine(); + public static readonly EmptyLine TwoLines = new EmptyLine(2); + public static readonly EmptyLine ThreeLines = new EmptyLine(3); + + public uint Count { get; set; } + + public EmptyLine() + { + this.Count = 1; + } + + public EmptyLine(uint count) + { + this.Count = count; + } + + public override void GenerateCode(int level, CGenerator generator) + { + uint c = this.Count; + + while (c > 0) + { + generator.WriteNewLine(); + c--; + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Function.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Function.cs new file mode 100644 index 00000000..d81f6e56 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Function.cs @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; + +namespace CCodeGeneration +{ + public class Function: CodeContainerBase + { + public string Name { get; set; } + public bool IsStatic { get; set; } + + private readonly List parameter = new List(); + private VariableType returnType = VariableType.Void; + + public Function() + { + } + + public Function(string name, bool isStatic = false) + { + this.Name = name; + this.IsStatic = isStatic; + } + + public List Parameter + { + get { return this.parameter; } + } + + public VariableType ReturnType + { + get { return this.returnType; } + set + { + if (value == null) + { + throw new ArgumentNullException("ReturnValue"); + } + this.returnType = value; + } + } + + public static Function FromDeclaration(FunctionDeclaration decl) + { + Function result = new Function(decl.Name, decl.IsStatic); + result.ReturnType = decl.ReturnType.Clone() as VariableType; + + foreach (VariableType param in decl.Parameter) + { + result.parameter.Add(param.Clone() as VariableType); + } + + return result; + } + + public override void GenerateCode(int level, CGenerator generator) + { + generator.IndentLine(level); + + if (this.IsStatic) + { + generator.OutputStream.Write("static "); + } + + this.returnType.GenerateCode(generator); + generator.OutputStream.Write(" " + this.Name + "("); + + if (this.Parameter.Count > 0) + { + for (int i = 0; i < this.parameter.Count; i++) + { + this.parameter[i].GenerateCode(generator); + + if (i < (this.parameter.Count - 1)) + { + generator.OutputStream.Write(", "); + } + } + } + else + { + generator.OutputStream.Write("void"); + } + + generator.OutputStream.Write(")"); + generator.WriteNewLine(); + generator.IndentLine(level); + generator.OutputStream.Write("{"); + generator.WriteNewLine(); + + base.GenerateCode(level, generator); + + generator.IndentLine(level); + generator.OutputStream.Write("}"); + generator.WriteNewLine(); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/FunctionDeclaration.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/FunctionDeclaration.cs new file mode 100644 index 00000000..3bc42888 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/FunctionDeclaration.cs @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; + +namespace CCodeGeneration +{ + public class FunctionDeclaration: CodeElement + { + public string Name { get; set; } + public bool IsStatic { get; set; } + public bool IsExtern { get; set; } + + private readonly List parameter = new List(); + private VariableType returnType = VariableType.Void; + + public FunctionDeclaration() + { + } + + public FunctionDeclaration(string name, bool isStatic = false, bool isExtern = false) + { + this.Name = name; + this.IsStatic = isStatic; + this.IsExtern = isExtern; + } + + public List Parameter + { + get { return this.parameter; } + } + + public VariableType ReturnType + { + get { return this.returnType; } + set + { + if (value == null) + { + throw new ArgumentNullException("ReturnValue"); + } + this.returnType = value; + } + } + + public override void GenerateCode(int level, CGenerator generator) + { + generator.IndentLine(level); + + if (this.IsExtern) + { + generator.OutputStream.Write("extern "); + } + + if (this.IsStatic) + { + generator.OutputStream.Write("static "); + } + + this.returnType.GenerateCode(generator); + generator.OutputStream.Write(" " + this.Name + "("); + + if (this.Parameter.Count > 0) + { + for (int i = 0; i < this.parameter.Count; i++) + { + this.parameter[i].GenerateCode(generator); + + if (i < (this.parameter.Count - 1)) + { + generator.OutputStream.Write(", "); + } + } + } + else + { + generator.OutputStream.Write("void"); + } + + generator.OutputStream.Write(");"); + generator.WriteNewLine(); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/IfThenElse.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/IfThenElse.cs new file mode 100644 index 00000000..c4710225 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/IfThenElse.cs @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; + +namespace CCodeGeneration +{ + public class ElseIf : CodeContainerBase + { + public string Condition { get; set; } + + public ElseIf() + { + } + + public ElseIf(string condition) + { + this.Condition = condition; + } + + public override void GenerateCode(int level, CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.Condition)) + { + generator.IndentLine(level); + generator.OutputStream.Write(String.Format("else if ({0})", this.Condition)); + generator.WriteNewLine(); + generator.IndentLine(level); + generator.OutputStream.Write("{"); + generator.WriteNewLine(); + + base.GenerateCode(level, generator); + + generator.IndentLine(level); + generator.OutputStream.Write("}"); + generator.WriteNewLine(); + } + } + } + + public class IfThenElse: CodeContainerBase + { + public string Condition { get; set; } + + private List elseIf = new List(); + private CodeContainerBase else_ = new CodeContainerBase(); + + public IfThenElse() + { + } + + public IfThenElse(string condition) + { + this.Condition = condition; + } + + public List ElseIf + { + get { return this.elseIf; } + } + + public CodeContainerBase Else + { + get { return this.else_; } + } + + public override void GenerateCode(int level, CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.Condition)) + { + generator.IndentLine(level); + generator.OutputStream.Write(String.Format("if ({0})", this.Condition)); + generator.WriteNewLine(); + generator.IndentLine(level); + generator.OutputStream.Write("{"); + generator.WriteNewLine(); + + base.GenerateCode(level, generator); + + generator.IndentLine(level); + generator.OutputStream.Write("}"); + generator.WriteNewLine(); + + foreach (ElseIf elif in this.elseIf) + { + elif.GenerateCode(level, generator); + } + + if (this.else_.InnerElements.Count > 0) + { + generator.IndentLine(level); + generator.OutputStream.Write("else"); + generator.WriteNewLine(); + generator.IndentLine(level); + generator.OutputStream.Write("{"); + generator.WriteNewLine(); + + this.else_.GenerateCode(level, generator); + + generator.IndentLine(level); + generator.OutputStream.Write("}"); + generator.WriteNewLine(); + } + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_If.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_If.cs new file mode 100644 index 00000000..55682155 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_If.cs @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; + +namespace CCodeGeneration +{ + public class PP_If: CodeContainerBase + { + public string Condition { get; set; } + + public PP_If() + { + base.IncreaseLevel = false; + } + + public PP_If(string condition) + : this() + { + this.Condition = condition; + } + + + public override void GenerateCode(int level, CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.Condition)) + { + generator.OutputStream.Write("#if " + this.Condition); + generator.WriteNewLine(); + + base.GenerateCode(level, generator); + + generator.OutputStream.Write("#endif /* " + this.Condition + " */"); + generator.WriteNewLine(); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Ifdef.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Ifdef.cs new file mode 100644 index 00000000..fd4f45af --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Ifdef.cs @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; + +namespace CCodeGeneration +{ + public class PP_Ifdef: CodeContainerBase + { + public string Macro { get; set; } + public bool Inverted { get; set; } + + public PP_Ifdef() + { + base.IncreaseLevel = false; + } + + public PP_Ifdef(string macro, bool inverted = false) + : this() + { + this.Macro = macro; + this.Inverted = inverted; + } + + + public override void GenerateCode(int level, CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.Macro)) + { + if (this.Inverted) + { + generator.OutputStream.Write("#ifndef " + this.Macro); + } + else + { + generator.OutputStream.Write("#ifdef " + this.Macro); + } + generator.WriteNewLine(); + + base.GenerateCode(level, generator); + + generator.OutputStream.Write("#endif /* " + this.Macro + " */"); + generator.WriteNewLine(); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Include.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Include.cs new file mode 100644 index 00000000..0393d271 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Include.cs @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; + +namespace CCodeGeneration +{ + public class PP_Include : CodeElement + { + public string File { get; set; } + public bool IsLocal { get; set; } + + public PP_Include() + { + this.IsLocal = true; + } + + public PP_Include(string file, bool isLocal = true) + { + this.File = file; + this.IsLocal = isLocal; + } + + public override void GenerateCode(int level, CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.File)) + { + // includes are never indented + if (this.IsLocal) + { + generator.OutputStream.Write("#include \"" + this.File + "\""); + } + else + { + generator.OutputStream.Write("#include <" + this.File + ">"); + } + + generator.WriteNewLine(); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Macro.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Macro.cs new file mode 100644 index 00000000..6f302aa9 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PP_Macro.cs @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +namespace CCodeGeneration +{ + public class PP_Macro: CodeElement + { + public string Name { get; set; } + public string Value { get; set; } + + public PP_Macro() + { + } + + public PP_Macro(string name, string value) + { + this.Name = name; + this.Value = value; + } + + + public override void GenerateCode(int level, CGenerator generator) + { + // macros are not indented at all + generator.OutputStream.Write("#define " + this.Name + " "); + generator.WriteMultilineString(this.Value); + generator.WriteNewLine(); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PlainText.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PlainText.cs new file mode 100644 index 00000000..d5e076fe --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/PlainText.cs @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +namespace CCodeGeneration +{ + public class PlainText : CodeElement + { + public string Value { get; set; } + + public PlainText(string value) + { + this.Value = value; + } + + public override void GenerateCode(int level, CGenerator generator) + { + generator.WriteMultilineString(this.Value); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Properties/AssemblyInfo.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..4c716ad3 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die mit einer Assembly verknüpft sind. +[assembly: AssemblyTitle("CCodeGeneration")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CCodeGeneration")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar +// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von +// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("8f07a0fa-86f4-48a0-97c7-f94fc5c3f103")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern +// übernehmen, indem Sie "*" eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Switch.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Switch.cs new file mode 100644 index 00000000..9166fb89 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/Switch.cs @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; + +namespace CCodeGeneration +{ + public class SwitchCase : CodeContainerBase + { + public string Value { get; set; } + + public SwitchCase() + { + } + + public SwitchCase(string value) + { + this.Value = value; + } + + public bool IsDefault + { + get { return (this.Value.ToLowerInvariant() == "default"); } + } + + public static SwitchCase GenerateDefault() + { + return new SwitchCase("default"); + } + + public override void GenerateCode(int level, CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.Value)) + { + generator.IndentLine(level); + if (this.IsDefault) + { + generator.OutputStream.Write("default:"); + } + else + { + generator.OutputStream.Write(String.Format("case {0}:", this.Value)); + } + generator.WriteNewLine(); + generator.IndentLine(level + 1); + generator.OutputStream.Write("{"); + generator.WriteNewLine(); + + base.GenerateCode(level + 1, generator); + + generator.IndentLine(level + 1); + generator.OutputStream.Write("}"); + generator.WriteNewLine(); + + generator.IndentLine(level + 1); + generator.OutputStream.Write("break;"); + generator.WriteNewLine(); + } + } + } + + public class Switch: CodeElement + { + public string SwitchVar { get; set; } + + private List switches = new List(); + + public Switch() + { + } + + public Switch(string switchVar) + { + this.SwitchVar = switchVar; + } + + public List Switches + { + get { return this.switches; } + } + + public override void GenerateCode(int level, CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.SwitchVar)) + { + generator.IndentLine(level); + generator.OutputStream.Write(String.Format("switch ({0})", this.SwitchVar)); + generator.WriteNewLine(); + generator.IndentLine(level); + generator.OutputStream.Write("{"); + generator.WriteNewLine(); + + SwitchCase defaultCase = null; // generate 'default' always as last case + foreach (SwitchCase switchCase in this.switches) + { + if (switchCase.IsDefault) + { + defaultCase = switchCase; + } + else + { + switchCase.GenerateCode(level + 1, generator); + } + } + if (defaultCase != null) + { + defaultCase.GenerateCode(level + 1, generator); + } + + generator.IndentLine(level); + generator.OutputStream.Write("}"); + generator.WriteNewLine(); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariableDeclaration.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariableDeclaration.cs new file mode 100644 index 00000000..bf2c9026 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariableDeclaration.cs @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; + +namespace CCodeGeneration +{ + public class VariableDeclaration : CodeElement + { + public VariableType Type { get; set; } + public string InitialValue { get; set; } + public bool IsStatic { get; set; } + + public VariableDeclaration() + : base() + { + } + + public VariableDeclaration(VariableType type, string initialValue = null, bool isStatic = false) : + base() + { + this.Type = type; + this.InitialValue = initialValue; + this.IsStatic = isStatic; + } + + public override void GenerateCode(int level, CGenerator generator) + { + if (this.Type != null) + { + generator.IndentLine(level); + + if (this.IsStatic) + { + generator.OutputStream.Write("static "); + } + + // declare the variable + this.Type.GenerateCode(generator); + + if (!String.IsNullOrWhiteSpace(this.InitialValue)) + { + // add initialization value + generator.OutputStream.Write(" = "); + generator.WriteMultilineString(this.InitialValue, level); + } + + generator.OutputStream.Write(";"); + generator.WriteNewLine(); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariablePrototype.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariablePrototype.cs new file mode 100644 index 00000000..38a41663 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariablePrototype.cs @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +namespace CCodeGeneration +{ + public class VariablePrototype : CodeElement + { + public VariableType Type { get; set; } + + public VariablePrototype() + : base() + { + } + + public VariablePrototype(VariableType type) : + base() + { + Type = type; + } + + public static VariablePrototype FromVariableDeclaration(VariableDeclaration declaration) + { + return new VariablePrototype(declaration.Type); + } + + + public override void GenerateCode(int level, CGenerator generator) + { + if (this.Type != null) + { + generator.IndentLine(level); + + generator.OutputStream.Write("extern "); + + // declare the variable + this.Type.GenerateCode(generator); + + generator.OutputStream.Write(";"); + generator.WriteNewLine(); + } + } + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariableType.cs b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariableType.cs new file mode 100644 index 00000000..313abbee --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/CCodeGeneration/VariableType.cs @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text; + +namespace CCodeGeneration +{ + public enum ConstType + { + None, + Value, + Indirection, + Both + } + + public class VariableType : ICloneable + { + public const string VoidString = "void"; + public static readonly VariableType Void = new VariableType(null, "void"); + + public string Name { get; set; } + public string Type { get; set; } + public string Indirection { get; set; } + public ConstType Const { get; set; } + public string ArraySpecifier { get; set; } + + public VariableType() + { + } + + public VariableType(string name, string type, string indirection = null, ConstType const_ = ConstType.None, string arraySpecifier = null) + { + this.Name = name; + this.Type = type; + this.Indirection = indirection; + this.Const = const_; + this.ArraySpecifier = arraySpecifier; + } + + public void GenerateCode(CGenerator generator) + { + if (!String.IsNullOrWhiteSpace(this.Type)) + { + generator.OutputStream.Write(this.ToString().Trim()); + } + } + + public override string ToString() + { + if (!String.IsNullOrWhiteSpace(this.Type)) + { + StringBuilder vt = new StringBuilder(); + + if ((this.Const == ConstType.Value) || (this.Const == ConstType.Both)) + { + vt.Append("const "); + } + + vt.Append(this.Type); + vt.Append(" "); + + if (!String.IsNullOrWhiteSpace(this.Indirection)) + { + vt.Append(this.Indirection); + } + + if ((this.Const == ConstType.Indirection) || (this.Const == ConstType.Both)) + { + vt.Append("const "); + } + + if (!String.IsNullOrWhiteSpace(this.Name)) + { + vt.Append(this.Name); + } + + if (this.ArraySpecifier != null) + { + vt.Append("["); + vt.Append(this.ArraySpecifier); + vt.Append("]"); + } + + return vt.ToString().Trim(); + } + + return base.ToString(); + } + + #region ICloneable Member + + public object Clone() + { + // we only have value types as members -> simply use .net base function + return this.MemberwiseClone(); + } + + #endregion + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibCompiler.sln b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler.sln new file mode 100644 index 00000000..12ca54de --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler.sln @@ -0,0 +1,47 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LwipMibCompiler", "LwipMibCompiler\LwipMibCompiler.csproj", "{C25D5640-D999-49BD-82E0-A1975296A91E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LwipSnmpCodeGeneration", "LwipSnmpCodeGeneration\LwipSnmpCodeGeneration.csproj", "{AABCAB90-1540-45D4-A159-14831A54E9A3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CCodeGeneration", "CCodeGeneration\CCodeGeneration.csproj", "{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpSnmpLib.Mib", "SharpSnmpLib\SharpSnmpLib.Mib.csproj", "{CBE20411-5DB7-487D-825D-7694267BB6F5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LwipMibViewer", "LwipMibViewer\LwipMibViewer.csproj", "{86CC0B65-7985-4017-A252-0A7A18DCAEF3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Release|Any CPU.Build.0 = Release|Any CPU + {86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Release|Any CPU.Build.0 = Release|Any CPU + {AABCAB90-1540-45D4-A159-14831A54E9A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AABCAB90-1540-45D4-A159-14831A54E9A3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AABCAB90-1540-45D4-A159-14831A54E9A3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AABCAB90-1540-45D4-A159-14831A54E9A3}.Release|Any CPU.Build.0 = Release|Any CPU + {C25D5640-D999-49BD-82E0-A1975296A91E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C25D5640-D999-49BD-82E0-A1975296A91E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C25D5640-D999-49BD-82E0-A1975296A91E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C25D5640-D999-49BD-82E0-A1975296A91E}.Release|Any CPU.Build.0 = Release|Any CPU + {CBE20411-5DB7-487D-825D-7694267BB6F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CBE20411-5DB7-487D-825D-7694267BB6F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CBE20411-5DB7-487D-825D-7694267BB6F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CBE20411-5DB7-487D-825D-7694267BB6F5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(MonoDevelopProperties) = preSolution + StartupItem = LwipMibViewer\LwipMibViewer.csproj + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/LwipMibCompiler.csproj b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/LwipMibCompiler.csproj new file mode 100644 index 00000000..eb54c3f1 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/LwipMibCompiler.csproj @@ -0,0 +1,71 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {C25D5640-D999-49BD-82E0-A1975296A91E} + Exe + Properties + LwipMibCompiler + LwipMibCompiler + v4.0 + 512 + + + + true + bin\Debug\ + DEBUG;TRACE + full + AnyCPU + prompt + false + false + 4 + false + + + bin\Release\ + TRACE + true + pdbonly + AnyCPU + prompt + 4 + + + + + + + + + + + + + + {7DA7C0AB-0982-4BF5-9324-F59A7A08D65B} + CCodeGeneration + + + {AABCAB90-1540-45D4-A159-14831A54E9A3} + LwipSnmpCodeGeneration + + + {CBE20411-5DB7-487D-825D-7694267BB6F5} + SharpSnmpLib.Mib + + + + + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/Program.cs b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/Program.cs new file mode 100644 index 00000000..20e726ef --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/Program.cs @@ -0,0 +1,470 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text.RegularExpressions; +using CCodeGeneration; +using Lextm.SharpSnmpLib.Mib; +using Lextm.SharpSnmpLib.Mib.Elements.Entities; +using Lextm.SharpSnmpLib.Mib.Elements.Types; +using LwipSnmpCodeGeneration; + +namespace LwipMibCompiler +{ + class Program + { + private static readonly Regex _alphaNumericRegex = new Regex("[^a-zA-Z0-9]"); + + static void Main(string[] args) + { + Console.WriteLine("lwIP MIB Compiler"); + Console.WriteLine(""); + + // check args + if ((args.Length < 2) || String.IsNullOrWhiteSpace(args[0]) || String.IsNullOrWhiteSpace(args[1])) + { + PrintUsage(); + return; + } + + string mibFile = args[0]; + if (!File.Exists(mibFile)) + { + Console.WriteLine(String.Format("Unable to find file '{0}'!", mibFile)); + } + + string destFile = args[1]; + string destHeaderFile; + + if (Directory.Exists(destFile)) + { + // only directory passed -> create dest filename from mib filename + string mibFileName = Path.GetFileNameWithoutExtension(mibFile).ToLowerInvariant(); + destFile = Path.Combine(destFile, mibFileName + ".c"); + } + + string destFileExt = Path.GetExtension(destFile); + if (!String.IsNullOrEmpty(destFileExt)) + { + destHeaderFile = destFile.Substring(0, destFile.Length - destFileExt.Length); + } + else + { + destHeaderFile = destFile; + } + destHeaderFile += ".h"; + + for (int i=2; i [ ...]", appName)); + Console.WriteLine(""); + Console.WriteLine(" "); + Console.WriteLine(" Path and filename of MIB file to convert."); + Console.WriteLine(""); + Console.WriteLine(" "); + Console.WriteLine(" Destination path and file. If a path is passed only, filename is auto"); + Console.WriteLine(" generated from MIB file name."); + Console.WriteLine(""); + Console.WriteLine(" "); + Console.WriteLine(" It's important to provide all referred MIB's in order to correctly "); + Console.WriteLine(" resolve all used types."); + Console.WriteLine(""); + } + + + #region Generation of LWIP Object Tree + + private static void ProcessMibTreeNode(MibTreeNode mibTreeNode, SnmpTreeNode assignedSnmpNode) + { + foreach (MibTreeNode mtn in mibTreeNode.ChildNodes) + { + // in theory container nodes may also be scalars or tables at the same time (for now only process real containers) + if (mtn.NodeType == MibTreeNodeType.Container) + { + SnmpTreeNode snmpTreeNode = GenerateSnmpTreeNode(mtn, assignedSnmpNode); + assignedSnmpNode.ChildNodes.Add(snmpTreeNode); + + ProcessMibTreeNode(mtn, snmpTreeNode); + } + else if ((mtn.NodeType & MibTreeNodeType.Scalar) != 0) + { + SnmpScalarNode snmpScalarNode = GenerateSnmpScalarNode(mtn, assignedSnmpNode); + if (snmpScalarNode != null) + { + assignedSnmpNode.ChildNodes.Add(snmpScalarNode); + } + } + else if ((mtn.NodeType & MibTreeNodeType.Table) != 0) + { + SnmpTableNode snmpTableNode = GenerateSnmpTableNode(mtn, assignedSnmpNode); + if (snmpTableNode != null) + { + assignedSnmpNode.ChildNodes.Add(snmpTableNode); + } + } + } + } + + private static SnmpTreeNode GenerateSnmpTreeNode(MibTreeNode mibTreeNode, SnmpTreeNode parentNode) + { + SnmpTreeNode result = new SnmpTreeNode(parentNode); + result.Name = _alphaNumericRegex.Replace(mibTreeNode.Entity.Name, "").ToLowerInvariant(); + result.Oid = mibTreeNode.Entity.Value; + result.FullOid = MibTypesResolver.ResolveOid(mibTreeNode.Entity).GetOidString(); + + return result; + } + + private static SnmpScalarNode GenerateSnmpScalarNode(MibTreeNode mibTreeNode, SnmpTreeNode parentNode, bool ignoreAccessibleFlag = false) + { + ObjectType ote = mibTreeNode.Entity as ObjectType; + if (ote != null) + { + return GenerateSnmpScalarNode(ote, parentNode, ignoreAccessibleFlag); + } + + return null; + } + + private static SnmpScalarNode GenerateSnmpScalarNode(ObjectType ote, SnmpTreeNode parentNode, bool ignoreAccessibleFlag = false) + { + SnmpScalarNode result; + + ITypeAssignment mibType = ote.BaseType; + IntegerType it = (mibType as IntegerType); + if (it != null) + { + if (ote.ReferredType.Name == Symbol.TruthValue.ToString()) + { + result = new SnmpScalarNodeTruthValue(parentNode); + } + else if ((it.Type == IntegerType.Types.Integer) || (it.Type == IntegerType.Types.Integer32)) + { + result = new SnmpScalarNodeInt(parentNode); + } + else + { + Console.WriteLine(String.Format("Unsupported IntegerType '{0}'!", it.Type)); + return null; + } + if (it.IsEnumeration) + { + result.Restrictions.AddRange(CreateRestrictions(it.Enumeration)); + } + else + { + result.Restrictions.AddRange(CreateRestrictions(it.Ranges)); + } + } + else + { + UnsignedType ut = (mibType as UnsignedType); + if (ut != null) + { + if ((ut.Type == UnsignedType.Types.Unsigned32) || + (ut.Type == UnsignedType.Types.Gauge32)) + { + result = new SnmpScalarNodeUint(SnmpDataType.Gauge, parentNode); + } + else if (ut.Type == UnsignedType.Types.Counter32) + { + result = new SnmpScalarNodeUint(SnmpDataType.Counter, parentNode); + } + else if (ut.Type == UnsignedType.Types.TimeTicks) + { + result = new SnmpScalarNodeUint(SnmpDataType.TimeTicks, parentNode); + } + else if (ut.Type == UnsignedType.Types.Counter64) + { + result = new SnmpScalarNodeCounter64(parentNode); + if ((ut.Ranges != null) && (ut.Ranges.Count > 0)) + { + Console.WriteLine(String.Format("Generation of ranges is not supported for Counter64 type!")); + return null; + } + } + else + { + Console.WriteLine(String.Format("Unsupported UnsignedType '{0}'!", ut.Type)); + return null; + } + result.Restrictions.AddRange(CreateRestrictions(ut.Ranges)); + } + else if (mibType is IpAddressType) + { + result = new SnmpScalarNodeOctetString(SnmpDataType.IpAddress, parentNode); + result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size)); + } + else if (mibType is OpaqueType) + { + result = new SnmpScalarNodeOctetString(SnmpDataType.Opaque, parentNode); + result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size)); + } + else if (mibType is OctetStringType) + { + result = new SnmpScalarNodeOctetString(SnmpDataType.OctetString, parentNode); + result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size)); + } + else if (mibType is ObjectIdentifierType) + { + result = new SnmpScalarNodeObjectIdentifier(parentNode); + } + else if (mibType is BitsType) + { + result = new SnmpScalarNodeBits(parentNode, (uint)((mibType as BitsType).Map.GetHighestValue() + 1)); + result.Restrictions.AddRange(CreateRestrictions(mibType as BitsType)); + } + else + { + TypeAssignment ta = mibType as TypeAssignment; + if (ta != null) + { + Console.WriteLine(String.Format("Unsupported BaseType: Module='{0}', Name='{1}', Type='{2}'!", ta.Module.Name, ta.Name, ta.Type)); + } + else + { + Console.WriteLine(String.Format("Unsupported BaseType: Module='{0}', Name='{1}'!", mibType.Module, mibType.Name)); + } + + return null; + } + } + + result.Name = _alphaNumericRegex.Replace(ote.Name, "").ToLowerInvariant(); + result.Oid = ote.Value; + + if (ote.Access == MaxAccess.readWrite) + { + result.AccessMode = SnmpAccessMode.ReadWrite; + } + else if (ote.Access == MaxAccess.readOnly) + { + result.AccessMode = SnmpAccessMode.ReadOnly; + } + else if (ignoreAccessibleFlag && (ote.Access == MaxAccess.notAccessible)) + { + result.AccessMode = SnmpAccessMode.NotAccessible; + } + else + { + // not accessible or unsupported accress type + return null; + } + + return result; + } + + private static IEnumerable CreateRestrictions(ValueRanges ranges) + { + List result = new List(); + + if (ranges != null) + { + foreach (ValueRange range in ranges) + { + if (!range.End.HasValue) + { + result.Add(new IsEqualRestriction(range.Start)); + } + else + { + result.Add(new IsInRangeRestriction(range.Start, range.End.Value)); + } + } + } + + return result; + } + + private static IEnumerable CreateRestrictions(ValueMap map) + { + if ((map != null) && (map.Count > 0)) + { + return CreateRestrictions(map.GetContinousRanges()); + } + + return new List(); + } + + private static IEnumerable CreateRestrictions(BitsType bt) + { + List result = new List(); + + if ((bt != null) && (bt.Map != null)) + { + result.Add(new BitMaskRestriction(bt.Map.GetBitMask())); + } + + return result; + } + + private static SnmpTableNode GenerateSnmpTableNode(MibTreeNode mibTreeNode, SnmpTreeNode parentNode) + { + SnmpTableNode result = new SnmpTableNode(parentNode); + result.Name = mibTreeNode.Entity.Name; + result.Oid = mibTreeNode.Entity.Value; + + // expect exactly one row entry + if ((mibTreeNode.ChildNodes.Count != 1) || ((mibTreeNode.ChildNodes[0].NodeType & MibTreeNodeType.TableRow) == 0) || (mibTreeNode.ChildNodes[0].Entity.Value != 1)) + { + Console.WriteLine("Found table with unsupported properties! Table needs exactly one (fixed) TableRow with OID=1 ! (" + mibTreeNode.Entity.Name + ")"); + return null; + } + + MibTreeNode rowNode = mibTreeNode.ChildNodes[0]; + + ObjectType rot = rowNode.Entity as ObjectType; + if (rot != null) + { + if (!String.IsNullOrWhiteSpace(rot.Augments)) + { + result.AugmentedTableRow = rot.Augments; + + // the indeces from another table shall be used because this table is only an extension of it + rot = MibTypesResolver.ResolveDeclaration(rot.Module, rot.Augments) as ObjectType; + } + + if (rot.Indices != null) + { + foreach (string index in rot.Indices) + { + ObjectType indexEntity = MibTypesResolver.ResolveDeclaration(rot.Module, index) as ObjectType; + if (indexEntity == null) + { + Console.WriteLine(String.Format("Could not resolve index '{0}' for table '{1}'! Table omitted!", index, result.Name)); + return null; + } + + result.IndexNodes.Add(GenerateSnmpScalarNode(indexEntity, parentNode, ignoreAccessibleFlag: true)); + } + } + } + + if (result.IndexNodes.Count == 0) + { + // a table cannot be used without index + Console.WriteLine("Found table without any index column ! (" + mibTreeNode.Entity.Name + ")"); + return null; + } + + // add child nodes + foreach (MibTreeNode cellNode in rowNode.ChildNodes) + { + SnmpScalarNode ssn = GenerateSnmpScalarNode(cellNode, parentNode); + if (ssn != null) + { + result.CellNodes.Add(ssn); + } + } + + return result; + } + + #endregion + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/Properties/AssemblyInfo.cs b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..d30b8425 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die mit einer Assembly verknüpft sind. +[assembly: AssemblyTitle("ConsoleApplication28")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ConsoleApplication28")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar +// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von +// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("0abf7541-6a96-43cd-9e24-462e074b2c96")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern +// übernehmen, indem Sie "*" eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/app.config b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/app.config new file mode 100644 index 00000000..e3656033 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibCompiler/app.config @@ -0,0 +1,3 @@ + + + diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.Designer.cs b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.Designer.cs new file mode 100644 index 00000000..dcd19aa5 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.Designer.cs @@ -0,0 +1,166 @@ +namespace LwipMibViewer +{ + partial class FormMain + { + /// + /// Erforderliche Designervariable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Verwendete Ressourcen bereinigen. + /// + /// True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Vom Windows Form-Designer generierter Code + + /// + /// Erforderliche Methode für die Designerunterstützung. + /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain)); + this.treeMib = new System.Windows.Forms.TreeView(); + this.imagelistTreeNodeImages = new System.Windows.Forms.ImageList(this.components); + this.splitContainerMain = new System.Windows.Forms.SplitContainer(); + this.listviewNodeDetails = new System.Windows.Forms.ListView(); + this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.toolStripMain = new System.Windows.Forms.ToolStrip(); + this.toolbuttonOpenMib = new System.Windows.Forms.ToolStripButton(); + this.dialogOpenMib = new System.Windows.Forms.OpenFileDialog(); + ((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).BeginInit(); + this.splitContainerMain.Panel1.SuspendLayout(); + this.splitContainerMain.Panel2.SuspendLayout(); + this.splitContainerMain.SuspendLayout(); + this.toolStripMain.SuspendLayout(); + this.SuspendLayout(); + // + // treeMib + // + this.treeMib.Dock = System.Windows.Forms.DockStyle.Fill; + this.treeMib.ImageIndex = 0; + this.treeMib.ImageList = this.imagelistTreeNodeImages; + this.treeMib.Location = new System.Drawing.Point(0, 0); + this.treeMib.Name = "treeMib"; + this.treeMib.SelectedImageIndex = 0; + this.treeMib.Size = new System.Drawing.Size(1028, 418); + this.treeMib.TabIndex = 0; + this.treeMib.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeMib_AfterSelect); + // + // imagelistTreeNodeImages + // + this.imagelistTreeNodeImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imagelistTreeNodeImages.ImageStream"))); + this.imagelistTreeNodeImages.TransparentColor = System.Drawing.Color.Transparent; + this.imagelistTreeNodeImages.Images.SetKeyName(0, "ntimgContainer"); + this.imagelistTreeNodeImages.Images.SetKeyName(1, "ntimgTable"); + this.imagelistTreeNodeImages.Images.SetKeyName(2, "ntimgRow"); + this.imagelistTreeNodeImages.Images.SetKeyName(3, "ntimgColumn"); + this.imagelistTreeNodeImages.Images.SetKeyName(4, "ntimgScalar"); + this.imagelistTreeNodeImages.Images.SetKeyName(5, "ntimgUnknown"); + // + // splitContainerMain + // + this.splitContainerMain.Dock = System.Windows.Forms.DockStyle.Fill; + this.splitContainerMain.Location = new System.Drawing.Point(0, 25); + this.splitContainerMain.Name = "splitContainerMain"; + this.splitContainerMain.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // splitContainerMain.Panel1 + // + this.splitContainerMain.Panel1.Controls.Add(this.treeMib); + // + // splitContainerMain.Panel2 + // + this.splitContainerMain.Panel2.Controls.Add(this.listviewNodeDetails); + this.splitContainerMain.Size = new System.Drawing.Size(1028, 625); + this.splitContainerMain.SplitterDistance = 418; + this.splitContainerMain.TabIndex = 1; + // + // listviewNodeDetails + // + this.listviewNodeDetails.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.columnHeader1, + this.columnHeader2}); + this.listviewNodeDetails.Dock = System.Windows.Forms.DockStyle.Fill; + this.listviewNodeDetails.FullRowSelect = true; + this.listviewNodeDetails.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; + this.listviewNodeDetails.Location = new System.Drawing.Point(0, 0); + this.listviewNodeDetails.Name = "listviewNodeDetails"; + this.listviewNodeDetails.Size = new System.Drawing.Size(1028, 203); + this.listviewNodeDetails.TabIndex = 0; + this.listviewNodeDetails.UseCompatibleStateImageBehavior = false; + this.listviewNodeDetails.View = System.Windows.Forms.View.Details; + // + // columnHeader1 + // + this.columnHeader1.Text = ""; + this.columnHeader1.Width = 150; + // + // columnHeader2 + // + this.columnHeader2.Text = ""; + this.columnHeader2.Width = 777; + // + // toolStripMain + // + this.toolStripMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolbuttonOpenMib}); + this.toolStripMain.Location = new System.Drawing.Point(0, 0); + this.toolStripMain.Name = "toolStripMain"; + this.toolStripMain.Size = new System.Drawing.Size(1028, 25); + this.toolStripMain.TabIndex = 2; + // + // toolbuttonOpenMib + // + this.toolbuttonOpenMib.Image = ((System.Drawing.Image)(resources.GetObject("toolbuttonOpenMib.Image"))); + this.toolbuttonOpenMib.Name = "toolbuttonOpenMib"; + this.toolbuttonOpenMib.Size = new System.Drawing.Size(65, 22); + this.toolbuttonOpenMib.Text = "Open..."; + this.toolbuttonOpenMib.Click += new System.EventHandler(this.toolbuttonOpenMib_Click); + // + // FormMain + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1028, 650); + this.Controls.Add(this.splitContainerMain); + this.Controls.Add(this.toolStripMain); + this.Name = "FormMain"; + this.Text = "MIB Viewer"; + this.WindowState = System.Windows.Forms.FormWindowState.Maximized; + this.splitContainerMain.Panel1.ResumeLayout(false); + this.splitContainerMain.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).EndInit(); + this.splitContainerMain.ResumeLayout(false); + this.toolStripMain.ResumeLayout(false); + this.toolStripMain.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TreeView treeMib; + private System.Windows.Forms.SplitContainer splitContainerMain; + private System.Windows.Forms.ListView listviewNodeDetails; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ImageList imagelistTreeNodeImages; + private System.Windows.Forms.ToolStrip toolStripMain; + private System.Windows.Forms.ToolStripButton toolbuttonOpenMib; + private System.Windows.Forms.OpenFileDialog dialogOpenMib; + } +} + diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.cs b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.cs new file mode 100644 index 00000000..3ed25365 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.cs @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System.Windows.Forms; +using Lextm.SharpSnmpLib.Mib; +using Lextm.SharpSnmpLib.Mib.Elements; +using Lextm.SharpSnmpLib.Mib.Elements.Types; +using Lextm.SharpSnmpLib.Mib.Elements.Entities; +using System.IO; + +namespace LwipMibViewer +{ + public partial class FormMain : Form + { + readonly ListViewGroup listviewgroupAbstract; + readonly ListViewGroup listviewgroupElement; + readonly ListViewGroup listviewgroupBaseType; + readonly ListViewGroup listviewgroupTypeChain; + + public FormMain() + { + this.Font = SystemInformation.MenuFont; + InitializeComponent(); + + this.listviewgroupAbstract = new ListViewGroup("Abstract", System.Windows.Forms.HorizontalAlignment.Left); + this.listviewgroupElement = new ListViewGroup("Element Properties", System.Windows.Forms.HorizontalAlignment.Left); + this.listviewgroupBaseType = new ListViewGroup("Element Base Type", System.Windows.Forms.HorizontalAlignment.Left); + this.listviewgroupTypeChain = new ListViewGroup("Element Type Chain", System.Windows.Forms.HorizontalAlignment.Left); + this.listviewNodeDetails.Groups.AddRange(new System.Windows.Forms.ListViewGroup[] { + listviewgroupAbstract, + listviewgroupElement, + listviewgroupBaseType, + listviewgroupTypeChain}); + + try + { + DirectoryInfo dirInfo = new DirectoryInfo(Path.GetDirectoryName(Application.ExecutablePath)); + if (dirInfo != null) + { + dirInfo = dirInfo.Parent; + if (dirInfo != null) + { + dirInfo = dirInfo.Parent; + if (dirInfo != null) + { + dirInfo = new DirectoryInfo(Path.Combine(dirInfo.FullName, "Mibs")); + if (dirInfo.Exists) + { + MibTypesResolver.RegisterResolver(new FileSystemMibResolver(dirInfo.FullName, true)); + } + } + } + } + } + catch + { } + } + + #region GUI Event Handler + + private void toolbuttonOpenMib_Click(object sender, System.EventArgs e) + { + if (this.dialogOpenMib.ShowDialog() == DialogResult.OK) + { + OpenMib(this.dialogOpenMib.FileName); + } + } + + private void treeMib_AfterSelect(object sender, TreeViewEventArgs e) + { + listviewNodeDetails.Items.Clear(); + + if (e.Node != null) + { + MibTreeNode mtn = e.Node.Tag as MibTreeNode; + if (mtn != null) + { + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Abstract", mtn.NodeType.ToString() }, this.listviewgroupAbstract)); + + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Module", (mtn.Entity.Module != null) ? mtn.Entity.Module.Name : "" }, this.listviewgroupElement)); + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Type", mtn.Entity.GetType().Name }, this.listviewgroupElement)); + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Name", mtn.Entity.Name }, this.listviewgroupElement)); + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Description", mtn.Entity.Description }, this.listviewgroupElement)); + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "OID", mtn.Entity.Value.ToString() }, this.listviewgroupElement)); + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Full OID", MibTypesResolver.ResolveOid(mtn.Entity).GetOidString() }, this.listviewgroupElement)); + if (mtn.Entity is ObjectType) + { + listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Access", (mtn.Entity as ObjectType).Access.ToString() }, this.listviewgroupElement)); + } + + ITypeReferrer tr = mtn.Entity as ITypeReferrer; + if (tr != null) + { + ShowTypeDetails(listviewNodeDetails, this.listviewgroupBaseType, tr.BaseType); + ShowTypeChain(listviewNodeDetails, tr.ReferredType); + } + } + } + } + + #endregion + + #region Methods + + private void OpenMib(string file) + { + try + { + MibDocument md = new MibDocument(file); + MibTypesResolver.ResolveTypes(md.Modules[0]); + + this.treeMib.Nodes.Clear(); + this.listviewNodeDetails.Items.Clear(); + + MibTree mt = new MibTree(md.Modules[0] as MibModule); + if (mt.Root != null) + { + AddNode(mt.Root, this.treeMib.Nodes); + + foreach (TreeNode node in this.treeMib.Nodes) + { + node.Expand(); + } + } + } + catch + { + } + } + + private void AddNode(MibTreeNode mibNode, TreeNodeCollection parentNodes) + { + int imgIndex = 5; //unknown + if ((mibNode.NodeType & MibTreeNodeType.Table) != 0) + { + imgIndex = 1; + } + else if ((mibNode.NodeType & MibTreeNodeType.TableRow) != 0) + { + imgIndex = 2; + } + else if ((mibNode.NodeType & MibTreeNodeType.TableCell) != 0) + { + imgIndex = 3; + } + else if ((mibNode.NodeType & MibTreeNodeType.Scalar) != 0) + { + imgIndex = 4; + } + else if ((mibNode.NodeType & MibTreeNodeType.Container) != 0) + { + imgIndex = 0; + } + + TreeNode newNode = new TreeNode(mibNode.Entity.Name, imgIndex, imgIndex); + newNode.Tag = mibNode; + + parentNodes.Add(newNode); + + foreach (MibTreeNode child in mibNode.ChildNodes) + { + AddNode(child, newNode.Nodes); + } + } + + private void ShowTypeChain(ListView lv, ITypeAssignment type) + { + ShowTypeDetails(lv, this.listviewgroupTypeChain, type); + + ITypeReferrer tr = type as ITypeReferrer; + if ((tr != null) && (tr.ReferredType != null)) + { + lv.Items.Add(new ListViewItem(new string[] { " >>>", "" }, this.listviewgroupTypeChain)); + ShowTypeChain(listviewNodeDetails, tr.ReferredType); + } + } + + private void ShowTypeDetails(ListView lv, ListViewGroup lvg, ITypeAssignment type) + { + lv.Items.Add(new ListViewItem(new string[] { "Module", (type.Module != null) ? type.Module.Name : "" }, lvg)); + lv.Items.Add(new ListViewItem(new string[] { "Type", type.GetType().Name }, lvg)); + lv.Items.Add(new ListViewItem(new string[] { "Name", type.Name }, lvg)); + } + + #endregion + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.resx b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.resx new file mode 100644 index 00000000..973f546b --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/FormMain.resx @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + + AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w + LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZTeXN0 + ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMAAABo + IQAAAk1TRnQBSQFMAgEBBgEAARABAAEQAQABEAEAARABAAT/ASEBAAj/AUIBTQE2BwABNgMAASgDAAFA + AwABIAMAAQEBAAEgBgABIBIAAwQBBQMWAR4DIgEyAzEBTwJGAUQBhwMvAUsDHgErAxsBJgMYASIDFQEd + AxIBGAMNARIDCgENAwcBCQMEAQUDAQECAwQBBQMWAR4DIgEyAzEBTgJGAUQBhwMvAUsDHgErAxsBJgMb + ASYDIQExAyEBMAMdASoDGwEmAxgBIQMLAQ8DAQECgAADAgEDAwwBEAMrAUMCRgFEAYIC/wHwAf8CRgFE + AYIDKgFAAw8BFAMNAREDCwEPAwkBDAMHAQoDBQEHAwQBBQMCAQMDAAEBAwIBAwMLAQ8DKwFDAkYBRAGC + Av8B8AH/AkYBRAGCAyoBQAMOARMDEgEZAT0COwFpAVwBRQFCAawBZwE+AToBxAFaAUUBQwGqATwBOwE6 + AWYDEAEWAwABAYQAAx4BKwJEAUIBewL/AfAB/wLpAdoD/wHxAf8CRAFCAXsDHgErJAADHgErAkQBQgF7 + Av8B8AH/AukB2gP/AfEB/wJEAUIBewMeASsBLgItAUcBdwFHATwByQG7AVQBPQHxA+4B/wG7AVMBPAHx + AXcBRgE8AckBLgItAUeEAAMdASoCRAFCAXcC/wHwAf8B6wHdAbEB/wH3AcEBNwH/Ae0B3wGzA/8B8gH/ + AkQBQgF3Ax0BKhwAAx0BKgJEAUIBdwL/AfAB/wLpAdoB/wLqAdwB/wLrAd4D/wHyAf8CRAFCAXcBZAFJ + AUIBrwG2AVkBQQHxAc0BVAEyAf8BvQF5AWIB/wHFAVABLgH/AbEBUQE1AfEBXAFIAUQBn4QAAkMBQQF2 + Av8B8AH/AukB2gH/AecBqwEhAf8B5wGrASEB/wHnAasBIQH/AeoB2wGwA/8B9AH/AkMBQQF2Ax0BKhgA + AkMBQQF2Av8B8AH/AukB2gH/AuoB3AH/AusB3gH/AuwB3wH/Au0B4QP/AfQB/wGAAUQBMQHaAc4BcAFN + AfwBugFMASoB/wPSAf8BvgGLAXgB/wG7AVIBMgH8AW8BSQE/AbqEAAMdASkCQwFBAXQC/wHxAf8B5wHX + AasB/wHXAZYBDAH/AdcBlgEMAf8B1wGWAQwB/wHoAdgBrgP/AfUB/wJDAUEBdAMdASkUAAMdASkCQwFB + AXQC/wHxAf8C6wHeAf8C7AHfAf8C7QHhAf8C7gHjAf8C7wHlAf8BzQF5AV4B/wHOAXcBWAH3AbwBVAEy + Af8BtAFMASoB/wPmAf8BtwFlAUsB8AFdAUkBRAGdiAADHQEpAkIBQQFyAv8B8gH/AeUB1AGpAf8BzQGJ + AQAB/wHNAYkBAAH/Ac0BiQEAAf8B6AHXAa8D/wH3Af8CQgFBAXIDHAEoFAADHQEpAkIBQQFyAv8B8gH/ + Au0B4QH/Au4B4wH/Au8B5QH/AvAB5wH/AeABuwGqAf8BzgFpAUgB/wHjAcsBwQH5BP8B3gHHAb0B9QF+ + AU8BQgHEAi0BLAFFjAADHAEoAkEBQAFxAv8B9AH/AecB1gGsAf8B0QGOAQQB/wHRAY4BBAH/AdEBjgEE + Af8B7AHbAbMD/wH4Af8CQQFAAXEDHAEoFAADHAEoAkEBQAFxAv8B9AH/Au8B5QH/AvAB5wH/AvEB6QH/ + AvMB6gH/AeQBvgGsAf8B1AGBAWIB/wGGAUoBNAHXAWYBTQFEAaoCLQEsAUWUAAMcAScCQQFAAW8C/wH1 + Af8B7AHcAbMB/wHfAaEBFwH/Ad8BoQEXAf8B3wGhARcB/wHxAeIBuwP/AfoB/wJBAUABbwMcAScUAAMc + AScCQQFAAW8C/wH1Af8C8QHpAf8C8wHqAf8C9AHsAf8C9QHuAf8C9gHwA/8B+gH/AkEBQAFvAxwBJ5gA + AxwBJwJAAT8BbQL/AfcB/wHyAeMBuwH/AfABuAEuAf8B8AG4AS4B/wHwAbgBLgH/AvgB9AP/AfsB/wJA + AT8BbQMcAScUAAMcAScCQAE/AW0C/wH3Af8C9AHsAf8C9QHuAf8C9gHwAf8C9wHyAf8C+AH0A/8B+wH/ + AkABPwFtAxwBJ5gAAxsBJgJAAT8BbAL/AfgB/wH3AeoBwwH/Af0ByQE/Af8B+QHsAccB/wL7AfcB/wL8 + AfkD/wH8Af8CQAE/AWwDGwEmFAADGwEmAkABPwFsAv8B+AH/AvYB8AH/AvcB8gH/AvgB9AH/AvsB9wH/ + AvwB+QP/AfwB/wJAAT8BbAMbASaYAAMbASYCPwE+AWsC/wH6Af8C+AH0Af8C+wH3Af8C3wHVAf8CyQG5 + Af8C4AHWA/8B/gH/Aj8BPgFrGAADGwEmAj8BPgFrAv8B+gH/AvgB9AH/AvsB9wH/At8B1QH/AskBuQH/ + AuAB1gP/Af4B/wI/AT4Ba5wAAxoBJQI/AT0BaQL/AfsB/wL8AfkB/wK8AawB/wQAArwBrAP/Af4B/wI/ + AT0BaRwAAxoBJQI/AT0BaQL/AfsB/wL8AfkB/wK8AawB/wQAArwBrAP/Af4B/wI/AT0BaaAAAxoBJQI+ + AT0BaAL/AfwB/wLLAcEB/wKgAZAB/wLLAcED/wH+Af8CPgE9AWggAAMaASUCPgE9AWgC/wH8Af8CywHB + Af8CoAGQAf8CywHBA/8B/gH/Aj4BPQFopAADGgElAj4BPQFnAv8B/gP/Af4D/wH+Bf8CPgE9AWckAAMa + ASUCPgE9AWcC/wH+A/8B/gP/Af4F/wI+AT0BZ6gAAxoBJAI+AT0BZgI+AT0BZgI+AT0BZgI+AT0BZgMx + AU0oAAMaASQCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYDMQFNlAADIQEwAUABRgFIAXwBQwFOAVIBkgMF + AQccAAMHAQkDEAEWAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEa + AxABFgMHAQkDBwEJAxABFgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEa + AxMBGgMQARYDBwEJAwcBCQMQARYDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEa + AxMBGgMTARoDEAEWAwcBCQwAAjIBMwFQAUMBUQFXAZkBRQFkAXQBwAFYAYsBogHgATwBWAFqAcEDEwEa + AwUBBxgAAjwBOwFpAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGH + AkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAjwBOwFpAjkBNAFpAkABNwGHAkABNwGH + AkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGH + AkABNwGHAkABNwGHAjkBNAFpAjwBOwFpAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGH + AkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAjwBOwFpAw0BEQMa + ASQBRAFNAVEBmAE8AYkBrAHyAWcBrwHTAfoBggHLAewB/wGFAc4B7gH/ARUBWwGCAe8BOgFXAWYBxAE6 + AVcBZgHEAT4BWgFqAb4BPgFaAWoBvgE+AVoBagG+AUQBTQFRAZgDGgEkAw0BEQJGAUMBgQL5AekB/wLz + AeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLz + AeIB/wLzAeIB/wL5AekB/wJGAUMBgQJDAToBgQL5AekB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLz + AeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wL5AekB/wJDAToBgQJG + AUMBgQL5AekB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLz + AeIB/wLzAeIB/wLzAeIB/wLzAeIB/wL5AekB/wJGAUMBgQMHAQkDDQESAUIBWwFmAbIBiAHQAe8B/wF9 + AcoB6QH/AX0BygHpAf8BhwHQAe8B/wEkAXsBqQH/AX0BvAHbAf8BfQG8AdsB/wGNAdEB8wH/AY0B0QHz + Af8BkAHUAfUB/wFCAVsBZgGyATACMQFNAwcBCQJEAUMBegL0AeQC/wHMAUIB/wH+AcsBQQH/AewB0gGG + Af8C2gHJAf8C2AHHAf8C1gHFAf8C1AHDAf8C0wHCAf8C0QHAAf8CzwG+Af8CzgG9Af8CzQG8Af8C9AHk + Af8CRAFDAXoCRgE+AXoC9AHkAv8BzAFDAf8B/gHLAUIB/wHsAdIBhgH/AtoByQH/AtgBxwH/AtYBxQH/ + AtQBwwH/AtMBwgH/AtEBwAH/As8BvgH/As4BvQH/As0BvAH/AvQB5AH/AkYBPgF6AkQBQwF6AvQB5AL/ + AcwBQgH/Af4BywFBAf8B7AHSAYYB/wLaAckB/wLYAccB/wHnAWEBPwH/AecBYQE/Af8B5wFhAT8B/wHn + AWEBPwH/As8BvgH/As4BvQH/As0BvAH/AvQB5AH/AkQBQwF6CAABQwFXAWABpAGKAdMB8AH/AYIBzQHr + Af8BggHNAesB/wGKAdMB8AH/ASQBfAGrAf8BegG5AdgB/wF6AbkB2AH/AYoBzgHwAf8BigHOAfAB/wGP + AdMB9AH/AfQBtgEsAf8BQwFXAWABpAQAAkQBQgF3AvUB5gL/AcwBQgL/Ae4BiAH/AewB0gGGAf8C9QHu + Af8C9QHuAf8C1gHFAf8C9QHuAf8C9QHuAf8C0QHAAf8C9QHuAf8C9QHuAf8CzQG8Af8C9QHmAf8CRAFC + AXcCRwE/AXcC9QHmAv8BzAFDAv8B7gGIAf8B7AHSAYYB/wL1Ae4B/wL1Ae4B/wLWAcUB/wL1Ae4B/wL1 + Ae4B/wLRAcAB/wL1Ae4B/wL1Ae4B/wLNAbwB/wL1AeYB/wJHAT8BdwJEAUIBdwL1AeYC/wHMAUIC/wHu + AYgB/wHsAdIBhgH/AvUB7gH/AvUB7gH/AdkBWAE2Af8B8gHJAbgB/wHyAckBuAH/AdkBWAE2Af8C9QHu + Af8C9QHuAf8CzQG8Af8C9QHmAf8CRAFCAXcIAAFDAVUBXgGeAY4B1gHyAf8BhwHQAe0B/wGHAdAB7QH/ + AY4B1gHyAf8BJgGCAa8B/wF7AboB2AH/AXsBugHYAf8BiwHPAfEB/wGLAc8B8QH/AZEB1QH1Af8B/gHJ + AT8B/wFDAVUBXgGeBAACQwFBAXUC9gHpAv8BzAFCAf8B/gHLAUEB/wHsAdIBhgH/AtoByQH/AtgBxwH/ + AtwBzAH/AtQBwwH/AtMBwgH/AtgByAH/As8BvgH/As4BvQH/As0BvAH/AvYB6QH/AkMBQQF1AkcBPwF1 + AvYB6QL/AcwBQwH/Af4BywFCAf8B7AHSAYYB/wLaAckB/wLYAccB/wLcAcwB/wLUAcMB/wLTAcIB/wLY + AcgB/wLPAb4B/wLOAb0B/wLNAbwB/wL2AekB/wJHAT8BdQJDAUEBdQL2AekC/wHMAUIB/wH+AcsBQQH/ + AewB0gGGAf8C2gHJAf8C2AHHAf8ByAFPAS0B/wHeAbYBngH/Ad4BtQGdAf8ByAFPAS0B/wLPAb4B/wLO + Ab0B/wLNAbwB/wL2AekB/wJDAUEBdQgAAUQBVQFdAZsBkgHaAfQB/wGLAdQB8AH/AYsB1AHwAf8BkgHa + AfQB/wEpAYUBswH/AX0BvAHaAf8BfQG8AdoB/wGNAdEB8wH/AY0B0QHzAf8BkwHXAfYB/wLrAd0B/wFE + AVUBXQGbBAACQgFBAXMC9wHrAv8BzAFCAv8B7gGIAf8B7AHSAYYB/wL3AfEB/wL3AfEB/wLWAcUB/wL3 + AfEB/wL3AfEB/wLRAcAB/wL3AfEB/wL3AfEB/wLNAbwB/wL3AesB/wJCAUEBcwJHAT8BcwL3AesC/wHM + AUMC/wHuAYgB/wHsAdIBhgH/AvcB8QH/AvcB8QH/AtYBxQH/AvcB8QH/AvcB8QH/AtEBwAH/AvcB8QH/ + AvcB8QH/As0BvAH/AvcB6wH/AkcBPwFzAkIBQQFzAvcB6wL/AcwBQgL/Ae4BiAH/AewB0gGGAf8C9wHx + Af8C9wHxAf8BuAFHASUB/wHzAcsBuQH/AfMBywG5Af8BuAFHASUB/wL3AfEB/wL3AfEB/wLNAbwB/wL3 + AesB/wJCAUEBcwgAAUQBUwFbApcB3gH2Af8BkAHYAfIB/wGQAdgB8gH/AZcB3gH2Af8BKwGJAbcB/wGA + Ab0B3AH/AYABvQHcAf8BjwHTAfUB/wGPAdMB9QH/AZUB2QH4Af8C9QHuAf8BRAFTAVsBlwQAAkIBQQFy + AvgB7gL/AcwBQgH/Af4BywFBAf8B7AHSAYYB/wLaAckB/wLYAccB/wLdAc4B/wLUAcMB/wLTAcIB/wLZ + AcoB/wLPAb4B/wLOAb0B/wLNAbwB/wL4Ae4B/wJCAUEBcgJIAUABcgL4Ae4B/wHsAYYBYwH/AeIBewFZ + Af8B1AFuAUwB/wHEAWABPgH/AbYBUgEwAf8BrQFHASUB/wGrAUMBIQH/AbEBRAEiAf8BvQFKASgB/wHM + AVIBMAH/AdsBWgE4Af8B6AFiAUAB/wL4Ae4B/wJIAUABcgJCAUEBcgL4Ae4C/wHMAUIB/wH+AcsBQQH/ + AewB0gGGAf8C2gHJAf8C2AHHAf8BrQFCASAB/wHeAbYBngH/Ad4BtQGdAf8BrQFCASAB/wLPAb4B/wLO + Ab0B/wLNAbwB/wL4Ae4B/wJCAUEBcggAAUQBUwFaAZQBmwHhAfcB/wGUAdsB9AH/AZQB2wH0Af8BmwHh + AfcB/wEuAY0BvAH/AYEBvgHdAf8BgQG+Ad0B/wGQAdQB9gH/AZAB1AH2Af8BlwHbAfkB/wL+Af0B/wFE + AVMBWgGUBAACQQFAAXAC+QHxAv8BzAFCAv8B7gGIAf8B7AHSAYYB/wL5AfUB/wL5AfUB/wLWAcUB/wL5 + AfUB/wL5AfUB/wLRAcAB/wL5AfUB/wL5AfUB/wLNAbwB/wL5AfEB/wJBAUABcAJHAUABcAL5AfEB/wHs + AYYBYwH/AfgBxQF5Af8B7QG1AXgB/wH1AcwBvAH/AfUBzAG8Af8B4AG3AZ8B/wH1AcwBvAH/AfUBzAG8 + Af8B3QG0AZwB/wH1AcwBvAH/AfUBzAG8Af8B6AFiAUAB/wL5AfEB/wJHAUABcAJBAUABcAL5AfEC/wHM + AUIC/wHuAYgB/wHsAdIBhgH/AvkB9QH/AvkB9QH/AasBRAEiAf8B9QHMAbwB/wH1AcwBvAH/AasBRAEi + Af8C+QH1Af8C+QH1Af8CzQG8Af8C+QHxAf8CQQFAAXAIAAFEAVEBVwGQAZ4B5QH5Af8BmAHfAfYB/wGY + Ad8B9gH/AZ4B5QH5Af8BMAGQAcAB/wGDAcAB3wH/AYMBwAHfAf8BkgHWAfgB/wGSAdYB+AH/AZkB3QH6 + Af8BRAFRAVcBkAMjATMEAAJBAUABbgL7AfQC/wHMAUIB/wH+AcsBQQH/AewB0gGGAf8C2gHJAf8C2AHH + Af8C3gHQAf8C1AHDAf8C0wHCAf8C2gHMAf8CzwG+Af8CzgG9Af8CzQG8Af8C+wH0Af8CQQFAAW4CRwFA + AW4C+wH0Af8B7AGGAWMB/wHiAXsBWQH/AdQBbgFMAf8BxAFgAT4B/wG2AVIBMAH/Aa0BRwElAf8BqwFD + ASEB/wGxAUQBIgH/Ab0BSgEoAf8BzAFSATAB/wHbAVoBOAH/AegBYgFAAf8C+wH0Af8CRwFAAW4CQQFA + AW4C+wH0Av8BzAFCAf8B/gHLAUEB/wHsAdIBhgH/AtoByQH/AtgBxwH/AbIBTAEqAf8B3gG2AZ4B/wHe + AbUBnQH/AbIBTAEqAf8CzwG+Af8CzgG9Af8CzQG8Af8C+wH0Af8CQQFAAW4IAAFDAU8BVQGNAaMB6AH7 + Af8BnQHjAfkB/wGdAeMB+QH/AaMB6AH7Af8BMwGUAcUB/wGFAcIB4QH/AYUBwgHhAf8BlAHYAfoB/wGU + AdgB+gH/AZsB3wH8Af8BQwFPAVUBjQgAAkABPwFtAvwB9wL/AcwBQgL/Ae4BiAH/AewB0gGGAf8C/AH6 + Af8C/AH6Af8C1gHFAf8C/AH6Af8C/AH6Af8C0QHAAf8C/AH6Af8C/AH6Af8CzQG8Af8C/AH3Af8CQAE/ + AW0CRwFAAW0C/AH3Av8BzAFDAv8B7gGIAf8B7AHSAYYB/wL8AfoB/wL8AfoB/wLWAcUB/wL8AfoB/wL8 + AfoB/wLRAcAB/wL8AfoB/wL8AfoB/wLNAbwB/wL8AfcB/wJHAUABbQJAAT8BbQL8AfcC/wHMAUIC/wHu + AYgB/wHsAdIBhgH/AvwB+gH/AvwB+gH/AcABWgE4Af8B9gHOAb8B/wH2Ac4BvwH/AcABWgE4Af8C/AH6 + Af8C/AH6Af8CzQG8Af8C/AH3Af8CQAE/AW0IAAFDAU8BVAGKAaYB6wH8Af8BoQHmAfsB/wGhAeYB+wH/ + AaYB6wH8Af8BOgGdAc8B/wGHAcQB4gH/AYcBxAHiAf8BlgHaAfwB/wGWAdoB/AH/AZ4B4gH9Af8BQwFP + AVQBiggAAj8BPgFrAv0B+QL/AcwBQgH/Af4BywFBAf8B9QHOAWIB/wHrAdIBhQH/AekB0AGDAf8B5wHO + AYEB/wHlAcwBgAH/AeQBywF8Af8B4gHJAXoB/wHgAccBeAH/Ad8BxgF3Af8B3gHFAXYB/wL9AfkB/wI/ + AT4BawJHAUABawL9AfkC/wHMAUMB/wH+AcsBQgH/AfUBzgFjAf8B6wHSAYUB/wHpAdABgwH/AecBzgGB + Af8B5QHMAYAB/wHkAcsBfQH/AeIByQF7Af8B4AHHAXkB/wHfAcYBeAH/Ad4BxQF3Af8C/QH5Af8CRwFA + AWsCPwE+AWsC/QH5Av8BzAFCAf8B/gHLAUEB/wH1Ac4BYgH/AesB0gGFAf8B6QHQAYMB/wHRAWoBSAH/ + AekBsQF0Af8B6AGwAXMB/wHRAWoBSAH/AeABxwF4Af8B3wHGAXcB/wHeAcUBdgH/Av0B+QH/Aj8BPgFr + CAABQgFNAVIBhwGpAe4B/QH/AaQB6QH8Af8BpAHpAfwB/wGqAe8B/QH/AUABoQHRAf8BkAHRAfEB/wGW + AdoB+wH/AZcB2wH9Af8BlwHbAf0B/wGfAeMB/gH/AUIBTQFSAYcIAAI/AT4BagL+AfwC/wHMAUIC/wHu + AYgB/wH9AcoBQAH/AfwB6wGFAf8B+wHqAYQB/wH4AcUBOwH/AfYB5QF9Af8B9AHjAXsB/wHzAcABNgH/ + AfEB4AF4Af8B7wHeAXYB/wHvAbwBMgH/Av4B/AH/Aj8BPgFqAkcBQAFqAv4B/AL/AcwBQwL/Ae4BiAH/ + Af0BygFBAf8B/AHrAYUB/wH7AeoBhAH/AfgBxQE8Af8B9gHlAX4B/wH0AeMBfAH/AfMBwAE3Af8B8QHg + AXkB/wHvAd4BdwH/Ae8BvAEzAf8C/gH8Af8CRwFAAWoCPwE+AWoC/gH8Av8BzAFCAv8B7gGIAf8B/QHK + AUAB/wH8AesBhQH/AfsB6gGEAf8B4QF5AVcB/wHzAcABcwH/AfIBvwFyAf8B4QF5AVcB/wHxAeABeAH/ + Ae8B3gF2Af8B7wG8ATIB/wL+AfwB/wI/AT4BaggAAUMBTAFSAYUBrQHxAv8BqwHvAf4B/wGVAeIB+AH/ + AWwByQHtAf8BRgGpAdkB/wGYAdwB/gH/AZgB3AH+Af8BmAHcAf4B/wGYAdwB/gH/AaEB5QL/AUMBTAFS + AYUIAAI+AT0BaAL/Af4C/wHMAUIB/wH+AcsBQQH/Af0BygFAAf8B/AHJAT8B/wH6AccBPQH/AfgBxQE7 + Af8B9gHDAToB/wH1AcIBOAH/AfMBwAE2Af8B8QG+ATQB/wHwAb0BMwH/Ae8BvAEyA/8B/gH/Aj4BPQFo + AkcBQAFoAv8B/gL/AcwBQwH/Af4BywFCAf8B/QHKAUEB/wH8AckBQAH/AfoBxwE+Af8B+AHFATwB/wH2 + AcMBOwH/AfUBwgE5Af8B8wHAATcB/wHxAb4BNQH/AfABvQE0Af8B7wG8ATMD/wH+Af8CRwFAAWgCPgE9 + AWgC/wH+Av8BzAFCAf8B/gHLAUEB/wH9AcoBQAH/AfwByQE/Af8B+gHHAT0B/wHsAYYBYgH/AewBhgFi + Af8B7AGGAWIB/wHsAYYBYgH/AfEBvgE0Af8B8AG9ATMB/wHvAbwBMgP/Af4B/wI+AT0BaAgAAUMBTAFQ + AYMBiAHcAfQB/wFeAcAB6QH/AV0BvwHqAf8BgAHTAfQB/wGcAeMB/QH/AaIB5gL/AaIB5gL/AaIB5gL/ + AaIB5gL/AaYB6gL/AUMBTAFQAYMIAAI+AT0BZzj/Aj4BPQFnAkcBQAFnOP8CRwFAAWcCPgE9AWc4/wI+ + AT0BZwgAATkBOwE9AWEBQgFLAU8BgQFCAUsBTwGBAUIBSwFPAYEBQgFLAU8BgQFCAUsBTwGBAUIBSwFP + AYEBQgFLAU8BgQFCAUsBTwGBAUIBSwFPAYEBQgFLAU8BgQE5ATsBPQFhCAADMQFNAj4BPQFmAj4BPQFm + Aj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFm + Aj4BPQFmAj4BPQFmAzEBTQI3ATQBTQJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJH + AUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgI3ATQBTQMxAU0CPgE9 + AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9 + AWYCPgE9AWYCPgE9AWYCPgE9AWYDMQFNAUIBTQE+BwABPgMAASgDAAFAAwABIAMAAQEBAAEBBgABARYA + A/8RAAGAAf8BgAEBBQABfwEAAQEFAAE/AQABAQUAAR8BAAEBBAABgAEPAYABAQQAAcABBwHAAQMEAAHg + AQMB4AEDBAAB8AEBAfABAQQAAfgBAAH4BQAB/AEAAfwFAAH+AQgB/gEIBAAB/wEAAf8FAAH/AYAB/wGA + BAAB/wHAAf8BwAQAAfgBfwYAAeABPxYAAcABAQYAAcABAQYAAcABAQYAAcABAQYAAcABAQYAAcABAQYA + AcABAwYAAcABAwYAAcABAwYAAcABAwYAAcABAwYAAcABAwYACw== + + + + 211, 17 + + + + + iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 + YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAK6SURBVDhPjZNbSNNRHMfPU9DtwR71oZf5IgkF0YMEEYb2 + EGgG5YNgGQmGSUoYimbel5KKmlM0u3jJSpv3ad7WnGkzb2yO4bByF3WuuTnnnLv47Zw/9YclQQc+/L// + P+d8/r/f+Z8/Ib/HjJDcmhaS3P+Bzf2zjr8qiki+QyuE6dNNbIzFw6F8DJ++AVh97c9GK9jcA4LJAlKI + rQ7sW9/DpauGZSoFg6JwfJSU+TE0XIXOgqCaAwJ5ASn2bb6F19TM4bO+w4z4HgwWC9YcDugpK3Y7umQy + FOZEDMRkZQX7SWS5pMRrboVn9RUHy1/aEqDSajGn0WDZbIZ6bQ0t/f1gIzojI8lPMvaIPPWsN2FP/5yD + ZdmLWLwUi/FhZASSqSlOUtXczBMcGZnFVzGUTSr2jI1wfq/lYHms4Tqkc3MYnZ2F0mDAqs3GV8LaiUhN + TeYFA5mkenelHg5tNQfLw3UxaOrpQZdUiu7xca5/Mc0do6PQb28jPDk5hRf0PiQi5zcR7JoKDpYHaqIg + VyohW1jg+lcZjVwlCzod1p1OXEhMvM8LOtNJvWOpEjZVKQfL/ZVX0NrXh165HP2Tk5hQqzGuUmFQocCm + y4XzCQlpvKA9jTTa1WWwzBdzsNxdfhmfFxcxQRct0Q3UmEzY2t2FdWcHdrcb5+LiHvCC1hTSbFOWwDyT + x8GyuDQCbRIJ3tBPp6CfU0pbcdA3M4mDCs7ExqYzwWHKibo7pNs6T4+yIofDSqtof3IJBtqzTq+Hx+uF + y+OBky5kkh2aT0VFZTNBAEWQFEFqhyvO2pclSe6f03nYnC1EW9FFGOnGGSi+/X14KW6fD3tUtkdzYFiY + 0O801iWSaNFtUteWGST92nL1R/q1Q7ojAkHV0ZCQkuOhocV/c0wguHvgn2APyuPJ6dI4kpV/gzyjtycp + gf8g4Begs1B6Kbj3cQAAAABJRU5ErkJggg== + + + + 337, 17 + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/LwipMibViewer.csproj b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/LwipMibViewer.csproj new file mode 100644 index 00000000..0b1d214d --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/LwipMibViewer.csproj @@ -0,0 +1,92 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {86CC0B65-7985-4017-A252-0A7A18DCAEF3} + WinExe + Properties + LwipMibViewer + LwipMibViewer + v4.0 + 512 + + + + true + bin\Debug\ + DEBUG;TRACE + full + prompt + true + true + 4 + false + + + bin\Release\ + TRACE + true + pdbonly + AnyCPU + prompt + true + true + 4 + + + + + + + + + Form + + + FormMain.cs + + + + + FormMain.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + {CBE20411-5DB7-487D-825D-7694267BB6F5} + SharpSnmpLib.Mib + + + + + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Program.cs b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Program.cs new file mode 100644 index 00000000..cd3ef314 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Program.cs @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Windows.Forms; + +namespace LwipMibViewer +{ + static class Program + { + /// + /// Der Haupteinstiegspunkt für die Anwendung. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new FormMain()); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/AssemblyInfo.cs b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..06e7286c --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die mit einer Assembly verknüpft sind. +[assembly: AssemblyTitle("LwipMibViewer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LwipMibViewer")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar +// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von +// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("7ffbd1c1-1c64-45bb-b243-2400446c649d")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern +// übernehmen, indem Sie "*" eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Resources.Designer.cs b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Resources.Designer.cs new file mode 100644 index 00000000..bf157177 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// Dieser Code wurde von einem Tool generiert. +// Laufzeitversion:4.0.30319.225 +// +// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn +// der Code erneut generiert wird. +// +//------------------------------------------------------------------------------ + +namespace LwipMibViewer.Properties { + using System; + + + /// + /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. + /// + // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert + // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert. + // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen + // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LwipMibViewer.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle + /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Resources.resx b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Resources.resx new file mode 100644 index 00000000..af7dbebb --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Settings.Designer.cs b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Settings.Designer.cs new file mode 100644 index 00000000..9831b20f --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// Dieser Code wurde von einem Tool generiert. +// Laufzeitversion:4.0.30319.225 +// +// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn +// der Code erneut generiert wird. +// +//------------------------------------------------------------------------------ + +namespace LwipMibViewer.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Settings.settings b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Settings.settings new file mode 100644 index 00000000..39645652 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/apps/snmp/LwipMibCompiler/LwipMibViewer/app.config b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/app.config new file mode 100644 index 00000000..e3656033 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipMibViewer/app.config @@ -0,0 +1,3 @@ + + + diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/IRestriction.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/IRestriction.cs new file mode 100644 index 00000000..ee2f4536 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/IRestriction.cs @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; + +namespace LwipSnmpCodeGeneration +{ + public interface IRestriction + { + string GetCheckCodeValid(string varNameToCheck); + string GetCheckCodeInvalid(string varNameToCheck); + } + + public class BitMaskRestriction : IRestriction + { + UInt32 mask; + + public BitMaskRestriction(UInt32 mask) + { + this.mask = mask; + } + + public string GetCheckCodeValid(string varNameToCheck) + { + return String.Format("(({0} & {1}) == {0})", varNameToCheck, this.mask); + } + + public string GetCheckCodeInvalid(string varNameToCheck) + { + return String.Format("(({0} & {1}) != {0})", varNameToCheck, this.mask); + } + } + + public class IsEqualRestriction : IRestriction + { + private Int64 value; + + public IsEqualRestriction(Int64 value) + { + this.value = value; + } + + public long Value + { + get { return value; } + } + + public string GetCheckCodeValid(string varNameToCheck) + { + return String.Format("({0} == {1})", varNameToCheck, this.value); + } + + public string GetCheckCodeInvalid(string varNameToCheck) + { + return String.Format("({0} != {1})", varNameToCheck, this.value); + } + } + + public class IsInRangeRestriction : IRestriction + { + private Int64 rangeStart; + private Int64 rangeEnd; + + public IsInRangeRestriction(Int64 rangeStart, Int64 rangeEnd) + { + this.rangeStart = rangeStart; + this.rangeEnd = rangeEnd; + } + + public long RangeStart + { + get { return this.rangeStart; } + } + + public long RangeEnd + { + get { return this.rangeEnd; } + } + + public string GetCheckCodeValid(string varNameToCheck) + { + return String.Format("(({0} >= {1}) && ({0} <= {2}))", varNameToCheck, this.rangeStart, this.rangeEnd); + } + + public string GetCheckCodeInvalid(string varNameToCheck) + { + return String.Format("(({0} < {1}) || ({0} > {2}))", varNameToCheck, this.rangeStart, this.rangeEnd); + } + } + +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/LwipSnmp.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/LwipSnmp.cs new file mode 100644 index 00000000..edac59e0 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/LwipSnmp.cs @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; + +namespace LwipSnmpCodeGeneration +{ + public static class LwipOpts + { + public static bool GenerateEmptyFolders = false; + /// + /// If a tree node only has scalar nodes as child nodes, it is replaced by + /// a single scalar array node in order to save memory and have only one single get/test/set method for all scalars. + /// + public static bool GenerateScalarArrays = true; + /// + /// If a tree node has multiple scalars as subnodes as well as other treenodes it + /// defines a single get/test/set method for all scalar child node. + /// (without other treenodes as child it would have been converted to scalar array node). + /// + public static bool GenerateSingleAccessMethodsForTreeNodeScalars = GenerateScalarArrays; + } + + public static class LwipDefs + { + public const string Null = "NULL"; + public const string Vt_U8 = "u8_t"; + public const string Vt_U16 = "u16_t"; + public const string Vt_U32 = "u32_t"; + public const string Vt_S8 = "s8_t"; + public const string Vt_S16 = "s16_t"; + public const string Vt_S32 = "s32_t"; + public const string Vt_Snmp_err = "snmp_err_t"; + + public const string Incl_SnmpOpts = "lwip/apps/snmp_opts.h"; + public const string Opt_SnmpEnabled = "LWIP_SNMP"; + + public const string Vt_StMib = "struct snmp_mib"; + public const string Vt_StObjectId = "struct snmp_obj_id"; + public const string Vt_StNode = "struct snmp_node"; + public const string Vt_StNodeInstance = "struct snmp_node_instance"; + public const string Vt_StTreeNode = "struct snmp_tree_node"; + public const string Vt_StScalarNode = "struct snmp_scalar_node"; + public const string Vt_StScalarArrayNode = "struct snmp_scalar_array_node"; + public const string Vt_StScalarArrayNodeDef = "struct snmp_scalar_array_node_def"; + public const string Vt_StTableNode = "struct snmp_table_node"; + public const string Vt_StTableColumnDef = "struct snmp_table_col_def"; + public const string Vt_StNextOidState = "struct snmp_next_oid_state"; + + public const string Def_NodeAccessReadOnly = "SNMP_NODE_INSTANCE_READ_ONLY"; + public const string Def_NodeAccessReadWrite = "SNMP_NODE_INSTANCE_READ_WRITE"; + public const string Def_NodeAccessWriteOnly = "SNMP_NODE_INSTANCE_WRITE_ONLY"; + public const string Def_NodeAccessNotAccessible = "SNMP_NODE_INSTANCE_NOT_ACCESSIBLE"; + + public const string Def_ErrorCode_Ok = "SNMP_ERR_NOERROR"; + public const string Def_ErrorCode_WrongValue = "SNMP_ERR_WRONGVALUE"; + public const string Def_ErrorCode_NoSuchInstance = "SNMP_ERR_NOSUCHINSTANCE"; + + public const string FnctSuffix_GetValue = "_get_value"; + public const string FnctSuffix_SetTest = "_set_test"; + public const string FnctSuffix_SetValue = "_set_value"; + public const string FnctSuffix_GetInstance = "_get_instance"; + public const string FnctSuffix_GetNextInstance = "_get_next_instance"; + + public const string FnctName_SetTest_Ok = "snmp_set_test_ok"; + + public static string GetLwipDefForSnmpAccessMode(SnmpAccessMode am) + { + switch (am) + { + case SnmpAccessMode.ReadOnly: return Def_NodeAccessReadOnly; + case SnmpAccessMode.ReadWrite: return Def_NodeAccessReadWrite; + case SnmpAccessMode.NotAccessible: return Def_NodeAccessNotAccessible; + case SnmpAccessMode.WriteOnly: return Def_NodeAccessWriteOnly; + default: throw new NotSupportedException("Unknown SnmpAccessMode!"); + } + } + + public static string GetAsn1DefForSnmpDataType(SnmpDataType dt) + { + switch (dt) + { + // primitive + case SnmpDataType.Null: + return "SNMP_ASN1_TYPE_NULL"; + case SnmpDataType.Bits: + case SnmpDataType.OctetString: + return "SNMP_ASN1_TYPE_OCTET_STRING"; + case SnmpDataType.ObjectIdentifier: + return "SNMP_ASN1_TYPE_OBJECT_ID"; + case SnmpDataType.Integer: + return "SNMP_ASN1_TYPE_INTEGER"; + + // application + case SnmpDataType.IpAddress: + return "SNMP_ASN1_TYPE_IPADDR"; + case SnmpDataType.Counter: + return "SNMP_ASN1_TYPE_COUNTER"; + case SnmpDataType.Gauge: + return "SNMP_ASN1_TYPE_GAUGE"; + case SnmpDataType.TimeTicks: + return "SNMP_ASN1_TYPE_TIMETICKS"; + case SnmpDataType.Opaque: + return "SNMP_ASN1_TYPE_OPAQUE"; + case SnmpDataType.Counter64: + return "SNMP_ASN1_TYPE_COUNTER64"; + default: + throw new NotSupportedException("Unknown SnmpDataType!"); + } + } + + public static string GetLengthForSnmpDataType(SnmpDataType dt) + { + switch (dt) + { + case SnmpDataType.Null: + return "0"; + + case SnmpDataType.Integer: + case SnmpDataType.Counter: + case SnmpDataType.IpAddress: + case SnmpDataType.Gauge: + case SnmpDataType.TimeTicks: + return "4"; + + case SnmpDataType.Counter64: + return "8"; + + case SnmpDataType.OctetString: + case SnmpDataType.ObjectIdentifier: + case SnmpDataType.Bits: + case SnmpDataType.Opaque: + return null; + + default: + throw new NotSupportedException("Unknown SnmpDataType!"); + } + } + } + + public enum SnmpDataType + { + Null, + + Integer, // INTEGER, Integer32 + + Counter, // Counter, Counter32 + Gauge, // Gauge, Gauge32, Unsigned32 + TimeTicks, + + Counter64, + + OctetString, + Opaque, + Bits, + + ObjectIdentifier, + + IpAddress, + } + + public enum SnmpAccessMode + { + ReadOnly, + ReadWrite, + WriteOnly, + NotAccessible + } + +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/LwipSnmpCodeGeneration.csproj b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/LwipSnmpCodeGeneration.csproj new file mode 100644 index 00000000..f4541c0c --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/LwipSnmpCodeGeneration.csproj @@ -0,0 +1,72 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {AABCAB90-1540-45D4-A159-14831A54E9A3} + Library + Properties + LwipSnmpCodeGeneration + LwipSnmpCodeGeneration + v4.0 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + {7DA7C0AB-0982-4BF5-9324-F59A7A08D65B} + CCodeGeneration + + + + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/MibCFile.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/MibCFile.cs new file mode 100644 index 00000000..c48ec29d --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/MibCFile.cs @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System.Collections.Generic; +using CCodeGeneration; +using System; +using System.IO; + +namespace LwipSnmpCodeGeneration +{ + public class MibCFile + { + #region Fields + + private const string PreservedSectionMarker = "LWIP MIB generator - preserved section begin"; + private const string PreservedSectionHeader = + "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" + + PreservedSectionMarker + "\n" + + "Code below is preserved on regeneration. Remove these comment lines to regenerate code.\n" + + "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"; + + private readonly List includes = new List(); + private readonly List defines = new List(); + private readonly List declarations = new List(); + private readonly List implementation = new List(); + private readonly List preservedCode = new List(); + + #endregion + + public MibCFile() + { + } + + #region Accessors + + public List Includes + { + get { return this.includes; } + } + + public List Defines + { + get { return this.defines; } + } + + public List Declarations + { + get { return this.declarations; } + } + + public List Implementation + { + get { return this.implementation; } + } + + public List PreservedCode + { + get { return this.preservedCode; } + } + + #endregion + + #region Methods + + public void Save(CGenerator cGenerator) + { + CFile cFile = new CFile(); + + cFile.AddElement(new Comment("Generated by LwipMibCompiler")); + cFile.AddElement(EmptyLine.SingleLine); + + cFile.AddElement(new PP_Include(LwipDefs.Incl_SnmpOpts)); + CodeContainerBase e = cFile.AddElement(new PP_If(LwipDefs.Opt_SnmpEnabled)) as CodeContainerBase; + e.AddElement(EmptyLine.SingleLine); + + // include header file + string file = cGenerator.FileName; + if (!String.IsNullOrWhiteSpace(file)) + { + string ext = System.IO.Path.GetExtension(file); + + string headerFile = !String.IsNullOrEmpty(ext) ? file.Substring(0, file.Length - ext.Length) : file; + headerFile += ".h"; + + e.AddElement(new PP_Include(headerFile)); + } + + // include common snmp files + e.AddElement(new PP_Include("lwip/apps/snmp.h")); + e.AddElement(new PP_Include("lwip/apps/snmp_core.h")); + e.AddElement(new PP_Include("lwip/apps/snmp_scalar.h")); + e.AddElement(new PP_Include("lwip/apps/snmp_table.h")); + + if (this.includes.Count > 0) + { + e.AddElement(EmptyLine.SingleLine); + e.AddElements(this.includes); + } + + if (this.defines.Count > 0) + { + e.AddElement(EmptyLine.SingleLine); + e.AddElements(this.defines); + } + + if (this.declarations.Count > 0) + { + e.AddElement(EmptyLine.TwoLines); + e.AddElements(this.declarations); + } + + if (this.implementation.Count > 0) + { + e.AddElement(EmptyLine.TwoLines); + e.AddElements(this.implementation); + } + + if (this.preservedCode.Count > 0) + { + e.AddElement(EmptyLine.TwoLines); + e.AddElement(new Comment(PreservedSectionHeader)); + e.AddElement(EmptyLine.SingleLine); + e.AddElements(this.preservedCode); + } + + cFile.Save(cGenerator); + } + + public static string GetPreservedCode(string file) + { + if (File.Exists(file)) + { + using (StreamReader fileStream = new StreamReader(file)) + { + while (!fileStream.EndOfStream) + { + string line = fileStream.ReadLine(); + if (line == PreservedSectionMarker) + { + break; + } + } + + if (!fileStream.EndOfStream) + { + // skip the rest of the comment + spacer line + fileStream.ReadLine(); // "Code below is preserved... + fileStream.ReadLine(); // "+++++++++++++++++++++++... + fileStream.ReadLine(); // */ + fileStream.ReadLine(); // + + string preservedCode = fileStream.ReadToEnd(); + + int lastEndif = preservedCode.LastIndexOf("#endif", StringComparison.Ordinal); + preservedCode = preservedCode.Remove(lastEndif); + + return preservedCode; + } + } + } + + return null; + } + + #endregion + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/MibHeaderFile.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/MibHeaderFile.cs new file mode 100644 index 00000000..95f2a06c --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/MibHeaderFile.cs @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System.Collections.Generic; +using System.Text.RegularExpressions; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class MibHeaderFile + { + + #region Fields + + private readonly List defines = new List(); + private readonly List includes = new List(); + private readonly List functionDeclarations = new List(); + private readonly List variableDeclarations = new List(); + + #endregion + + public MibHeaderFile() + { + } + + #region Accessors + + public List Defines + { + get { return this.defines; } + } + + public List Includes + { + get { return this.includes; } + } + + public List FunctionDeclarations + { + get { return this.functionDeclarations; } + } + + public List VariableDeclarations + { + get { return this.variableDeclarations; } + } + + #endregion + + #region Methods + + public void Save(CGenerator cGenerator) + { + CFile cFile = new CFile(); + + cFile.AddElement(new Comment("Generated by LwipMibCompiler")); + cFile.AddElement(EmptyLine.SingleLine); + + string headerDefine = cGenerator.FileName; + headerDefine = new Regex("[^a-zA-Z0-9]").Replace(headerDefine, "_"); + headerDefine = headerDefine.ToUpperInvariant(); + + CodeContainerBase e = cFile.AddElement(new PP_Ifdef(headerDefine, inverted: true)) as CodeContainerBase; + e.AddElement(new PP_Macro(headerDefine, headerDefine)); + e.AddElement(EmptyLine.SingleLine); + + e.AddElement(new PP_Include(LwipDefs.Incl_SnmpOpts)); + e = e.AddElement(new PP_If(LwipDefs.Opt_SnmpEnabled)) as CodeContainerBase; + e.AddElement(EmptyLine.SingleLine); + + CodeContainerBase cplusplusopen = e.AddElement(new PP_Ifdef("__cplusplus")) as CodeContainerBase; + cplusplusopen.AddElement(new Code("extern \"C\" {")); + e.AddElement(EmptyLine.SingleLine); + + if (this.includes.Count > 0) + { + e.AddElements(this.includes); + e.AddElement(EmptyLine.SingleLine); + } + + if (this.defines.Count > 0) + { + e.AddElements(this.defines); + e.AddElement(EmptyLine.SingleLine); + } + + e.AddElements(this.functionDeclarations, EmptyLine.SingleLine); + e.AddElements(this.variableDeclarations, EmptyLine.SingleLine); + + e.AddElement(EmptyLine.SingleLine); + CodeContainerBase cplusplusclose = e.AddElement(new PP_Ifdef("__cplusplus")) as CodeContainerBase; + cplusplusclose.AddElement(new Code("}")); + + e.AddElement(EmptyLine.SingleLine); + cFile.Save(cGenerator); + } + + #endregion + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/Properties/AssemblyInfo.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..e68b43d5 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die mit einer Assembly verknüpft sind. +[assembly: AssemblyTitle("LwipSnmpCodeGeneration")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LwipSnmpCodeGeneration")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar +// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von +// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("8cfbbb8b-dfbb-4dd5-80c9-e07845dd58c9")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern +// übernehmen, indem Sie "*" eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpMib.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpMib.cs new file mode 100644 index 00000000..f3c027ea --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpMib.cs @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpMib : SnmpTreeNode + { + public int[] BaseOid { get; set; } + + public SnmpMib() + : base(null) + { + } + + public SnmpMib(int[] baseOid) + : base(null) + { + this.BaseOid = baseOid; + } + + public override string FullNodeName + { + get { return this.Name + "_root"; } + } + + public override void GenerateCode(MibCFile mibFile) + { + base.GenerateCode(mibFile); + + System.Diagnostics.Debug.Assert((this.BaseOid != null) && (this.BaseOid.Length > 0)); + + // create and add BaseOID declarations + StringBuilder boidInitialization = new StringBuilder("{"); + foreach (int t in this.BaseOid) + { + boidInitialization.Append(t); + boidInitialization.Append(","); + } + boidInitialization.Length -= 1; + boidInitialization.Append("}"); + + VariableDeclaration boidDecl = new VariableDeclaration( + new VariableType(this.Name + "_base_oid", LwipDefs.Vt_U32, null, ConstType.Value, String.Empty), + boidInitialization.ToString(), true); + + mibFile.Declarations.Add(boidDecl); + mibFile.Declarations.Add(GetExportDeclaration()); + } + + public override void GenerateHeaderCode(MibHeaderFile mibHeaderFile) + { + mibHeaderFile.Includes.Add(new PP_Include("lwip/apps/snmp_core.h")); + + mibHeaderFile.VariableDeclarations.Add(VariablePrototype.FromVariableDeclaration(GetExportDeclaration())); + } + + VariableDeclaration GetExportDeclaration() + { + return new VariableDeclaration( + new VariableType(this.Name, LwipDefs.Vt_StMib, null, ConstType.Value), + String.Format("{{{0}_base_oid, LWIP_ARRAYSIZE({0}_base_oid), &{1}.node}}", this.Name, this.FullNodeName)); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpNode.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpNode.cs new file mode 100644 index 00000000..fceb4d52 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpNode.cs @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text.RegularExpressions; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public abstract class SnmpNode + { + public static readonly Regex NameValidationRegex = new Regex(@"^\w+$"); + + private string name; + private readonly SnmpTreeNode parentNode; + + protected SnmpNode(SnmpTreeNode parentNode) + { + this.parentNode = parentNode; + } + + public SnmpTreeNode ParentNode + { + get { return this.parentNode; } + } + + public virtual uint Oid { get; set; } + + public abstract string FullNodeName + { + get; + } + + public virtual string Name + { + get { return this.name; } + set + { + if (value != this.name) + { + // check for valid name + if (!NameValidationRegex.IsMatch(value)) + { + throw new ArgumentOutOfRangeException("Name"); + } + + this.name = value; + } + } + } + + public virtual void Generate(MibCFile generatedFile, MibHeaderFile generatedHeaderFile) + { + int declCount = generatedFile.Declarations.Count; + int implCount = generatedFile.Implementation.Count; + + this.GenerateHeaderCode(generatedHeaderFile); + this.GenerateCode(generatedFile); + + if (generatedFile.Declarations.Count != declCount) + { + generatedFile.Declarations.Add(EmptyLine.SingleLine); + } + if (generatedFile.Implementation.Count != implCount) + { + generatedFile.Implementation.Add(EmptyLine.SingleLine); + } + } + + public abstract void GenerateCode(MibCFile mibFile); + + public virtual void GenerateHeaderCode(MibHeaderFile mibHeaderFile) + { + } + + /// + /// Called after node structure creation is completed and before code is created. + /// Offers the possibility to perform operations depending on properties/subnodes. + /// If the node shall be transformed to another node(-type) than the own instance + /// may be replaced on parent node by the transformed instance. + /// Calling sequence is always from leafs up to root. So a tree node can assume + /// that the analyze method was already called on all child nodes. + /// E.g. a tree node only has scalar sub nodes -> it transforms itself to a scalar array node + /// + /// The transformed node or null if nothing shall be changed in parent structure. + public virtual void Analyze() + { + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarAggregationNode.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarAggregationNode.cs new file mode 100644 index 00000000..659acd25 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarAggregationNode.cs @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System.Collections.Generic; +using System.Globalization; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public abstract class SnmpScalarAggregationNode: SnmpNode + { + private bool getMethodRequired = false; + private bool testMethodRequired = false; + private bool setMethodRequired = false; + + protected SnmpScalarAggregationNode(SnmpTreeNode parentNode) + : base(parentNode) + { + } + + protected virtual string GetMethodName + { + get { return this.FullNodeName + LwipDefs.FnctSuffix_GetValue; } + } + + protected bool GetMethodRequired + { + get { return this.getMethodRequired; } + } + + protected virtual string TestMethodName + { + get { return this.FullNodeName + LwipDefs.FnctSuffix_SetTest; } + } + + protected bool TestMethodRequired + { + get { return this.testMethodRequired; } + } + + protected virtual string SetMethodName + { + get { return this.FullNodeName + LwipDefs.FnctSuffix_SetValue; } + } + + protected bool SetMethodRequired + { + get { return this.setMethodRequired; } + } + + protected abstract IEnumerable AggregatedScalarNodes + { + get; + } + + public override void Analyze() + { + base.Analyze(); + + this.getMethodRequired = false; + this.testMethodRequired = false; + this.setMethodRequired = false; + + foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes) + { + if ((scalarNode.AccessMode == SnmpAccessMode.ReadOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite)) + { + this.getMethodRequired = true; + } + if ((scalarNode.AccessMode == SnmpAccessMode.WriteOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite)) + { + this.testMethodRequired = true; + this.setMethodRequired = true; + } + + if (this.getMethodRequired && this.setMethodRequired) + { + break; + } + } + } + + protected void GenerateAggregatedCode(MibCFile mibFile, VariableType instanceType, string switchSelector, bool generateDeclarations = true, bool generateImplementations = true) + { + if (this.getMethodRequired) + { + FunctionDeclaration getMethodDecl = new FunctionDeclaration(this.GetMethodName, isStatic: true); + getMethodDecl.Parameter.Add(instanceType); + getMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); + getMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_U16); + + if (generateDeclarations) + { + mibFile.Declarations.Add(getMethodDecl); + } + if (generateImplementations) + { + Function getMethod = Function.FromDeclaration(getMethodDecl); + GenerateGetMethodCode(getMethod, switchSelector); + mibFile.Implementation.Add(getMethod); + } + } + + if (this.testMethodRequired) + { + FunctionDeclaration testMethodDecl = new FunctionDeclaration(this.TestMethodName, isStatic: true); + testMethodDecl.Parameter.Add(instanceType); + testMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16)); + testMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); + testMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); + + if (generateDeclarations) + { + mibFile.Declarations.Add(testMethodDecl); + } + if (generateImplementations) + { + Function testMethod = Function.FromDeclaration(testMethodDecl); + GenerateTestMethodCode(testMethod, switchSelector); + mibFile.Implementation.Add(testMethod); + } + } + + if (this.setMethodRequired) + { + FunctionDeclaration setMethodDecl = new FunctionDeclaration(this.SetMethodName, isStatic: true); + setMethodDecl.Parameter.Add(instanceType); + setMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16)); + setMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); + setMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); + + if (generateDeclarations) + { + mibFile.Declarations.Add(setMethodDecl); + } + if (generateImplementations) + { + Function setMethod = Function.FromDeclaration(setMethodDecl); + GenerateSetMethodCode(setMethod, switchSelector); + mibFile.Implementation.Add(setMethod); + } + } + } + + protected virtual void GenerateGetMethodCode(Function getMethod, string switchSelector) + { + VariableDeclaration returnValue = new VariableDeclaration((VariableType)getMethod.ReturnType.Clone()); + returnValue.Type.Name = "value_len"; + getMethod.Declarations.Add(returnValue); + Switch sw = new Switch(switchSelector); + + bool valueVarUsed = false; + + foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes) + { + if ((scalarNode.AccessMode == SnmpAccessMode.ReadOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite)) + { + SwitchCase sc = new SwitchCase(scalarNode.Oid.ToString(CultureInfo.InvariantCulture)); + sc.Declarations.Add(new Comment(scalarNode.Name, singleLine: true)); + + scalarNode.GenerateGetMethodCode(sc, getMethod.Parameter[1].Name, ref valueVarUsed, returnValue.Type.Name); + + sw.Switches.Add(sc); + } + } + + SwitchCase scd = SwitchCase.GenerateDefault(); + scd.AddCodeFormat("LWIP_DEBUGF(SNMP_MIB_DEBUG,(\"{0}(): unknown id: %\"S32_F\"\\n\", {1}));", getMethod.Name, switchSelector); + scd.AddCodeFormat("{0} = 0;", returnValue.Type.Name); + sw.Switches.Add(scd); + + if (!valueVarUsed) + { + getMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getMethod.Parameter[1].Name); + } + + getMethod.AddElement(sw); + + getMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + } + + protected virtual void GenerateTestMethodCode(Function testMethod, string switchSelector) + { + VariableDeclaration returnValue = new VariableDeclaration((VariableType)testMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_WrongValue); + returnValue.Type.Name = "err"; + testMethod.Declarations.Add(returnValue); + Switch sw = new Switch(switchSelector); + + bool valueVarUsed = false; + bool lenVarUsed = false; + + foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes) + { + if ((scalarNode.AccessMode == SnmpAccessMode.WriteOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite)) + { + SwitchCase sc = new SwitchCase(scalarNode.Oid.ToString(CultureInfo.InvariantCulture)); + sc.Declarations.Add(new Comment(scalarNode.Name, singleLine: true)); + + scalarNode.GenerateTestMethodCode(sc, testMethod.Parameter[2].Name, ref valueVarUsed, testMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name); + + sw.Switches.Add(sc); + } + } + + SwitchCase scd = SwitchCase.GenerateDefault(); + scd.AddCodeFormat("LWIP_DEBUGF(SNMP_MIB_DEBUG,(\"{0}(): unknown id: %\"S32_F\"\\n\", {1}));", testMethod.Name, switchSelector); + sw.Switches.Add(scd); + + if (!valueVarUsed) + { + testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[2].Name); + } + if (!lenVarUsed) + { + testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[1].Name); + } + + testMethod.AddElement(sw); + + testMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + } + + protected virtual void GenerateSetMethodCode(Function setMethod, string switchSelector) + { + VariableDeclaration returnValue = new VariableDeclaration((VariableType)setMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_Ok); + returnValue.Type.Name = "err"; + setMethod.Declarations.Add(returnValue); + Switch sw = new Switch(switchSelector); + + bool valueVarUsed = false; + bool lenVarUsed = false; + + foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes) + { + if ((scalarNode.AccessMode == SnmpAccessMode.WriteOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite)) + { + SwitchCase sc = new SwitchCase(scalarNode.Oid.ToString(CultureInfo.InvariantCulture)); + sc.Declarations.Add(new Comment(scalarNode.Name, singleLine: true)); + + scalarNode.GenerateSetMethodCode(sc, setMethod.Parameter[2].Name, ref valueVarUsed, setMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name); + + sw.Switches.Add(sc); + } + } + + SwitchCase scd = SwitchCase.GenerateDefault(); + scd.AddCodeFormat("LWIP_DEBUGF(SNMP_MIB_DEBUG,(\"{0}(): unknown id: %\"S32_F\"\\n\", {1}));", setMethod.Name, switchSelector); + sw.Switches.Add(scd); + + if (!valueVarUsed) + { + setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[2].Name); + } + if (!lenVarUsed) + { + setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[1].Name); + } + + setMethod.AddElement(sw); + + setMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarArrayNode.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarArrayNode.cs new file mode 100644 index 00000000..3d66492b --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarArrayNode.cs @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarArrayNode : SnmpScalarAggregationNode + { + private readonly List scalarNodes; + + public SnmpScalarArrayNode(List scalarNodes, SnmpTreeNode parentNode) + : base(parentNode) + { + this.scalarNodes = scalarNodes; + } + + public override string FullNodeName + { + get { return this.Name + "_scalars"; } + } + + protected override IEnumerable AggregatedScalarNodes + { + get { return this.scalarNodes; } + } + + public override void GenerateCode(MibCFile mibFile) + { + VariableType instanceType = new VariableType("node", LwipDefs.Vt_StScalarArrayNodeDef, "*", ConstType.Value); + GenerateAggregatedCode( + mibFile, + instanceType, + instanceType.Name + "->oid"); + + + // create and add node definitions + StringBuilder nodeDefs = new StringBuilder(); + foreach (SnmpScalarNode scalarNode in this.scalarNodes) + { + nodeDefs.AppendFormat(" {{{0}, {1}, {2}}}, /* {3} */ \n", + scalarNode.Oid, + LwipDefs.GetAsn1DefForSnmpDataType(scalarNode.DataType), + LwipDefs.GetLwipDefForSnmpAccessMode(scalarNode.AccessMode), + scalarNode.Name); + } + if (nodeDefs.Length > 0) + nodeDefs.Length--; + + VariableDeclaration nodeDefsDecl = new VariableDeclaration( + new VariableType(this.FullNodeName + "_nodes", LwipDefs.Vt_StScalarArrayNodeDef, null, ConstType.Value, String.Empty), + "{\n" + nodeDefs + "\n}" , + isStatic: true); + + mibFile.Declarations.Add(nodeDefsDecl); + + + // create and add node declaration + string nodeInitialization = String.Format("SNMP_SCALAR_CREATE_ARRAY_NODE({0}, {1}, {2}, {3}, {4})", + this.Oid, + nodeDefsDecl.Type.Name, + (this.GetMethodRequired) ? this.GetMethodName : LwipDefs.Null, + (this.TestMethodRequired) ? this.TestMethodName : LwipDefs.Null, + (this.SetMethodRequired) ? this.SetMethodName : LwipDefs.Null + ); + + mibFile.Declarations.Add(new VariableDeclaration( + new VariableType(this.FullNodeName, LwipDefs.Vt_StScalarArrayNode, null, ConstType.Value), + nodeInitialization, + isStatic: true)); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNode.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNode.cs new file mode 100644 index 00000000..c37af466 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNode.cs @@ -0,0 +1,395 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNode: SnmpNode + { + protected const string LocalValueName = "v"; // name of (casted) local value variable + + private SnmpDataType dataType; + private SnmpAccessMode accessMode; + private readonly List restrictions = new List(); + + private bool useExternalMethods = false; + private string externalGetMethod; + private string externalTestMethod; + private string externalSetMethod; + + + public SnmpScalarNode(SnmpTreeNode parentNode) + : base(parentNode) + { + } + + public override string FullNodeName + { + get { return this.Name + "_scalar"; } + } + + public SnmpDataType DataType + { + get { return this.dataType; } + set { this.dataType = value; } + } + + public List Restrictions + { + get { return this.restrictions; } + } + + public SnmpAccessMode AccessMode + { + get { return this.accessMode; } + set { this.accessMode = value; } + } + + public virtual string FixedValueLength + { + get { return null; } + } + + /// + /// If scalar is used as a table index its value becomes part of the OID. This value returns how many OID parts are required to represent this value. + /// + public virtual int OidRepresentationLen + { + get { return -1; } + } + + public bool UseExternalMethods + { + get { return this.useExternalMethods; } + set { this.useExternalMethods = value; } + } + + public string ExternalGetMethod + { + get { return this.externalGetMethod; } + set { this.externalGetMethod = value; } + } + public string ExternalTestMethod + { + get { return this.externalTestMethod; } + set { this.externalTestMethod = value; } + } + public string ExternalSetMethod + { + get { return this.externalSetMethod; } + set { this.externalSetMethod = value; } + } + + public override void GenerateCode(MibCFile mibFile) + { + string getMethodName; + string testMethodName; + string setMethodName; + + if (this.useExternalMethods) + { + getMethodName = this.externalGetMethod; + testMethodName = this.externalTestMethod; + setMethodName = this.externalSetMethod; + } + else + { + getMethodName = LwipDefs.Null; + testMethodName = LwipDefs.Null; + setMethodName = LwipDefs.Null; + + if ((this.accessMode == SnmpAccessMode.ReadWrite) || (this.accessMode == SnmpAccessMode.ReadOnly)) + { + FunctionDeclaration getMethodDecl = new FunctionDeclaration(this.Name + LwipDefs.FnctSuffix_GetValue, isStatic: true); + getMethodDecl.Parameter.Add(new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*")); + getMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); + getMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_U16); + mibFile.Declarations.Add(getMethodDecl); + + Function getMethod = Function.FromDeclaration(getMethodDecl); + getMethodName = getMethod.Name; + + VariableDeclaration returnValue = new VariableDeclaration((VariableType)getMethod.ReturnType.Clone()); + returnValue.Type.Name = "value_len"; + getMethod.Declarations.Add(returnValue); + getMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getMethod.Parameter[0].Name); + + bool valueVarUsed = false; + GenerateGetMethodCode(getMethod, getMethod.Parameter[1].Name, ref valueVarUsed, returnValue.Type.Name); + if (!valueVarUsed) + { + getMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getMethod.Parameter[1].Name); + } + + getMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + + mibFile.Implementation.Add(getMethod); + } + + if ((this.accessMode == SnmpAccessMode.ReadWrite) || (this.accessMode == SnmpAccessMode.WriteOnly)) + { + bool valueVarUsed; + bool lenVarUsed; + VariableDeclaration returnValue; + + if (this.restrictions.Count > 0) + { + FunctionDeclaration testMethodDecl = new FunctionDeclaration(this.Name + LwipDefs.FnctSuffix_SetTest, isStatic: true); + testMethodDecl.Parameter.Add(new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*")); + testMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16)); + testMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); + testMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); + mibFile.Declarations.Add(testMethodDecl); + + Function testMethod = Function.FromDeclaration(testMethodDecl); + testMethodName = testMethod.Name; + + returnValue = new VariableDeclaration((VariableType)testMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_WrongValue); + returnValue.Type.Name = "err"; + testMethod.Declarations.Add(returnValue); + testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[0].Name); + + valueVarUsed = false; + lenVarUsed = false; + + GenerateTestMethodCode(testMethod, testMethod.Parameter[2].Name, ref valueVarUsed, testMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name); + + if (!valueVarUsed) + { + testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[2].Name); + } + if (!lenVarUsed) + { + testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[1].Name); + } + + testMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + + mibFile.Implementation.Add(testMethod); + + } + else + { + testMethodName = LwipDefs.FnctName_SetTest_Ok; + } + + FunctionDeclaration setMethodDecl = null; + setMethodDecl = new FunctionDeclaration(this.Name + LwipDefs.FnctSuffix_SetValue, isStatic: true); + setMethodDecl.Parameter.Add(new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*")); + setMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16)); + setMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); + setMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); + mibFile.Declarations.Add(setMethodDecl); + + Function setMethod = Function.FromDeclaration(setMethodDecl); + setMethodName = setMethod.Name; + + returnValue = new VariableDeclaration((VariableType)setMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_Ok); + returnValue.Type.Name = "err"; + setMethod.Declarations.Add(returnValue); + setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[0].Name); + + valueVarUsed = false; + lenVarUsed = false; + + GenerateSetMethodCode(setMethod, setMethod.Parameter[2].Name, ref valueVarUsed, setMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name); + + if (!valueVarUsed) + { + setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[2].Name); + } + if (!lenVarUsed) + { + setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[1].Name); + } + + setMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + + mibFile.Implementation.Add(setMethod); + } + } + + // create and add node declaration + string nodeInitialization; + if (this.accessMode == SnmpAccessMode.ReadOnly) + { + nodeInitialization = String.Format("SNMP_SCALAR_CREATE_NODE_READONLY({0}, {1}, {2})", + this.Oid, + LwipDefs.GetAsn1DefForSnmpDataType(this.dataType), + getMethodName); + } + else + { + nodeInitialization = String.Format("SNMP_SCALAR_CREATE_NODE({0}, {1}, {2}, {3}, {4}, {5})", + this.Oid, + LwipDefs.GetLwipDefForSnmpAccessMode(this.accessMode), + LwipDefs.GetAsn1DefForSnmpDataType(this.dataType), + getMethodName, + testMethodName, + setMethodName); + } + + mibFile.Declarations.Add(new VariableDeclaration( + new VariableType(this.FullNodeName, LwipDefs.Vt_StScalarNode, null, ConstType.Value), + nodeInitialization, isStatic: true)); + } + + public virtual void GenerateGetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string retLenVarName) + { + bool localValueVarUsed; + if (GenerateValueDeclaration(container, LocalValueName, valueVarName)) + { + valueVarUsed = true; + localValueVarUsed = false; + } + else + { + localValueVarUsed = true; // do not generate UNUSED_ARG code + } + + if (this.FixedValueLength == null) + { + // check that value with variable length fits into buffer + container.AddElement(new Comment(String.Format("TODO: take care that value with variable length fits into buffer: ({0} <= SNMP_MAX_VALUE_SIZE)", retLenVarName), singleLine: true)); + } + + GenerateGetMethodCodeCore(container, LocalValueName, ref localValueVarUsed, retLenVarName); + if (!localValueVarUsed) + { + container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", LocalValueName)); + } + } + + protected virtual void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName) + { + container.AddElement(new Comment(String.Format("TODO: put requested value to '*{0}' here", localValueVarName), singleLine: true)); + container.AddCodeFormat("{0} = {1};", + retLenVarName, + (!String.IsNullOrWhiteSpace(this.FixedValueLength)) ? this.FixedValueLength : "0"); + } + + public virtual void GenerateTestMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + if (this.Restrictions.Count > 0) + { + bool localVarUsed; + if (GenerateValueDeclaration(container, LocalValueName, valueVarName)) + { + valueVarUsed = true; + localVarUsed = false; + } + else + { + localVarUsed = true; // do not generate UNUSED_ARG code + } + + if (!String.IsNullOrWhiteSpace(this.FixedValueLength)) + { + // check for fixed value + container.AddCodeFormat("LWIP_ASSERT(\"Invalid length for datatype\", ({0} == {1}));", lenVarName, this.FixedValueLength); + lenVarUsed = true; + } + + GenerateTestMethodCodeCore(container, LocalValueName, ref localVarUsed, lenVarName, ref lenVarUsed, retErrVarName); + + if (!localVarUsed) + { + container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", LocalValueName)); + } + } + else + { + container.AddCodeFormat("{0} == {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok); + } + } + + protected virtual void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + container.AddElement(new Comment(String.Format("TODO: test new value here:\nif (*{0} == ) {1} = {2};", localValueVarName, retErrVarName, LwipDefs.Def_ErrorCode_Ok))); + } + + public virtual void GenerateSetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + bool localVarUsed; + if (GenerateValueDeclaration(container, LocalValueName, valueVarName)) + { + valueVarUsed = true; + localVarUsed = false; + } + else + { + localVarUsed = true; // do not generate UNUSED_ARG code + } + + GenerateSetMethodCodeCore(container, LocalValueName, ref localVarUsed, lenVarName, ref lenVarUsed, retErrVarName); + + if (!localVarUsed) + { + container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", LocalValueName)); + } + } + + protected virtual void GenerateSetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + container.AddElement(new Comment(String.Format("TODO: store new value contained in '*{0}' here", localValueVarName), singleLine: true)); + } + + + protected virtual bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName) + { + container.AddDeclaration(new VariableDeclaration( + new VariableType(variableName, LwipDefs.Vt_U8, "*"), + "(" + new VariableType(null, LwipDefs.Vt_U8, "*") + ")" + sourceName)); + + return true; + } + + public static SnmpScalarNode CreateFromDatatype(SnmpDataType dataType, SnmpTreeNode parentNode) + { + switch (dataType) + { + case SnmpDataType.Integer: + return new SnmpScalarNodeInt(parentNode); + + case SnmpDataType.Gauge: + case SnmpDataType.Counter: + case SnmpDataType.TimeTicks: + return new SnmpScalarNodeUint(dataType, parentNode); + } + + return new SnmpScalarNode(parentNode); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeBits.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeBits.cs new file mode 100644 index 00000000..906a5a6c --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeBits.cs @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNodeBits : SnmpScalarNode + { + private readonly uint bitCount; + + public SnmpScalarNodeBits(SnmpTreeNode parentNode, uint bitCount) + : base(parentNode) + { + this.DataType = SnmpDataType.Bits; + this.bitCount = bitCount; + } + + public override void GenerateGetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string retLenVarName) + { + container.AddCode(String.Format( + "{0} = snmp_encode_bits(({1} *){2}, SNMP_MAX_VALUE_SIZE, 0 /* TODO: pass real value here */, {3});", + retLenVarName, + LwipDefs.Vt_U8, + valueVarName, + this.bitCount)); + + valueVarUsed = true; + } + + public override void GenerateTestMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + if (this.Restrictions.Count > 0) + { + const string bitVarName = "bits"; + + container.Declarations.Add(new VariableDeclaration(new VariableType(bitVarName, LwipDefs.Vt_U32))); + + IfThenElse ite = new IfThenElse(String.Format( + "snmp_decode_bits(({0} *){1}, {2}, &{3}) == ERR_OK", + LwipDefs.Vt_U8, + valueVarName, + lenVarName, + bitVarName)); + + valueVarUsed = true; + lenVarUsed = true; + + StringBuilder innerIfCond = new StringBuilder(); + foreach (IRestriction restriction in this.Restrictions) + { + innerIfCond.Append(restriction.GetCheckCodeValid(bitVarName)); + innerIfCond.Append(" || "); + } + + innerIfCond.Length -= 4; + + IfThenElse innerIte = new IfThenElse(innerIfCond.ToString()); + innerIte.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok)); + ite.AddElement(innerIte); + container.AddElement(ite); + } + else + { + base.GenerateTestMethodCode(container, valueVarName, ref valueVarUsed, lenVarName, ref lenVarUsed, retErrVarName); + } + } + + public override void GenerateSetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + const string bitVarName = "bits"; + + container.Declarations.Add(new VariableDeclaration(new VariableType(bitVarName, LwipDefs.Vt_U32))); + + IfThenElse ite = new IfThenElse(String.Format( + "snmp_decode_bits(({0} *){1}, {2}, &{3}) == ERR_OK", + LwipDefs.Vt_U8, + valueVarName, + lenVarName, + bitVarName)); + + valueVarUsed = true; + lenVarUsed = true; + + ite.AddElement(new Comment(String.Format("TODO: store new value contained in '{0}' here", bitVarName), singleLine: true)); + + container.AddElement(ite); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeCounter64.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeCounter64.cs new file mode 100644 index 00000000..8f450c8a --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeCounter64.cs @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNodeCounter64 : SnmpScalarNode + { + public SnmpScalarNodeCounter64(SnmpTreeNode parentNode) + : base(parentNode) + { + this.DataType = SnmpDataType.Counter64; + } + + protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName) + { + container.AddDeclaration(new VariableDeclaration( + new VariableType(variableName + "_high", LwipDefs.Vt_U32, "*"), + "(" + new VariableType(null, LwipDefs.Vt_U32, "*").ToString() + ")" + sourceName)); + container.AddDeclaration(new VariableDeclaration( + new VariableType(variableName + "_low", LwipDefs.Vt_U32, "*"), + variableName + "_high + 1")); + + container.AddCode(String.Format("LWIP_UNUSED_ARG({0}_high);", variableName)); + container.AddCode(String.Format("LWIP_UNUSED_ARG({0}_low);", variableName)); + + return false; + } + + public override string FixedValueLength + { + get { return String.Format("(2 * sizeof({0}))", LwipDefs.Vt_U32); } + } + + public override int OidRepresentationLen + { + get { return 1; } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeInt.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeInt.cs new file mode 100644 index 00000000..a381234c --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeInt.cs @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNodeInt : SnmpScalarNode + { + public SnmpScalarNodeInt(SnmpTreeNode parentNode) + : base(parentNode) + { + this.DataType = SnmpDataType.Integer; + } + + protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + System.Diagnostics.Trace.Assert(this.Restrictions.Count > 0); + + StringBuilder ifCond = new StringBuilder(); + foreach (IRestriction restriction in this.Restrictions) + { + ifCond.Append(restriction.GetCheckCodeValid("*" + localValueVarName)); + ifCond.Append(" || "); + + localValueVarUsed = true; + } + + ifCond.Length -= 4; + + IfThenElse ite = new IfThenElse(ifCond.ToString()); + ite.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok)); + container.AddElement(ite); + } + + protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName) + { + container.AddDeclaration(new VariableDeclaration( + new VariableType(variableName, LwipDefs.Vt_S32, "*"), + "(" + new VariableType(null, LwipDefs.Vt_S32, "*") + ")" + sourceName)); + + return true; + } + + public override string FixedValueLength + { + get { return String.Format("sizeof({0})", LwipDefs.Vt_S32); } + } + + public override int OidRepresentationLen + { + get { return 1; } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeObjectIdentifier.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeObjectIdentifier.cs new file mode 100644 index 00000000..5ce8d146 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeObjectIdentifier.cs @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNodeObjectIdentifier: SnmpScalarNode + { + public SnmpScalarNodeObjectIdentifier(SnmpTreeNode parentNode) + : base(parentNode) + { + this.DataType = SnmpDataType.ObjectIdentifier; + } + + protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName) + { + container.AddDeclaration(new VariableDeclaration( + new VariableType(variableName, LwipDefs.Vt_U32, "*"), + "(" + new VariableType(null, LwipDefs.Vt_U32, "*") + ")" + sourceName)); + + return true; + } + + protected override void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName) + { + container.AddElement(new Comment(String.Format("TODO: put requested value to '*{0}' here. '{0}' has to be interpreted as {1}[]", localValueVarName, LwipDefs.Vt_U32), singleLine: true)); + container.AddElement(EmptyLine.SingleLine); + container.AddCode(String.Format("{0} = 0; // TODO: return real value length here (should be 'numOfElements * sizeof({1})')", retLenVarName, LwipDefs.Vt_U32)); + } + + protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + VariableDeclaration objIdLenVar = new VariableDeclaration( + new VariableType(localValueVarName + "_len", LwipDefs.Vt_U8), + String.Format("{0} / sizeof({1})", lenVarName, LwipDefs.Vt_U32)); + lenVarUsed = true; + + container.Declarations.Add(objIdLenVar); + + base.GenerateTestMethodCodeCore(container, localValueVarName, ref localValueVarUsed, lenVarName, ref lenVarUsed, retErrVarName); + + container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", objIdLenVar.Type.Name)); + } + + protected override void GenerateSetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + VariableDeclaration objIdLenVar = new VariableDeclaration( + new VariableType(localValueVarName + "_len", LwipDefs.Vt_U8), + String.Format("{0} / sizeof({1})", lenVarName, LwipDefs.Vt_U32)); + lenVarUsed = true; + + container.Declarations.Add(objIdLenVar); + + base.GenerateSetMethodCodeCore(container, localValueVarName, ref localValueVarUsed, lenVarName, ref lenVarUsed, retErrVarName); + + container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", objIdLenVar.Type.Name)); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeOctetString.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeOctetString.cs new file mode 100644 index 00000000..bf10f9a8 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeOctetString.cs @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNodeOctetString : SnmpScalarNode + { + public SnmpScalarNodeOctetString(SnmpDataType dataType, SnmpTreeNode parentNode) + : base(parentNode) + { + System.Diagnostics.Debug.Assert( + (dataType == SnmpDataType.OctetString) || + (dataType == SnmpDataType.Opaque) || + (dataType == SnmpDataType.IpAddress)); + + this.DataType = dataType; + } + + protected override void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName) + { + if (this.Restrictions.Count > 0) + { + StringBuilder ifCond = new StringBuilder(); + foreach (IRestriction restriction in this.Restrictions) + { + ifCond.Append(restriction.GetCheckCodeValid(retLenVarName)); + ifCond.Append(" || "); + } + + ifCond.Length -= 4; + container.AddElement(new Comment("TODO: take care of len restrictions defined in MIB: " + ifCond, singleLine: true)); + } + base.GenerateGetMethodCodeCore(container, localValueVarName, ref localValueVarUsed, retLenVarName); + } + + protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + System.Diagnostics.Trace.Assert(this.Restrictions.Count > 0); + + // checks refer to length of octet string + StringBuilder ifCond = new StringBuilder(); + foreach (IRestriction restriction in this.Restrictions) + { + ifCond.Append(restriction.GetCheckCodeValid(lenVarName)); + ifCond.Append(" || "); + + lenVarUsed = true; + } + + ifCond.Length -= 4; + + IfThenElse ite = new IfThenElse(ifCond.ToString()); + ite.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok)); + container.AddElement(ite); + } + + public override int OidRepresentationLen + { + get + { + // check restrictions if we are set to one fixed length + if ((this.Restrictions != null) && (this.Restrictions.Count > 0)) + { + foreach (IRestriction restriction in this.Restrictions) + { + if (restriction is IsInRangeRestriction) + { + if ((restriction as IsInRangeRestriction).RangeStart == (restriction as IsInRangeRestriction).RangeEnd) + { + return (int)(restriction as IsInRangeRestriction).RangeStart; + } + } + else if (restriction is IsEqualRestriction) + { + return (int)(restriction as IsEqualRestriction).Value; + } + } + } + + return -1; // variable length + } + } + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeTruthValue.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeTruthValue.cs new file mode 100644 index 00000000..0f557526 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeTruthValue.cs @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNodeTruthValue : SnmpScalarNodeInt + { + public SnmpScalarNodeTruthValue(SnmpTreeNode parentNode) + : base(parentNode) + { + } + + protected override void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName) + { + container.AddCodeFormat("snmp_encode_truthvalue({0}, /* TODO: put requested bool value here */ 0);", localValueVarName); + localValueVarUsed = true; + + container.AddCode(String.Format("{0} = {1};", + retLenVarName, + (!String.IsNullOrWhiteSpace(this.FixedValueLength)) ? this.FixedValueLength : "0")); + } + + protected override void GenerateSetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + VariableType truthVar = new VariableType("bool_value", LwipDefs.Vt_U8); + container.Declarations.Add(new VariableDeclaration(truthVar)); + + container.AddCodeFormat("snmp_decode_truthvalue({0}, &{1});", localValueVarName, truthVar.Name); + localValueVarUsed = true; + + container.AddElement(new Comment(String.Format("TODO: store new value contained in '{0}' here", truthVar.Name), singleLine: true)); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeUint.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeUint.cs new file mode 100644 index 00000000..edc161ac --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpScalarNodeUint.cs @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpScalarNodeUint : SnmpScalarNode + { + public SnmpScalarNodeUint(SnmpDataType dataType, SnmpTreeNode parentNode) + : base(parentNode) + { + System.Diagnostics.Debug.Assert( + (dataType == SnmpDataType.Counter) || + (dataType == SnmpDataType.Gauge) || + (dataType == SnmpDataType.TimeTicks)); + + this.DataType = dataType; + } + + protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName) + { + System.Diagnostics.Trace.Assert(this.Restrictions.Count > 0); + + StringBuilder ifCond = new StringBuilder(); + foreach (IRestriction restriction in this.Restrictions) + { + ifCond.Append(restriction.GetCheckCodeValid("*" + localValueVarName)); + ifCond.Append(" || "); + + localValueVarUsed = true; + } + + ifCond.Length -= 4; + + IfThenElse ite = new IfThenElse(ifCond.ToString()); + ite.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok)); + container.AddElement(ite); + } + + protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName) + { + container.AddDeclaration(new VariableDeclaration( + new VariableType(variableName, LwipDefs.Vt_U32, "*"), + "(" + new VariableType(null, LwipDefs.Vt_U32, "*") + ")" + sourceName)); + + return true; + } + + public override string FixedValueLength + { + get { return String.Format("sizeof({0})", LwipDefs.Vt_U32); } + } + + public override int OidRepresentationLen + { + get { return 1; } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpTableNode.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpTableNode.cs new file mode 100644 index 00000000..8799b013 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpTableNode.cs @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpTableNode: SnmpScalarAggregationNode + { + private readonly List cellNodes = new List(); + private readonly List indexNodes = new List(); + private string augmentedTableRow = null; + + + public SnmpTableNode(SnmpTreeNode parentNode) + : base(parentNode) + { + } + + public List CellNodes + { + get { return cellNodes; } + } + + public List IndexNodes + { + get { return indexNodes; } + } + + public string AugmentedTableRow + { + get { return this.augmentedTableRow; } + set { this.augmentedTableRow = value; } + } + + public override string FullNodeName + { + get + { + string result = this.Name.ToLowerInvariant(); + if (!result.Contains("table")) + { + result += "_table"; + } + + return result; + } + } + + protected override IEnumerable AggregatedScalarNodes + { + get { return this.cellNodes; } + } + + public override void GenerateCode(MibCFile mibFile) + { + FunctionDeclaration getInstanceMethodDecl = new FunctionDeclaration(this.FullNodeName + LwipDefs.FnctSuffix_GetInstance, isStatic: true); + getInstanceMethodDecl.Parameter.Add(new VariableType("column", LwipDefs.Vt_U32, "*", ConstType.Value)); + getInstanceMethodDecl.Parameter.Add(new VariableType("row_oid", LwipDefs.Vt_U32, "*", ConstType.Value)); + getInstanceMethodDecl.Parameter.Add(new VariableType("row_oid_len", LwipDefs.Vt_U8, "")); + getInstanceMethodDecl.Parameter.Add(new VariableType("cell_instance", LwipDefs.Vt_StNodeInstance, "*")); + getInstanceMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); + mibFile.Declarations.Add(getInstanceMethodDecl); + + Function getInstanceMethod = Function.FromDeclaration(getInstanceMethodDecl); + GenerateGetInstanceMethodCode(getInstanceMethod); + mibFile.Implementation.Add(getInstanceMethod); + + + FunctionDeclaration getNextInstanceMethodDecl = new FunctionDeclaration(this.FullNodeName + LwipDefs.FnctSuffix_GetNextInstance, isStatic: true); + getNextInstanceMethodDecl.Parameter.Add(new VariableType("column", LwipDefs.Vt_U32, "*", ConstType.Value)); + getNextInstanceMethodDecl.Parameter.Add(new VariableType("row_oid", LwipDefs.Vt_StObjectId, "*")); + getNextInstanceMethodDecl.Parameter.Add(new VariableType("cell_instance", LwipDefs.Vt_StNodeInstance, "*")); + getNextInstanceMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); + mibFile.Declarations.Add(getNextInstanceMethodDecl); + + Function getNextInstanceMethod = Function.FromDeclaration(getNextInstanceMethodDecl); + GenerateGetNextInstanceMethodCode(getNextInstanceMethod); + mibFile.Implementation.Add(getNextInstanceMethod); + + + VariableType instanceType = new VariableType("cell_instance", LwipDefs.Vt_StNodeInstance, "*"); + GenerateAggregatedCode( + mibFile, + instanceType, + String.Format("SNMP_TABLE_GET_COLUMN_FROM_OID({0}->instance_oid.id)", instanceType.Name)); + + + #region create and add column/table definitions + + StringBuilder colDefs = new StringBuilder(); + foreach (SnmpScalarNode colNode in this.cellNodes) + { + colDefs.AppendFormat(" {{{0}, {1}, {2}}}, /* {3} */ \n", + colNode.Oid, + LwipDefs.GetAsn1DefForSnmpDataType(colNode.DataType), + LwipDefs.GetLwipDefForSnmpAccessMode(colNode.AccessMode), + colNode.Name); + } + if (colDefs.Length > 0) + { + colDefs.Length--; + } + + VariableDeclaration colDefsDecl = new VariableDeclaration( + new VariableType(this.FullNodeName + "_columns", LwipDefs.Vt_StTableColumnDef, null, ConstType.Value, String.Empty), + "{\n" + colDefs + "\n}", + isStatic: true); + + mibFile.Declarations.Add(colDefsDecl); + + string nodeInitialization = String.Format("SNMP_TABLE_CREATE({0}, {1}, {2}, {3}, {4}, {5}, {6})", + this.Oid, + colDefsDecl.Type.Name, + getInstanceMethodDecl.Name, getNextInstanceMethodDecl.Name, + (this.GetMethodRequired) ? this.GetMethodName : LwipDefs.Null, + (this.TestMethodRequired) ? this.TestMethodName : LwipDefs.Null, + (this.SetMethodRequired) ? this.SetMethodName : LwipDefs.Null + ); + + mibFile.Declarations.Add(new VariableDeclaration( + new VariableType(this.FullNodeName, LwipDefs.Vt_StTableNode, null, ConstType.Value), + nodeInitialization, + isStatic: true)); + + #endregion + } + + protected virtual void GenerateGetInstanceMethodCode(Function getInstanceMethod) + { + VariableDeclaration returnValue = new VariableDeclaration((VariableType)getInstanceMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_NoSuchInstance); + returnValue.Type.Name = "err"; + getInstanceMethod.Declarations.Add(returnValue); + + int instanceOidLength = 0; + StringBuilder indexColumns = new StringBuilder(); + foreach (SnmpScalarNode indexNode in this.indexNodes) + { + if (instanceOidLength >= 0) + { + if (indexNode.OidRepresentationLen >= 0) + { + instanceOidLength += indexNode.OidRepresentationLen; + } + else + { + // at least one index column has a variable length -> we cannot perform a static check + instanceOidLength = -1; + } + } + + indexColumns.AppendFormat( + " {0} ({1}, OID length = {2})\n", + indexNode.Name, + indexNode.DataType, + (indexNode.OidRepresentationLen >= 0) ? indexNode.OidRepresentationLen.ToString() : "variable"); + } + if (indexColumns.Length > 0) + { + indexColumns.Length--; + + getInstanceMethod.Declarations.Insert(0, new Comment(String.Format( + "The instance OID of this table consists of following (index) column(s):\n{0}", + indexColumns))); + } + + string augmentsHint = ""; + if (!String.IsNullOrWhiteSpace(this.augmentedTableRow)) + { + augmentsHint = String.Format( + "This table augments table '{0}'! Index columns therefore belong to table '{0}'!\n" + + "You may simply call the '*{1}' method of this table.\n\n", + (this.augmentedTableRow.ToLowerInvariant().EndsWith("entry")) ? this.augmentedTableRow.Substring(0, this.augmentedTableRow.Length-5) : this.augmentedTableRow, + LwipDefs.FnctSuffix_GetInstance); + } + + CodeContainerBase ccb = getInstanceMethod; + if (instanceOidLength > 0) + { + IfThenElse ite = new IfThenElse(String.Format("{0} == {1}", getInstanceMethod.Parameter[2].Name, instanceOidLength)); + getInstanceMethod.AddElement(ite); + ccb = ite; + } + + ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[0].Name); + ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[1].Name); + if (instanceOidLength <= 0) + { + ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[2].Name); + } + ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[3].Name); + + ccb.AddElement(new Comment(String.Format( + "TODO: check if '{0}'/'{1}' params contain a valid instance oid for a row\n" + + "If so, set '{2} = {3};'\n\n" + + "snmp_oid_* methods may be used for easier processing of oid\n\n" + + "{4}" + + "In order to avoid decoding OID a second time in subsequent get_value/set_test/set_value methods,\n" + + "you may store an arbitrary value (like a pointer to target value object) in '{5}->reference'/'{5}->reference_len'.\n" + + "But be aware that not always a subsequent method is called -> Do NOT allocate memory here and try to release it in subsequent methods!\n\n" + + "You also may replace function pointers in '{5}' param for get/test/set methods which contain the default values from table definition,\n" + + "in order to provide special methods, for the currently processed cell. Changed pointers are only valid for current request.", + getInstanceMethod.Parameter[1].Name, + getInstanceMethod.Parameter[2].Name, + returnValue.Type.Name, + LwipDefs.Def_ErrorCode_Ok, + augmentsHint, + getInstanceMethod.Parameter[3].Name + ))); + + getInstanceMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + } + + protected virtual void GenerateGetNextInstanceMethodCode(Function getNextInstanceMethod) + { + getNextInstanceMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getNextInstanceMethod.Parameter[0].Name); + getNextInstanceMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getNextInstanceMethod.Parameter[1].Name); + getNextInstanceMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getNextInstanceMethod.Parameter[2].Name); + + VariableDeclaration returnValue = new VariableDeclaration((VariableType)getNextInstanceMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_NoSuchInstance); + returnValue.Type.Name = "err"; + getNextInstanceMethod.Declarations.Add(returnValue); + + StringBuilder indexColumns = new StringBuilder(); + foreach (SnmpScalarNode indexNode in this.indexNodes) + { + indexColumns.AppendFormat( + " {0} ({1}, OID length = {2})\n", + indexNode.Name, + indexNode.DataType, + (indexNode.OidRepresentationLen >= 0) ? indexNode.OidRepresentationLen.ToString() : "variable"); + } + if (indexColumns.Length > 0) + { + indexColumns.Length--; + + getNextInstanceMethod.Declarations.Insert(0, new Comment(String.Format( + "The instance OID of this table consists of following (index) column(s):\n{0}", + indexColumns))); + } + + string augmentsHint = ""; + if (!String.IsNullOrWhiteSpace(this.augmentedTableRow)) + { + augmentsHint = String.Format( + "This table augments table '{0}'! Index columns therefore belong to table '{0}'!\n" + + "You may simply call the '*{1}' method of this table.\n\n", + (this.augmentedTableRow.ToLowerInvariant().EndsWith("entry")) ? this.augmentedTableRow.Substring(0, this.augmentedTableRow.Length-5) : this.augmentedTableRow, + LwipDefs.FnctSuffix_GetNextInstance); + } + + getNextInstanceMethod.AddElement(new Comment(String.Format( + "TODO: analyze '{0}->id'/'{0}->len' and return the subsequent row instance\n" + + "Be aware that '{0}->id'/'{0}->len' must not point to a valid instance or have correct instance length.\n" + + "If '{0}->len' is 0, return the first instance. If '{0}->len' is longer than expected, cut superfluous OID parts.\n" + + "If a valid next instance is found, store it in '{0}->id'/'{0}->len' and set '{1} = {2};'\n\n" + + "snmp_oid_* methods may be used for easier processing of oid\n\n" + + "{3}" + + "In order to avoid decoding OID a second time in subsequent get_value/set_test/set_value methods,\n" + + "you may store an arbitrary value (like a pointer to target value object) in '{4}->reference'/'{4}->reference_len'.\n" + + "But be aware that not always a subsequent method is called -> Do NOT allocate memory here and try to release it in subsequent methods!\n\n" + + "You also may replace function pointers in '{4}' param for get/test/set methods which contain the default values from table definition,\n" + + "in order to provide special methods, for the currently processed cell. Changed pointers are only valid for current request.", + getNextInstanceMethod.Parameter[1].Name, + returnValue.Type.Name, + LwipDefs.Def_ErrorCode_Ok, + augmentsHint, + getNextInstanceMethod.Parameter[2].Name + ))); + + getNextInstanceMethod.AddElement(new Comment(String.Format( + "For easier processing and getting the next instance, you may use the 'snmp_next_oid_*' enumerator.\n" + + "Simply pass all known instance OID's to it and it returns the next valid one:\n\n" + + "{0} state;\n" + + "{1} result_buf;\n" + + "snmp_next_oid_init(&state, {2}->id, {2}->len, result_buf, LWIP_SNMP_OBJ_ID_LEN);\n" + + "while ({{not all instances passed}}) {{\n" + + " {1} test_oid;\n" + + " {{fill test_oid to create instance oid for next instance}}\n" + + " snmp_next_oid_check(&state, test_oid->id, test_oid->len, {{target_data_ptr}});\n" + + "}}\n" + + "if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {{\n" + + " snmp_oid_assign(row_oid, result_buf->oid, result_buf->len);\n" + + " {3}->reference.ptr = state.reference; //==target_data_ptr, for usage in subsequent get/test/set\n" + + " {4} = {5};\n" + + "}}" + , + LwipDefs.Vt_StNextOidState, + LwipDefs.Vt_StObjectId, + getNextInstanceMethod.Parameter[1].Name, + getNextInstanceMethod.Parameter[2].Name, + returnValue.Type.Name, + LwipDefs.Def_ErrorCode_Ok + ))); + + getNextInstanceMethod.AddCodeFormat("return {0};", returnValue.Type.Name); + } + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpTreeNode.cs b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpTreeNode.cs new file mode 100644 index 00000000..2abf7b58 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/LwipSnmpCodeGeneration/SnmpTreeNode.cs @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +using System; +using System.Collections.Generic; +using System.Text; +using CCodeGeneration; + +namespace LwipSnmpCodeGeneration +{ + public class SnmpTreeNode: SnmpScalarAggregationNode + { + private readonly List childNodes = new List(); + private readonly List childScalarNodes = new List(); + private string fullOid = ""; + + public SnmpTreeNode(SnmpTreeNode parentNode) + : base(parentNode) + { + } + + public override string FullNodeName + { + get { return this.Name + "_treenode"; } + } + + public string FullOid + { + get { return this.fullOid; } + set { this.fullOid = value; } + } + + public List ChildNodes + { + get { return this.childNodes; } + } + + protected override IEnumerable AggregatedScalarNodes + { + get { return this.childScalarNodes; } + } + + private void GenerateAggregatedCode(MibCFile mibFile, bool generateDeclarations, bool generateImplementations) + { + VariableType instanceType = new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*"); + base.GenerateAggregatedCode( + mibFile, + instanceType, + String.Format("{0}->node->oid", instanceType.Name), + generateDeclarations, + generateImplementations); + } + + private void GenerateAggregateMethodDeclarations(MibCFile mibFile) + { + if (LwipOpts.GenerateSingleAccessMethodsForTreeNodeScalars && (this.childScalarNodes.Count > 1)) + { + GenerateAggregatedCode(mibFile, true, false); + } + } + + public override void GenerateCode(MibCFile mibFile) + { + string nodeInitialization; + + if (LwipOpts.GenerateSingleAccessMethodsForTreeNodeScalars && (this.childScalarNodes.Count > 1)) + { + GenerateAggregatedCode(mibFile, false, true); + } + + // create and add node declaration + if (this.childNodes.Count > 0) + { + StringBuilder subnodeArrayInitialization = new StringBuilder(); + + for (int i=0; i=0; i--) + { + this.ChildNodes[i].Analyze(); + } + + // collect scalar nodes + foreach (SnmpNode childNode in this.childNodes) + { + SnmpScalarNode scalarNode = childNode as SnmpScalarNode; + if (scalarNode != null) + { + this.childScalarNodes.Add(scalarNode); + } + } + + base.Analyze(); + + // check if we can merge this node to a scalar array node (all childs need to be scalars) + if (this.childNodes.Count > 0) + { + if (LwipOpts.GenerateScalarArrays && (this.childScalarNodes.Count == this.childNodes.Count)) + { + SnmpScalarArrayNode scalarArrayNode = new SnmpScalarArrayNode(this.childScalarNodes, this.ParentNode); + scalarArrayNode.Oid = this.Oid; + scalarArrayNode.Name = this.Name; + + for (int i=0; i 1)) + { + foreach (SnmpScalarNode scalarNode in this.childScalarNodes) + { + scalarNode.UseExternalMethods = true; + scalarNode.ExternalGetMethod = this.GetMethodName; + scalarNode.ExternalTestMethod = this.TestMethodName; + scalarNode.ExternalSetMethod = this.SetMethodName; + } + } + } + else // if (this.childNodes.Count == 0) + { + if (!LwipOpts.GenerateEmptyFolders && (this.ParentNode != null)) + { + // do not generate this empty folder because it only waste (static) memory + for (int i=0; i + /// The AGENT-CAPABILITIES construct is used to specify implementation characteristics of an SNMP agent sub-system with respect to object types and events. + /// + public sealed class AgentCapabilities : EntityBase + { + /// + /// Creates an instance. + /// + /// + /// + /// + public AgentCapabilities(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols) + : base(module, preAssignSymbols, symbols) + { + } + + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/EntityBase.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/EntityBase.cs new file mode 100644 index 00000000..6da9b18c --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/EntityBase.cs @@ -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; } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/IEntity.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/IEntity.cs new file mode 100644 index 00000000..7360a472 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/IEntity.cs @@ -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 +{ + /// + /// Basic interface for all elements building up the MIB tree, thus having an OID as value. + /// + public interface IEntity : IDeclaration + { + /// + /// Parent name. + /// + string Parent + { + get; + set; + } + + /// + /// Value. + /// + uint Value + { + get; + } + + /// + /// Gets the description. + /// + /// The description. + string Description + { + get; + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ModuleCompliance.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ModuleCompliance.cs new file mode 100644 index 00000000..008c3545 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ModuleCompliance.cs @@ -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 +{ + /// + /// Description of ModuleComplianceNode. + /// + public sealed class ModuleCompliance : EntityBase + { + public ModuleCompliance(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols) + : base(module, preAssignSymbols, symbols) + { + } + + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ModuleIdentity.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ModuleIdentity.cs new file mode 100644 index 00000000..6de28ce6 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ModuleIdentity.cs @@ -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) + { + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/NotificationGroup.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/NotificationGroup.cs new file mode 100644 index 00000000..27d3e4ce --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/NotificationGroup.cs @@ -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 +{ + /// + /// Description of NotificationGroupNode. + /// + public sealed class NotificationGroup : EntityBase + { + public NotificationGroup(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols) + : base(module, preAssignSymbols, symbols) + { + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/NotificationType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/NotificationType.cs new file mode 100644 index 00000000..7386e217 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/NotificationType.cs @@ -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) + { + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectGroup.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectGroup.cs new file mode 100644 index 00000000..d846cdbb --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectGroup.cs @@ -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 +{ + /// + /// Description of ObjectGroupNode. + /// + public sealed class ObjectGroup : EntityBase + { + public ObjectGroup(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols) + : base(module, preAssignSymbols, symbols) + { + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectIdentity.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectIdentity.cs new file mode 100644 index 00000000..9c1e0848 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectIdentity.cs @@ -0,0 +1,21 @@ + +namespace Lextm.SharpSnmpLib.Mib.Elements.Entities +{ + /// + /// Object identifier node. + /// + public sealed class ObjectIdentity : EntityBase + { + + /// + /// Creates a . + /// + /// Module name + /// Header + /// Lexer + public ObjectIdentity(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols) + : base(module, preAssignSymbols, symbols) + { + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectType.cs new file mode 100644 index 00000000..3a8b567a --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/ObjectType.cs @@ -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 _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 ParseIndices(ISymbolEnumerator symbols) + { + Symbol current = symbols.NextNonEOLSymbol(); + + if (current == Symbol.Index) + { + current = symbols.NextNonEOLSymbol(); + current.Expect(Symbol.OpenBracket); + + List indices = new List(); + + 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 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 + + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/OidValueAssignment.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/OidValueAssignment.cs new file mode 100644 index 00000000..3c659407 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Entities/OidValueAssignment.cs @@ -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 +{ + /// + /// Object identifier node. + /// + public sealed class OidValueAssignment : EntityBase + { + /// + /// Creates a . + /// + /// Module + /// Name + /// Lexer + public OidValueAssignment(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols) + : base(module, preAssignSymbols, symbols) + { + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Exports.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Exports.cs new file mode 100644 index 00000000..c1e66e32 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Exports.cs @@ -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 +{ + /// + /// Description of Exports. + /// + public sealed class Exports: IElement + { + private IModule _module; + private readonly IList _types = new List(); + + 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 + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/IDeclaration.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/IDeclaration.cs new file mode 100644 index 00000000..0958ac61 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/IDeclaration.cs @@ -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 + { + /// + /// Name. + /// + string Name + { + get; + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/IElement.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/IElement.cs new file mode 100644 index 00000000..e2db7fd3 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/IElement.cs @@ -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 +{ + /// + /// Construct interface. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] + public interface IElement + { + /// + /// Containing module. + /// + IModule Module + { + get; + } + + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/ITypeReferrer.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/ITypeReferrer.cs new file mode 100644 index 00000000..f0f57056 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/ITypeReferrer.cs @@ -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; } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Imports.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Imports.cs new file mode 100644 index 00000000..3a4ec6ec --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Imports.cs @@ -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 +{ + /// + /// 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. + /// + public sealed class Imports : List, IElement + { + private IModule _module; + + /// + /// Creates an instance. + /// + /// + 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 Dependents + { + get + { + List result = new List(); + + 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 + + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/ImportsFrom.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/ImportsFrom.cs new file mode 100644 index 00000000..cd5154bd --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/ImportsFrom.cs @@ -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 _types = new List(); + + 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 Types + { + get { return _types; } + } + + public override string ToString() + { + return string.Join(", ", _types.ToArray()) + " FROM " + _module; + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/TrapType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/TrapType.cs new file mode 100644 index 00000000..9c5ca457 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/TrapType.cs @@ -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 + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/BaseType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/BaseType.cs new file mode 100644 index 00000000..a4412812 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/BaseType.cs @@ -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; } + } + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/BitsType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/BitsType.cs new file mode 100644 index 00000000..a64c8dbe --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/BitsType.cs @@ -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]; } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Choice.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Choice.cs new file mode 100644 index 00000000..c66d1f3f --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Choice.cs @@ -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 +{ + /// + /// The CHOICE type represents a list of alternatives.. + /// + public sealed class Choice : BaseType + { + /// + /// Creates a instance. + /// + /// + /// + /// + public Choice(IModule module, string name, ISymbolEnumerator symbols) + : base(module, name) + { + while (symbols.NextNonEOLSymbol() != Symbol.OpenBracket) + { + } + + while (symbols.NextNonEOLSymbol() != Symbol.CloseBracket) + { + } + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/ITypeAssignment.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/ITypeAssignment.cs new file mode 100644 index 00000000..e962f9df --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/ITypeAssignment.cs @@ -0,0 +1,6 @@ +namespace Lextm.SharpSnmpLib.Mib.Elements.Types +{ + public interface ITypeAssignment : IDeclaration + { + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/IntegerType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/IntegerType.cs new file mode 100644 index 00000000..4841ad51 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/IntegerType.cs @@ -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 +{ + /// + /// The INTEGER type represents a list of alternatives, or a range of numbers.. + /// Includes Integer32 as it's indistinguishable from INTEGER. + /// + /** + * 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; + + /// + /// Creates an instance. + /// + /// + /// + /// + 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; + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/IpAddressType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/IpAddressType.cs new file mode 100644 index 00000000..84d78d66 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/IpAddressType.cs @@ -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)); + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Macro.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Macro.cs new file mode 100644 index 00000000..9f911ac9 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Macro.cs @@ -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; } + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/ObjectIdentifierType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/ObjectIdentifierType.cs new file mode 100644 index 00000000..cacd415a --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/ObjectIdentifierType.cs @@ -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) + { + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/OctetStringType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/OctetStringType.cs new file mode 100644 index 00000000..f6453ce8 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/OctetStringType.cs @@ -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; } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/OpaqueType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/OpaqueType.cs new file mode 100644 index 00000000..5a7eda33 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/OpaqueType.cs @@ -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) + { + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Sequence.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Sequence.cs new file mode 100644 index 00000000..0162de30 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/Sequence.cs @@ -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 +{ + /// + /// The SEQUENCE type represents a set of specified types. This is roughtly analogous to a struct in C. + /// + public sealed class Sequence : BaseType + { + /// + /// Creates a instance. + /// + /// The module. + /// The name. + /// The enumerator. + 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--; + } + } + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/SequenceOf.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/SequenceOf.cs new file mode 100644 index 00000000..4160ca40 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/SequenceOf.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace Lextm.SharpSnmpLib.Mib.Elements.Types +{ + /// + /// The SEQUENCE OF type represents a list of data sets.. + /// + 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; } + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/TextualConvention.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/TextualConvention.cs new file mode 100644 index 00000000..ab477315 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/TextualConvention.cs @@ -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 + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/TypeAssignment.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/TypeAssignment.cs new file mode 100644 index 00000000..b074ef62 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/TypeAssignment.cs @@ -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 + * + * + */ + + /// + /// + public sealed class TypeAssignment : ITypeAssignment + { + private IModule _module; + private string _name; + private string _type; + private ValueRanges _ranges; + private ValueMap _map; + + /// + /// Creates an . + /// + /// The module. + /// The name. + /// The type. + /// The symbols. + /// if set to true indicates that the syntax clause of a macro is parsed (e.g. OBJECT-TYPE, TEXTUAL-CONVENTION). + 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 Map + { + get { return _map; } + } + + #region ITypeAssignment Member + + public IModule Module + { + get { return _module; } + } + + public string Name + { + get { return _name; } + } + + #endregion + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/UnsignedType.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/UnsignedType.cs new file mode 100644 index 00000000..4866fc90 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Elements/Types/UnsignedType.cs @@ -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; + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/IModule.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/IModule.cs new file mode 100644 index 00000000..d41ab129 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/IModule.cs @@ -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 +{ + /// + /// MIB Module interface. + /// + public interface IModule + { + /// + /// Module name. + /// + string Name + { + get; + } + + Exports Exports + { + get; + } + + Imports Imports + { + get; + } + + /// + /// Entities + Types + all other elements implementing IDeclaration + /// + IList Declarations + { + get; + } + + /// + /// Entities. + /// + IList Entities + { + get; + } + + /// + /// Known types. + /// + IList Types + { + get; + } + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ISymbolEnumerator.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ISymbolEnumerator.cs new file mode 100644 index 00000000..e9dd5920 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ISymbolEnumerator.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace Lextm.SharpSnmpLib.Mib +{ + public interface ISymbolEnumerator: IEnumerator + { + bool PutBack(Symbol item); + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Lexer.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Lexer.cs new file mode 100644 index 00000000..d54b9b93 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Lexer.cs @@ -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 +{ + /// + /// Lexer class that parses MIB files into symbol list. + /// + 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; + + } + + /// + /// Parses MIB file to symbol list. + /// + /// File + /// File stream + 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 continous 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 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 + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MaxAccess.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MaxAccess.cs new file mode 100644 index 00000000..f8029900 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MaxAccess.cs @@ -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 + } + +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibDocument.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibDocument.cs new file mode 100644 index 00000000..aac3b280 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibDocument.cs @@ -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 +{ + /// + /// MIB document. + /// + public sealed class MibDocument + { + private readonly List _modules = new List(); + + /// + /// Initializes a new instance of the class. + /// + /// The file. + public MibDocument(string file) + : this(new Lexer(file)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The lexer. + public MibDocument(Lexer lexer) + { + ISymbolEnumerator symbols = lexer.GetEnumerator(); + + Symbol current; + while ((current = symbols.NextNonEOLSymbol()) != null) + { + symbols.PutBack(current); + _modules.Add(new MibModule(symbols)); + } + } + + /// + /// containing in this document. + /// + public IList Modules + { + get + { + return _modules; + } + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibException.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibException.cs new file mode 100644 index 00000000..efd89b3f --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibException.cs @@ -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 +{ + /// + /// Description of MibException. + /// + [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mib")] + public sealed class MibException : Exception + { + /// + /// Symbol. + /// + public Symbol Symbol { get; private set; } + + /// + /// Creates a . + /// + public MibException() + { + } + + /// + /// Creates a instance with a specific . + /// + /// Message + public MibException(string message) : base(message) + { + } + + /// + /// Creates a instance with a specific and an . + /// + /// Message + /// Inner exception + public MibException(string message, Exception inner) + : base(message, inner) + { + } +#if (!SILVERLIGHT) + /// + /// Creates a instance. + /// + /// Info + /// Context + private MibException(SerializationInfo info, StreamingContext context) : base(info, context) + { + if (info == null) + { + throw new ArgumentNullException("info"); + } + + Symbol = (Symbol)info.GetValue("Symbol", typeof(Symbol)); + } + + /// + /// Gets object data. + /// + /// Info + /// Context + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("Symbol", Symbol); + } +#endif + + /// + /// Creates a with a specific . + /// + /// Message + /// Symbol + /// + 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; + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibModule.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibModule.cs new file mode 100644 index 00000000..3c6b7707 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibModule.cs @@ -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 +{ + /// + /// MIB module class. + /// + [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 _tokens = new List(); + + /// + /// Creates a with a specific . + /// + /// Module name + /// Lexer + [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 + + /// + /// Module name. + /// + public string Name + { + get { return _name; } + } + + public Exports Exports + { + get { return _exports; } + } + + public Imports Imports + { + get { return _imports; } + } + + public List Tokens + { + get { return this._tokens; } + } + + /// + /// Entities + Types + all other elements implementing IDeclaration + /// + public IList Declarations + { + get + { + IList result = new List(); + foreach (IElement e in _tokens) + { + IDeclaration decl = e as IDeclaration; + if (decl != null) + { + result.Add(decl); + } + } + + return result; + } + } + + /// + /// OID nodes. + /// + public IList Entities + { + get + { + IList result = new List(); + foreach (IElement e in _tokens) + { + IEntity entity = e as IEntity; + if (entity != null) + { + result.Add(entity); + } + } + + return result; + } + } + + public IList Types + { + get + { + IList result = new List(); + 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 Entitiy declaration"); + } + else + { + throw new MibException("Invalid Entitiy 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 + + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibResolver.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibResolver.cs new file mode 100644 index 00000000..0f3dfc61 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibResolver.cs @@ -0,0 +1,95 @@ +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, + moduleName + ".*", + (_recursive) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); + + if ((matchedFiles != null) && (matchedFiles.Length >= 1)) + { + foreach (string matchedFile in matchedFiles) + { + 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 modules) + //{ + // foreach (string dependent in module.Dependents) + // { + // if (!DependentFound(dependent, modules)) + // { + // return false; + // } + // } + + // return true; + //} + + //private static bool DependentFound(string dependent, IDictionary 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); + //} + +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTree.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTree.cs new file mode 100644 index 00000000..5a7ddfd3 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTree.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Lextm.SharpSnmpLib.Mib.Elements.Entities; + +namespace Lextm.SharpSnmpLib.Mib +{ + /// + /// Builds up a tree from a single MIB + /// + public class MibTree + { + private MibTreeNode _root = null; + + public MibTree(MibModule module) + { + IList 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) + { + entities.Remove(element); + _root = new MibTreeNode(null, mi); + break; + } + } + + if (_root == null) + { + //no module identity, assume first entity is root + _root = new MibTreeNode(null, entities[0]); + entities.RemoveAt(0); + } + + BuildTree(_root, entities); + UpdateTreeNodeTypes(_root); + } + } + + public MibTreeNode Root + { + get { return _root; } + } + + + private void BuildTree(MibTreeNode node, IList 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); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTreeNode.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTreeNode.cs new file mode 100644 index 00000000..386c8e5c --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTreeNode.cs @@ -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 _childNodes = new List(); + 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 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; + } + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTypesResolver.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTypesResolver.cs new file mode 100644 index 00000000..1e7529af --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/MibTypesResolver.cs @@ -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(@"^(?[^\(]+)\((?\d+)\)$"); + private static readonly List _resolver = new List(); + private static readonly List _cachedModules = new List(); + + 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; + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ObjectIdentifier.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ObjectIdentifier.cs new file mode 100644 index 00000000..04248043 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ObjectIdentifier.cs @@ -0,0 +1,54 @@ +using System.Collections.Generic; +using System.Text; + +namespace Lextm.SharpSnmpLib.Mib +{ + public class ObjectIdentifier: List> + { + public void Add(string name, uint oid) + { + this.Add(new KeyValuePair(name, oid)); + } + + public void Prepend(string name, uint oid) + { + this.Insert(0, new KeyValuePair(name, oid)); + } + + public void Insert(int index, string name, uint oid) + { + this.Insert(index, new KeyValuePair(name, oid)); + } + + public string GetOidString() + { + StringBuilder result = new StringBuilder(); + + foreach (KeyValuePair level in this) + { + result.Append(level.Value); + result.Append('.'); + } + + if (result.Length > 0) + { + result.Length--; + } + + return result.ToString(); + } + + public uint[] GetOidValues() + { + List result = new List(); + + foreach (KeyValuePair level in this) + { + result.Add(level.Value); + } + + return result.ToArray(); + } + + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Status.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Status.cs new file mode 100644 index 00000000..4ddd3bab --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Status.cs @@ -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 + } + +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Symbol.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Symbol.cs new file mode 100644 index 00000000..b11386d8 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/Symbol.cs @@ -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 +{ + /// + /// Description of Symbol. + /// + public sealed class Symbol : IEquatable + { + 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) + { + } + + /// + /// Creates a . + /// + /// File + /// Text + /// Row number + /// column number + public Symbol(string file, string text, int row, int column) + { + _file = file; + _text = text; + _row = row; + _column = column; + } + + /// + /// File. + /// + public string File + { + get + { + return _file; + } + } + + /// + /// Row number. + /// + public int Row + { + get + { + return _row; + } + } + + /// + /// Column number. + /// + public int Column + { + get + { + return _column; + } + } + + /// + /// Returns a that represents this . + /// + /// + public override string ToString() + { + return _text; + } + + /// + /// Determines whether the specified is equal to the current . + /// + /// The to compare with the current . + /// true if the specified is equal to the current ; otherwise, false. + /// + public override bool Equals(object obj) + { + if (obj == null) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + return GetType() == obj.GetType() && Equals((Symbol)obj); + } + + /// + /// Serves as a hash function for a particular type. + /// + /// A hash code for the current . + public override int GetHashCode() + { + return _text.GetHashCode(); + } + + /// + /// The equality operator. + /// + /// Left object + /// Right object + /// + /// Returns true if the values of its operands are equal, false otherwise. + public static bool operator ==(Symbol left, Symbol right) + { + return Equals(left, right); + } + + /// + /// Determines whether the specified is equal to the current . + /// + /// Left object + /// Right object + /// + /// Returns true if the values of its operands are equal, false otherwise. + 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); + } + + /// + /// The inequality operator. + /// + /// Left object + /// Right object + /// + /// Returns true if the values of its operands are not equal, false otherwise. + public static bool operator !=(Symbol left, Symbol right) + { + return !(left == right); + } + + #region IEquatable Members + /// + /// Indicates whether the current object is equal to another object of the same type. + /// + /// An object to compare with this object. + /// true if the current object is equal to the parameter; otherwise, false. + /// + 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 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; + } + } + } +} \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/SymbolList.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/SymbolList.cs new file mode 100644 index 00000000..5b2218e8 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/SymbolList.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Lextm.SharpSnmpLib.Mib +{ + public class SymbolList : List + { + 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 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 + } + + /// + /// Initializes a new instance of the class. + /// + 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 enumerator) + { + if (enumerator.MoveNext()) + { + return enumerator.Current; + } + + return null; + } + + public static Symbol NextNonEOLSymbol(this IEnumerator enumerator) + { + while (enumerator.MoveNext()) + { + if (enumerator.Current != Symbol.EOL) + { + return enumerator.Current; + } + } + + return null; + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ValueMap.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ValueMap.cs new file mode 100644 index 00000000..184dd580 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ValueMap.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; + +namespace Lextm.SharpSnmpLib.Mib +{ + public class ValueMap : Dictionary + { + public ValueMap() + { + } + + /// + /// Returns the values of the map as continous range. At best as one range. + /// + /// + public ValueRanges GetContinousRanges() + { + ValueRanges result = new ValueRanges(); + + if (this.Count > 0) + { + List values = new List(this.Keys); + values.Sort(); + + Int64 last = values[0]; + Int64 offset = values[0]; + for (int i=1; i + /// Gets the highest value contained in this value map. + /// + /// + public Int64 GetHighestValue() + { + Int64 result = 0; + + foreach (Int64 value in this.Keys) + { + if (value > result) + { + result = value; + } + } + + return result; + } + + /// + /// Interprets the single values as bit positions and creates a mask of it. + /// + /// + 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; + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ValueRange.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ValueRange.cs new file mode 100644 index 00000000..3ff5bcb7 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Mib/ValueRange.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; + +namespace Lextm.SharpSnmpLib.Mib +{ + public class ValueRanges: List + { + 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); + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/AssemblyInfo.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..f96080d0 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/AssemblyInfo.cs @@ -0,0 +1,61 @@ +// #SNMP Library. An open source SNMP implementation for .NET. +// Copyright (C) 2008 Lex Y. Li +// +// 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 + +#region Using directives + +using System; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +#endregion + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SharpSnmpLib")] +[assembly: AssemblyDescription("#SNMP Library for .NET")] +[assembly: AssemblyConfiguration("Lesser GPL 2.1+")] +[assembly: AssemblyCompany("LeXtudio")] +[assembly: AssemblyProduct("#SNMPLib")] +[assembly: AssemblyCopyright("(C) 2008-2010 Malcolm Crowe, Lex Li, Steve Santacroce, and other contributors.")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose index type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all the values or you can use the default the Revision and +// Build Numbers by using the '*' as shown below: +[assembly: AssemblyVersion("7.0.011207.31")] +#if (!CF) +[assembly: AssemblyFileVersion("7.0.011207.31")] +#endif +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lextm")] + +[assembly: InternalsVisibleTo("SharpSnmpLib.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f7030532c52524" ++ "993841a0d09420340f3814e1b65473851bdcd18815510b035a2ae9ecee69c4cd2d9e4d6e6d5fbf" ++ "a564e86c4a4cddc9597619a31c060846ebb2e99511a0323ff82b1ebd95d6a4912502945f0e769f" ++ "190a69a439dbfb969ebad72a6f7e2e047907da4a7b9c08c6e98d5f1be8b8cafaf3eb978914059a" ++ "245d4bc1")] diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/Resources.Designer.cs b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/Resources.Designer.cs new file mode 100644 index 00000000..38bc6bb9 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// Dieser Code wurde von einem Tool generiert. +// Laufzeitversion:4.0.30319.225 +// +// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn +// der Code erneut generiert wird. +// +//------------------------------------------------------------------------------ + +namespace Lextm.SharpSnmpLib.Mib { + using System; + + + /// + /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. + /// + // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert + // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert. + // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen + // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lextm.SharpSnmpLib.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle + /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/Resources.resx b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/Resources.resx new file mode 100644 index 00000000..7080a7d1 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/Properties/Resources.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/SharpSnmpLib.Mib.csproj b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/SharpSnmpLib.Mib.csproj new file mode 100644 index 00000000..ff621bbd --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/SharpSnmpLib.Mib.csproj @@ -0,0 +1,139 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {CBE20411-5DB7-487D-825D-7694267BB6F5} + Library + Properties + Lextm.SharpSnmpLib + SharpSnmpLib.Mib + ..\bin\SharpSnmpLib.Mib.xml + 512 + + True + sharpsnmplib.snk + False + File + + + + + + + + + False + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + + + pdbonly + true + ..\bin\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Lextm.SharpSnmpLib.Mib + Designer + + + + + + + + \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/license.txt b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/license.txt new file mode 100644 index 00000000..27946de2 --- /dev/null +++ b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/license.txt @@ -0,0 +1,458 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/sharpsnmplib.snk b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/sharpsnmplib.snk new file mode 100644 index 00000000..fe6f345a Binary files /dev/null and b/src/apps/snmp/LwipMibCompiler/SharpSnmpLib/sharpsnmplib.snk differ diff --git a/src/apps/snmp/README b/src/apps/snmp/README index 95af5bd7..e283de5a 100644 --- a/src/apps/snmp/README +++ b/src/apps/snmp/README @@ -6,25 +6,31 @@ Based on SNMP stack written by Christiaan Simons Rewritten by Martin Hentschel and Dirk Ziegelmeier -Changes: - - SNMPv2c support - - Greatly reduced RAM usage, no memory pools any more - - API cleanup - - MIB2 is separated from SNMP stack - - Support for multiple MIBs (snmp_set_mibs call) - e.g. for private MIB - - Improved MIB2 implementation (tcpConnTable etc.) - - Redesigned simple and generic API for MIB implementation - - Comfortable node types for scalar arrays and tables - - Counter64, bit and truthvalue datatype support - - Callbacks for SNMP writes - - Runs on two APIs: RAW and netconn +Features: + - SNMPv2c support. + - Low RAM usage - no memory pools, stack only. + - MIB2 implementation is separated from SNMP stack. + - Support for multiple MIBs (snmp_set_mibs call) - e.g. for private MIB. + - Simple and generic API for MIB implementation. + - Comfortable node types and helper functions for scalar arrays and tables. + - Counter64, bit and truthvalue datatype support. + - Callbacks for SNMP writes e.g. to implement persistency. + - Runs on two APIs: RAW and netconn. - Async API is gone - the stack now supports netconn API instead, so blocking operations can be done in MIB calls. SNMP runs in a worker thread when netconn API is used. - Simplified thread sync support for MIBs - useful when MIBs - need to access variables shared with other threads without locking - (used in MIB2 to access lwIP stats from lwIP thread) + need to access variables shared with other threads where no locking is + possible. Used in MIB2 to access lwIP stats from lwIP thread. + +MIB compiler (code generator): + - Written in C# but can be compiled and used under Linux with monodevelop. + - Based on a heavily modified version of last LGPL version of + SharpSnmpLib (https://sharpsnmplib.codeplex.com/). + +Notes: + - Stack and MIB compiler were used to implement a Profinet device. + Compiled/implemented MIBs: LLDP-MIB, LLDP-EXT-DOT3-MIB, LLDP-EXT-PNO-MIB. Currently in work: - Traps rewrite - - MIB compiler