Skip to content

Commit e74208d

Browse files
committed
Improve null safety
1 parent 0a65553 commit e74208d

File tree

13 files changed

+43
-29
lines changed

13 files changed

+43
-29
lines changed

Protest/Database/ContactsJsonConverter.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,17 @@ public override void Write(Utf8JsonWriter writer, Database value, JsonSerializer
4040
entry.attributes.TryGetValue("first name", out Database.Attribute firstname);
4141
entry.attributes.TryGetValue("last name", out Database.Attribute lastname);
4242

43-
string name = $"{firstname?.value} {lastname?.value}".Trim();
43+
string name = $"{firstname?.value ?? String.Empty} {lastname?.value ?? String.Empty}".Trim();
4444

4545
writer.WriteStartObject();
4646

47-
if (title?.value.Length > 0) writer.WriteString(_title, title.value);
47+
if (title?.value.Length > 0) writer.WriteString(_title, title?.value ?? String.Empty);
4848
if (name?.Length > 0) writer.WriteString(_name, name);
49-
if (department?.value.Length > 0) writer.WriteString(_department, department.value);
49+
if (department?.value.Length > 0) writer.WriteString(_department, department?.value ?? String.Empty);
5050

51-
if (email?.value.Length > 0) writer.WriteString(_email, email.value);
52-
if (telephoneNumber?.value.Length > 0) writer.WriteString(_telephone, telephoneNumber.value);
53-
if (mobileNumber?.value.Length > 0) writer.WriteString(_mobile, mobileNumber.value);
51+
if (email?.value.Length > 0) writer.WriteString(_email, email?.value ?? String.Empty);
52+
if (telephoneNumber?.value.Length > 0) writer.WriteString(_telephone, telephoneNumber?.value ?? String.Empty);
53+
if (mobileNumber?.value.Length > 0) writer.WriteString(_mobile, mobileNumber?.value ?? String.Empty);
5454

5555
writer.WriteEndObject();
5656
}

Protest/Database/Database.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,13 +219,13 @@ public bool Save(string file, ConcurrentDictionary<string, Attribute> modificati
219219
_ => null
220220
};
221221

222+
if (newEntry is null) return true;
223+
222224
string[] attributesWithNull = newEntry.attributes.Where(attr => attr.Value.value is null).Select(attr => attr.Key).ToArray();
223225
foreach (string key in attributesWithNull) {
224226
newEntry.attributes.TryRemove(key, out _);
225227
}
226228

227-
if (newEntry is null) return true;
228-
229229
dictionary.TryAdd(file, newEntry);
230230

231231
version = DateTime.UtcNow.Ticks;

Protest/Http/Listener.cs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,13 @@ public void Start() {
202202
}
203203

204204
public void Stop() {
205-
if (listener is not null && listener.IsListening) listener.Stop();
206-
listener.Abort();
205+
if (listener is not null) {
206+
if (listener.IsListening) {
207+
listener.Stop();
208+
}
209+
210+
listener.Abort();
211+
}
207212
}
208213

209214
private void ListenerCallback(IAsyncResult result) {
@@ -267,8 +272,8 @@ private void ListenerCallback(IAsyncResult result) {
267272
if (String.Equals(path, "/contacts", StringComparison.Ordinal)) {
268273
byte[] buffer = DatabaseInstances.users.SerializeContacts();
269274
ctx.Response.StatusCode = (int)HttpStatusCode.OK;
270-
ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
271-
ctx.Response.AddHeader("Content-Length", buffer?.Length.ToString() ?? "0");
275+
ctx.Response.OutputStream.Write(buffer!, 0, buffer!.Length);
276+
ctx.Response.AddHeader("Content-Length", buffer!.Length.ToString());
272277
ctx.Response.Close();
273278
return;
274279
}

Protest/Protocols/Dhcp.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,7 @@ private static byte[] Request(long timestamp, byte[] transactionId, string mac,
414414

415415
mac = mac.Replace(":", String.Empty);
416416
mac = mac.Replace("-", String.Empty);
417-
if (mac is null || mac.Length == 12) {
417+
if (mac is not null || mac.Length == 12) {
418418
buffer[index++] = Convert.ToByte(mac[0..2], 16); //client mac address
419419
buffer[index++] = Convert.ToByte(mac[2..4], 16);
420420
buffer[index++] = Convert.ToByte(mac[4..6], 16);

Protest/Proxy/TcpReverseProxy.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ private async Task ListenForClients() {
4747
}
4848

4949
private async Task ServeClient(TcpClient proxyClient) {
50+
if (proxyClient is null) return;
51+
5052
try {
5153
using TcpClient destinationClient = new TcpClient();
5254
await destinationClient.ConnectAsync(destinationEndPoint, cancellationToken);

Protest/Tasks/Fetch.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ public static ConcurrentDictionary<string, string[]> SingleDevice(string target,
283283
}
284284
}
285285

286-
if (!wmi.ContainsKey("manufacturer") && mac.Length > 0) {
286+
if (!wmi.ContainsKey("manufacturer") && String.IsNullOrEmpty(mac)) {
287287
byte[] manufacturerArray = MacLookup.Lookup(mac);
288288
if (manufacturerArray is not null) {
289289
string manufacturer = Encoding.UTF8.GetString(manufacturerArray);
@@ -645,6 +645,7 @@ public static byte[] DevicesTask(HttpListenerContext ctx, Dictionary<string, str
645645
origin
646646
);
647647
}
648+
648649
public static byte[] DevicesTask(string[] hosts, bool dns, bool wmi, bool ldap, SnmpProfiles.Profile[] snmpProfiles, string portScan, int retries, float interval, string origin) {
649650
if (task is not null) return Data.CODE_OTHER_TASK_IN_PROGRESS.Array;
650651
if (result is not null) return Data.CODE_OTHER_TASK_IN_PROGRESS.Array;
@@ -656,7 +657,7 @@ public static byte[] DevicesTask(string[] hosts, bool dns, bool wmi, bool ldap,
656657
const int WINDOW = 32;
657658
ConcurrentDictionary<string, ConcurrentDictionary<string, string[]>> dataset = new ConcurrentDictionary<string, ConcurrentDictionary<string, string[]>>();
658659

659-
task.status = TaskWrapper.TaskStatus.Running;
660+
task?.status = TaskWrapper.TaskStatus.Running;
660661

661662
List<string> queue = new List<string>(hosts);
662663
List<string> redo = new List<string>();

Protest/Tasks/Issues.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ public static async void WebSocketHandler(HttpListenerContext ctx) {
128128
return;
129129
}
130130

131-
IEnumerable<Issue> filtered = issues.Where(o => o.timestamp > lastTimestamp);
131+
IEnumerable<Issue> filtered = issues?.Where(o => o.timestamp > lastTimestamp);
132132

133133
if (filtered.Any()) {
134134
byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(filtered.Select(o => new {
@@ -232,11 +232,11 @@ public static void ScanDevice(Database.Entry device) {
232232
ipString = ip.value.Split(';').Select(o => o.Trim()).ToArray()[0];
233233
}
234234

235-
if (CheckCpuLifeline(device, ipString, out Issue ? cpuIssue)) {
235+
if (CheckCpuLifeline(device, ipString, out Issue ? cpuIssue) && cpuIssue.HasValue) {
236236
issues.Add(cpuIssue.Value);
237237
}
238238

239-
if (CheckMemoryLifeline(device, ipString, out Issue? memoryIssue)) {
239+
if (CheckMemoryLifeline(device, ipString, out Issue? memoryIssue) && memoryIssue.HasValue) {
240240
issues.Add(memoryIssue.Value);
241241
}
242242

@@ -246,11 +246,11 @@ public static void ScanDevice(Database.Entry device) {
246246
}
247247
}
248248

249-
if (CheckDiskIOLifeline(device, ipString, out Issue? diskIoIssue)) {
249+
if (CheckDiskIOLifeline(device, ipString, out Issue? diskIoIssue) && diskIoIssue.HasValue) {
250250
issues.Add(diskIoIssue.Value);
251251
}
252252

253-
if (CheckNicSpeed(device, ipString, out Issue ? nicSpeedIssue)) {
253+
if (CheckNicSpeed(device, ipString, out Issue? nicSpeedIssue) && nicSpeedIssue.HasValue) {
254254
issues.Add(nicSpeedIssue.Value);
255255
}
256256

@@ -598,7 +598,7 @@ public static bool CheckDiskSpaceLifeline(Database.Entry device, string host, ou
598598
List<(long timestamp, double percentUsed)> usageData = diskEntry.Value;
599599

600600
if (usageData.Count == 0) { continue; }
601-
if (CheckDiskSpace(device.filename, host, 100 - usageData[^1].percentUsed, diskEntry.Key, out Issue? diskIssue)) {
601+
if (CheckDiskSpace(device.filename, host, 100 - usageData[^1].percentUsed, diskEntry.Key, out Issue? diskIssue) && diskIssue.HasValue) {
602602
issuesList.Add(diskIssue.Value);
603603
continue;
604604
}
@@ -776,7 +776,8 @@ public static bool CheckDomainUser(Database.Entry user, out Issue[] issues, Seve
776776
isUser = true,
777777
});
778778
}
779-
else {
779+
780+
if (result is not null) {
780781
bool isDisabled = false;
781782
if (severityThreshold <= SeverityLevel.info
782783
&& result.Properties["userAccountControl"].Count > 0

Protest/Tasks/Lifeline.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ private static void LifelineLoop() {
6161
long lastVersion = 0;
6262

6363
while (true) {
64-
task.status = TaskWrapper.TaskStatus.Running;
64+
task?.status = TaskWrapper.TaskStatus.Running;
6565

6666
long startTimeStamp = DateTime.UtcNow.Ticks;
6767

Protest/Tasks/Watchdog.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ private static void WatchLoop() {
134134
int nextSleep = FIVE_MINUTE_IN_MILLI;
135135
//align time to the next 5-min interval
136136
long gap = (FIVE_MINUTE_IN_TICKS - DateTime.UtcNow.Ticks % FIVE_MINUTE_IN_TICKS) / 10_000;
137-
task.status = TaskWrapper.TaskStatus.Idle;
137+
task?.status = TaskWrapper.TaskStatus.Idle;
138138
Thread.Sleep((int)gap);
139139

140140
while (true) {

Protest/Tools/Cert.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public static byte[] Create(HttpListenerContext ctx, string origin) {
8080
validBefore = DateTime.Now.AddYears(5);
8181
}
8282

83-
string[] subjectAlternativeNames = altNamesString.Split(',').Select(o=>o.Trim()).ToArray();
83+
string[] subjectAlternativeNames = altNamesString?.Split(',').Select(o=>o.Trim()).ToArray() ?? Array.Empty<String>();
8484

8585
X509KeyUsageFlags keyUsageFlags = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment;
8686

0 commit comments

Comments
 (0)