chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Tap.Shared;
 
namespace OpenTap
{
    /// <summary>
    /// Representation of an assembly including its dependencies. Part of the object model used in the PluginManager
    /// </summary>
    [DebuggerDisplay("{Name} ({Location})")]
    public class AssemblyData : ITypeDataSource
    {
        private static readonly TraceSource log = Log.CreateSource("AssemblyData");
        /// <summary>
        /// The name of the assembly. This is the same as the filename without extension
        /// </summary>
        public string Name { get; internal set; }
 
        /// <summary>
        /// The file from which this assembly can be loaded. The information contained in this AssemblyData object comes from this file.
        /// </summary>
        public string Location { get; }
 
        /// <summary> Gets the attributes of this .net assembly. </summary>
        public IEnumerable<object> Attributes => Load()?.GetCustomAttributes() ?? Enumerable.Empty<object>();
 
        IEnumerable<ITypeData> ITypeDataSource.Types => PluginTypes;
 
        /// <summary>
        /// <see cref="PluginAssemblyAttribute"/> decorating assembly, if included
        /// </summary>
        public PluginAssemblyAttribute PluginAssemblyAttribute { get; internal set; }
 
        /// <summary>
        /// A list of Assemblies that this Assembly references.
        /// </summary>
        public IEnumerable<AssemblyData> References { get; internal set; }
 
        IEnumerable<ITypeDataSource> ITypeDataSource.References => References;
 
        List<TypeData> pluginTypes;
        
        /// <summary>
        /// Gets a list of plugin types that this Assembly defines
        /// </summary>
        public IEnumerable<TypeData> PluginTypes => pluginTypes;
 
        internal void AddPluginType(TypeData typename)
        {
            if (typename == null)
                return;
            if (pluginTypes == null)
                pluginTypes = new List<TypeData>();
            pluginTypes.Add(typename);
        }
 
        /// <summary> The loaded state of the assembly. </summary>
        internal LoadStatus Status => assembly != null ? LoadStatus.Loaded : (failedLoad ? LoadStatus.FailedToLoad : LoadStatus.NotLoaded);
        
        /// <summary>
        /// Gets the version of this Assembly. This will return null if the version cannot be parsed.
        /// </summary>
        public Version Version { get; internal set; } = null;
 
        // NoSemanticVersion - marker version instead of null to show that no version has been parsed. Null is a valid value for version.
        static readonly SemanticVersion NoSemanticVersion = new SemanticVersion(-1, 0, 0, "", "invalidversion");
        
        SemanticVersion semanticVersion = NoSemanticVersion;
        
        /// <summary>
        /// Gets the version of this Assembly as a <see cref="SemanticVersion"/>. Will return null if the version is not well formatted.
        /// </summary>
        public SemanticVersion SemanticVersion
        {
            get
            {
                if (ReferenceEquals(semanticVersion, NoSemanticVersion))
                {
                    if (SemanticVersion.TryParse(RawVersion, out var version))
                        semanticVersion = version;
                    else if (Version != null)
                        semanticVersion = new SemanticVersion(Version.Major, Version.Minor, Version.Revision, null, null);
                    else
                        semanticVersion = null;
                }
 
                return semanticVersion;
            }
        }
 
        string ITypeDataSource.Version => RawVersion;
        
        /// <summary> Raw version as set by the assembly. </summary>
        internal string RawVersion { get; set; }
 
        internal AssemblyData(string location, Assembly preloadedAssembly = null)
        {
            Location = location;
            this.preloadedAssembly = preloadedAssembly;
        }
 
        /// <summary>  Optionally set for preloaded assemblies.  </summary>
        readonly Assembly preloadedAssembly;
        Assembly assembly;
 
        bool failedLoad;
 
        /// <summary> Gets the assembly without loading it.</summary>
        internal Assembly GetCached() => assembly ?? preloadedAssembly;
 
        /// <summary> Check if the assembly is loaded. </summary>
        internal bool IsLoaded() => (assembly ?? preloadedAssembly) != null;
        
        /// <summary>
        /// Returns the System.Reflection.Assembly corresponding to this. 
        /// If the assembly has not yet been loaded, this call will load it.
        /// </summary>
        public Assembly Load()
        {
            if (failedLoad)
                return null;
            if (assembly == null)
            {
                try
                {
                    var watch = Stopwatch.StartNew();
                    if (preloadedAssembly != null)
                        assembly = preloadedAssembly;
                    else
                    {
                        var _asm = AppDomain.CurrentDomain.GetAssemblies()
                            .FirstOrDefault(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location) && PathUtils.AreEqual(asm.Location, this.Location));
                        assembly = _asm;
                    }
 
                    if (assembly == null)
                    {
                        if (this.Name == "OpenTap")
                        {
                            assembly = typeof(PluginSearcher).Assembly;
                        }
                        else
                        {
                            assembly = Assembly.LoadFrom(Path.GetFullPath(this.Location));
                        }
                    }
                     
                    try
                    {
                        // Find attribute
                        if (PluginAssemblyAttribute != null && PluginAssemblyAttribute.PluginInitMethod != null)
                        {
                            string fullName = PluginAssemblyAttribute.PluginInitMethod;
                            // Break into namespace, class, and method name
                            string[] names = fullName.Split('.');
                            if (names.Count() < 3)
                                throw new Exception($"Could not find method {fullName} in assembly: {Location}");
                            string methodName = names.Last();
                            string className = names.ElementAt(names.Count() - 2);
                            string namespacePath = string.Join(".", names.Take(names.Count() - 2));
                            Type initClass = assembly.GetType($"{namespacePath}.{className}");
                            // Check if loaded class exists and is static (abstract and sealed) and is public
                            if (initClass == null || !initClass.IsClass || !initClass.IsAbstract || !initClass.IsSealed || !initClass.IsPublic)
                                throw new Exception($"Could not find method {fullName} in assembly: {Location}");
                            MethodInfo initMethod = initClass.GetMethod(methodName);
                            // Check if loaded method exists and is static and returns void and is public
                            if (initMethod == null || !initMethod.IsStatic || initMethod.ReturnType != typeof(void) || !initMethod.IsPublic)
                                throw new Exception($"Could not find method {fullName} in assembly: {Location}");
                            // Invoke the method and unwrap the InnerException to get meaningful error message
                            try
                            {
                                initMethod.Invoke(null, null);
                            }
                            catch (TargetInvocationException exc)
                            {
                                throw exc.InnerException;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        failedLoad = true;
                        assembly = null;
                        log.Error($"Failed to load plugins from {this.Location}");
                        log.Debug(ex);
 
                        return null;
                    }
                    log.Debug(watch, "Loaded {0}.", this.Name);
                }
                catch (SystemException ex)
                {
                    failedLoad = true;
                    StringBuilder sb = new StringBuilder(String.Format("Failed to load plugins from {0}", this.Location));
                    bool addedZoneInfo = false;
                    try
                    {
                        var zonetype = Type.GetType("System.Security.Policy.Zone");
                        if (zonetype != null)
                        {               
                            // Hack to support .net core without having to build separate assemblies.
                            dynamic zone = zonetype.GetMethod("CreateFromUrl").Invoke(null, new object[] { this.Location });
                            var sec = zone.SecurityZone.ToString();
                            if (sec.Contains("Internet") || sec.Contains("Untrusted"))
 
                            {
                                // The file is in an NTFS Windows operating system blocked state
                                sb.Append(" The file came from another computer and might be blocked to help protect this computer. Please unblock the file in Windows.");
                                addedZoneInfo = true;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        log.Error("Failed to check Security policy for file.");
                        log.Debug(e);
                        addedZoneInfo = true;
                    }
 
                    if (!addedZoneInfo)
                        sb.Append(" Error: "  + ex.Message);
                    log.Error(sb.ToString());
                    log.Debug(ex);
                }
            }
            return assembly;
        }
 
        /// <summary> Returns name and version as a string. </summary>
        public override string ToString() =>  $"{Name}, {RawVersion}";
    }
}