-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathVcpkgComponentDetector.cs
More file actions
229 lines (195 loc) · 9.75 KB
/
Copy pathVcpkgComponentDetector.cs
File metadata and controls
229 lines (195 loc) · 9.75 KB
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
namespace Microsoft.ComponentDetection.Detectors.Vcpkg;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.Internal;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Microsoft.ComponentDetection.Detectors.Vcpkg.Contracts;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
public class VcpkgComponentDetector : FileComponentDetector
{
private const string VcpkgInstalledFolder = "vcpkg_installed";
private const string ManifestInfoFile = "manifest-info.json";
private readonly HashSet<string> projectRoots = [];
private readonly ConcurrentDictionary<string, string> manifestMappings = new(StringComparer.OrdinalIgnoreCase);
private readonly ICommandLineInvocationService commandLineInvocationService;
private readonly IEnvironmentVariableService envVarService;
public VcpkgComponentDetector(
IComponentStreamEnumerableFactory componentStreamEnumerableFactory,
IObservableDirectoryWalkerFactory walkerFactory,
ICommandLineInvocationService commandLineInvocationService,
IEnvironmentVariableService environmentVariableService,
ILogger<VcpkgComponentDetector> logger)
{
this.ComponentStreamEnumerableFactory = componentStreamEnumerableFactory;
this.Scanner = walkerFactory;
this.commandLineInvocationService = commandLineInvocationService;
this.envVarService = environmentVariableService;
this.Logger = logger;
}
public override string Id { get; } = "Vcpkg";
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Vcpkg)];
public override IList<string> SearchPatterns { get; } = ["vcpkg.spdx.json", ManifestInfoFile];
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.Vcpkg];
public override int Version => 3;
protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default)
{
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;
this.Logger.LogDebug("vcpkg detector found {File}", file);
var projectRootDirectory = Directory.GetParent(file.Location);
if (this.projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path)))
{
return;
}
await this.ParseSpdxFileAsync(this.GetManifestComponentRecorder(singleFileComponentRecorder), file);
}
protected override async Task<IObservable<ProcessRequest>> OnPrepareDetectionAsync(IObservable<ProcessRequest> processRequests, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default)
{
var filteredProcessRequests = new List<ProcessRequest>();
await processRequests.ForEachAsync(async pr =>
{
var fileLocation = pr.ComponentStream.Location;
var fileName = Path.GetFileName(fileLocation);
if (fileName.Equals(ManifestInfoFile, StringComparison.OrdinalIgnoreCase))
{
this.Logger.LogDebug("Discovered VCPKG package manifest file at: {Location}", pr.ComponentStream.Location);
using (var reader = new StreamReader(pr.ComponentStream.Stream))
{
var contents = await reader.ReadToEndAsync().ConfigureAwait(false);
var manifestData = JsonConvert.DeserializeObject<ManifestInfo>(contents);
if (manifestData == null || string.IsNullOrWhiteSpace(manifestData.ManifestPath))
{
this.Logger.LogDebug("Failed to deserialize manifest-info.json or missing ManifestPath at {Path}", pr.ComponentStream.Location);
}
else
{
this.manifestMappings.TryAdd(fileLocation, manifestData.ManifestPath);
}
}
}
else
{
filteredProcessRequests.Add(pr);
}
}).ConfigureAwait(false);
return filteredProcessRequests.ToObservable();
}
private async Task ParseSpdxFileAsync(
ISingleFileComponentRecorder singleFileComponentRecorder,
IComponentStream file)
{
using var reader = new StreamReader(file.Stream);
VcpkgSBOM sbom;
try
{
sbom = JsonConvert.DeserializeObject<VcpkgSBOM>(await reader.ReadToEndAsync());
}
catch (Exception)
{
return;
}
if (sbom?.Packages == null)
{
return;
}
foreach (var item in sbom.Packages)
{
try
{
if (string.IsNullOrEmpty(item.Name))
{
continue;
}
this.Logger.LogDebug("vcpkg parsed package {PackageName}", item.Name);
if (item.SPDXID == "SPDXRef-port")
{
var split = item.VersionInfo.Split('#');
var component = new VcpkgComponent(item.SPDXID, item.Name, split[0], portVersion: split.Length >= 2 ? split[1] : "0", downloadLocation: item.DownloadLocation);
singleFileComponentRecorder.RegisterUsage(new DetectedComponent(component));
}
else if (item.SPDXID == "SPDXRef-binary")
{
var split = item.Name.Split(':');
var component = new VcpkgComponent(item.SPDXID, item.Name, item.VersionInfo, triplet: split[1], downloadLocation: item.DownloadLocation);
singleFileComponentRecorder.RegisterUsage(new DetectedComponent(component));
}
else if (item.SPDXID.StartsWith("SPDXRef-resource-"))
{
var dl = item.DownloadLocation;
var split = dl.Split("#");
var subpath = split.Length > 1 ? split[1] : null;
dl = split.Length > 1 ? split[0] : dl;
split = dl.Split("@");
var version = split.Length > 1 ? split[1] : null;
dl = split.Length > 1 ? split[0] : dl;
var component = new VcpkgComponent(item.SPDXID, item.Name, version, downloadLocation: dl);
singleFileComponentRecorder.RegisterUsage(new DetectedComponent(component));
}
}
catch (Exception e)
{
this.Logger.LogWarning(e, "failed while handling {ItemName}", item.Name);
singleFileComponentRecorder.RegisterPackageParseFailure(item.Name);
}
}
}
/// <summary>
/// Attempts to resolve and return a manifest component recorder for the given recorder.
/// Returns the matching manifest component recorder if found; otherwise, returns the original recorder.
/// </summary>
private ISingleFileComponentRecorder GetManifestComponentRecorder(ISingleFileComponentRecorder singleFileComponentRecorder)
{
try
{
var manifestFileLocation = singleFileComponentRecorder.ManifestFileLocation;
var vcpkgInstalledIndex = manifestFileLocation.IndexOf(VcpkgInstalledFolder, StringComparison.OrdinalIgnoreCase);
if (vcpkgInstalledIndex < 0)
{
this.Logger.LogDebug(
"Could not find '{VcpkgInstalled}' in ManifestFileLocation: '{ManifestFileLocation}'. Returning original recorder.",
VcpkgInstalledFolder,
manifestFileLocation);
return singleFileComponentRecorder;
}
var vcpkgInstalledDir = manifestFileLocation[..(vcpkgInstalledIndex + VcpkgInstalledFolder.Length)];
var preferredManifest = Path.Combine(vcpkgInstalledDir, "vcpkg", ManifestInfoFile);
var fallbackManifest = Path.Combine(vcpkgInstalledDir, ManifestInfoFile);
// Try preferred location first
if (this.manifestMappings.TryGetValue(preferredManifest, out var manifestPath) && manifestPath != null)
{
return this.ComponentRecorder.CreateSingleFileComponentRecorder(manifestPath);
}
else if (this.manifestMappings.TryGetValue(fallbackManifest, out manifestPath) && manifestPath != null)
{
// Use the fallback location.
this.Logger.LogDebug(
"Preferred manifest at '{PreferredManifest}' was not found or invalid. Using fallback manifest at '{FallbackManifest}'.",
preferredManifest,
fallbackManifest);
return this.ComponentRecorder.CreateSingleFileComponentRecorder(manifestPath);
}
this.Logger.LogDebug(
"No valid manifest-info.json found at either '{PreferredManifest}' or '{FallbackManifest}' for base location '{VcpkgInstalledDir}'. Returning original recorder.",
preferredManifest,
fallbackManifest,
vcpkgInstalledDir);
}
catch (Exception ex)
{
this.Logger.LogWarning(
ex,
"An exception occurred while resolving manifest component recorder for '{ManifestFileLocation}'. Returning original recorder.",
singleFileComponentRecorder.ManifestFileLocation);
}
// Always return the original recorder if no manifest is found or on error
return singleFileComponentRecorder;
}
}