Skip to content

Commit 5f87288

Browse files
authored
[DnsServer] Various fixes (#1426)
1 parent 11319d8 commit 5f87288

File tree

4 files changed

+42
-38
lines changed

4 files changed

+42
-38
lines changed

devices/DnsServer/DnsAnswer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public byte[] GetBytes()
7171
// Create proper compression pointer (0xC000 | offset)
7272
ushort compressionPointer = (ushort)(DnsCompressionPointerFlag | NameOffset);
7373

74-
Logger.GlobalLogger.LogDebug("DNS Answer - Creating pointer 0x{0:X4} (flag=0x{1:X2}, offset=0x{2:X4})", compressionPointer, DnsCompressionPointerFlag, NameOffset);
74+
Logger.GlobalLogger?.LogDebug("DNS Answer - Creating pointer 0x{0:X4} (flag=0x{1:X2}, offset=0x{2:X4})", compressionPointer, DnsCompressionPointerFlag, NameOffset);
7575

7676
// Write each field in network byte order (big-endian)
7777
ByteHelper.WriteUInt16NetworkOrder(compressionPointer, result, position);

devices/DnsServer/DnsQuestion.cs

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,13 @@ internal class DnsQuestion
5353
/// </summary>
5454
public ushort QuestionOffset { get; }
5555

56-
/// <summary>
57-
/// Creates a new instance of the <see cref="DnsQuestion"/> class by parsing the given byte array starting at the specified offset.
58-
/// </summary>
59-
/// <param name="data"></param>
60-
/// <param name="offset"></param>
61-
public DnsQuestion(byte[] data, int offset)
56+
/// <summary>
57+
/// Creates a new instance of the <see cref="DnsQuestion"/> class by parsing the given byte array starting at the specified offset.
58+
/// </summary>
59+
/// <param name="data">The byte array containing the DNS question data.</param>
60+
/// <param name="offset">The offset in the byte array where the DNS question starts.</param>
61+
/// <exception cref="ArgumentException">Thrown when the data is invalid or cannot be parsed.</exception>
62+
public DnsQuestion(byte[] data, int offset)
6263
{
6364
int terminatorIndex = -1;
6465

@@ -110,17 +111,17 @@ public bool TryParseQuestion(Hashtable dnsEntries, ref DnsAnswer dnsAnswer)
110111

111112
if (string.IsNullOrEmpty(name))
112113
{
113-
Logger.GlobalLogger.LogWarning("Failed to parse DNS question name.");
114+
Logger.GlobalLogger?.LogWarning("Failed to parse DNS question name.");
114115

115116
return false;
116117
}
117118

118-
Logger.GlobalLogger.LogDebug("Parsed DNS question: Name={0}, Type={1}, Class={2} (name offset={3}, length={4})", name, Type, Class, QuestionOffset, nameLength);
119+
Logger.GlobalLogger?.LogDebug("Parsed DNS question: Name={0}, Type={1}, Class={2} (name offset={3}, length={4})", name, Type, Class, QuestionOffset, nameLength);
119120

120121
// For captive portal, we'll handle A record types
121122
if (Type != QuestionTypeA)
122123
{
123-
Logger.GlobalLogger.LogWarning("Unsupported DNS question type: {0}. Only A (IPv4 address) records are supported.", Type);
124+
Logger.GlobalLogger?.LogWarning("Unsupported DNS question type: {0}. Only A (IPv4 address) records are supported.", Type);
124125

125126
return false;
126127
}
@@ -141,11 +142,11 @@ public bool TryParseQuestion(Hashtable dnsEntries, ref DnsAnswer dnsAnswer)
141142
TTL = 300
142143
};
143144

144-
Logger.GlobalLogger.LogDebug("Generated DNS answer for name: {0}, Type: {1}, Address: {2}, pointer offset: 0x{3:X4}", name, Type, ipAddress, QuestionOffset);
145+
Logger.GlobalLogger?.LogDebug("Generated DNS answer for name: {0}, Type: {1}, Address: {2}, pointer offset: 0x{3:X4}", name, Type, ipAddress, QuestionOffset);
145146
}
146147
else
147148
{
148-
Logger.GlobalLogger.LogWarning("No DNS entry found for name: {0}", name);
149+
Logger.GlobalLogger?.LogWarning("No DNS entry found for name: {0}", name);
149150

150151
return false;
151152
}
@@ -184,7 +185,7 @@ private string ParseName(ref ushort nameLength)
184185
if ((labelLength & _DnsCompressionPointerFlag) == _DnsCompressionPointerFlag)
185186
{
186187
// This is a pointer (first two bits are set)
187-
Logger.GlobalLogger.LogWarning("DNS name compression (pointers) not supported in this simplified implementation");
188+
Logger.GlobalLogger?.LogWarning("DNS name compression (pointers) not supported in this simplified implementation");
188189

189190
nameLength = 0;
190191

@@ -194,7 +195,7 @@ private string ParseName(ref ushort nameLength)
194195
// Make sure we have enough bytes for this label
195196
if (position + labelLength > Name.Length)
196197
{
197-
Logger.GlobalLogger.LogWarning("DNS label exceeds packet boundary");
198+
Logger.GlobalLogger?.LogWarning("DNS label exceeds packet boundary");
198199

199200
nameLength = 0;
200201

@@ -218,7 +219,7 @@ private string ParseName(ref ushort nameLength)
218219
}
219220
catch (Exception ex)
220221
{
221-
Logger.GlobalLogger.LogError(ex, "Exception parsing DNS name");
222+
Logger.GlobalLogger?.LogError(ex, "Exception parsing DNS name");
222223

223224
nameLength = 0;
224225

@@ -231,6 +232,7 @@ private string ParseName(ref ushort nameLength)
231232
/// Tries to find a matching DNS entry for the given name.
232233
/// </summary>
233234
/// <param name="name">The domain name to look up.</param>
235+
/// <param name="dnsEntries">The hashtable with the DNS entries.</param>
234236
/// <param name="ipAddress">The IP address if found.</param>
235237
/// <returns><see langword="true"/> if a match was found; otherwise, <see langword="false"/>.</returns>
236238
private bool TryFindDnsEntry(
@@ -261,7 +263,7 @@ private bool TryFindDnsEntry(
261263
{
262264
ipAddress = (IPAddress)dnsEntries[key];
263265

264-
Logger.GlobalLogger.LogDebug("Wildcard match: '{0}' matches pattern '{1}'", name, key);
266+
Logger.GlobalLogger?.LogDebug("Wildcard match: '{0}' matches pattern '{1}'", name, key);
265267

266268
return true;
267269
}
@@ -271,9 +273,9 @@ private bool TryFindDnsEntry(
271273
return false;
272274
}
273275

276+
/// <summary>
274277
/// Returns the byte array representation of this DNS question, suitable for network transmission.
275278
/// </summary>
276-
/// <param name="none"></param>
277279
/// <returns>
278280
/// A <see cref="byte"/> array containing the DNS question in wire format.
279281
/// </returns>

devices/DnsServer/DnsReply.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,24 +59,24 @@ public bool ParseRequest()
5959
// parse DNS header
6060
Header = new DnsHeader(_requestData);
6161

62-
Logger.GlobalLogger.LogDebug("DNS Header - ID: {0}, Flags: {1}, QDCount: {2}", Header.Id, Header.Flags, Header.QDCount);
62+
Logger.GlobalLogger?.LogDebug("DNS Header - ID: {0}, Flags: {1}, QDCount: {2}", Header.Id, Header.Flags, Header.QDCount);
6363

6464
// only process standard queries
6565
if ((Header.Flags & DnsHeader.DnsFlagOpCodeMask) != 0)
6666
{
67-
Logger.GlobalLogger.LogWarning("Unsupported DNS operation code.");
67+
Logger.GlobalLogger?.LogWarning("Unsupported DNS operation code.");
6868
return false;
6969
}
7070

7171
// only process requests with a single question
7272
if (Header.QDCount == 0)
7373
{
74-
Logger.GlobalLogger.LogWarning("DNS request contains no questions.");
74+
Logger.GlobalLogger?.LogWarning("DNS request contains no questions.");
7575
return false;
7676
}
7777
else if (Header.QDCount > 1)
7878
{
79-
Logger.GlobalLogger.LogWarning("DNS request contains multiple questions. Only single question requests are supported.");
79+
Logger.GlobalLogger?.LogWarning("DNS request contains multiple questions. Only single question requests are supported.");
8080
return false;
8181
}
8282

@@ -91,7 +91,7 @@ public bool ParseRequest()
9191

9292
if (!DnsQuestions[0].TryParseQuestion(_dnsEntries, ref Answers[0]))
9393
{
94-
Logger.GlobalLogger.LogWarning("Failed to parse DNS question.");
94+
Logger.GlobalLogger?.LogWarning("Failed to parse DNS question.");
9595

9696
return false;
9797
}
@@ -116,24 +116,24 @@ public byte[] GetBytes()
116116
// copy header with modified flags and answer count
117117
Array.Copy(Header.GetBytes(), 0, replyData, 0, DnsHeader.Length);
118118

119-
Logger.GlobalLogger.LogDebug("DNS Reply - Header: ID={0}, Flags=0x{1:X4}, QD={2}, AN={3}", Header.Id, Header.Flags, Header.QDCount, Header.ANCount);
119+
Logger.GlobalLogger?.LogDebug("DNS Reply - Header: ID={0}, Flags=0x{1:X4}, QD={2}, AN={3}", Header.Id, Header.Flags, Header.QDCount, Header.ANCount);
120120

121121
int position = DnsHeader.Length;
122122

123123
// copy questions section from the original request
124124
Array.Copy(DnsQuestions[0].GetBytes(), 0, replyData, position, DnsQuestions[0].Length);
125125

126-
Logger.GlobalLogger.LogDebug("DNS Reply - Added questions section, {0} bytes", DnsQuestions.Length);
126+
Logger.GlobalLogger?.LogDebug("DNS Reply - Added questions section, {0} bytes", DnsQuestions.Length);
127127

128128
// move position forward
129129
position += DnsQuestions[0].Length;
130130

131131
// copy answer
132132
Array.Copy(Answers[0].GetBytes(), 0, replyData, position, DnsAnswer.Length);
133133

134-
Logger.GlobalLogger.LogDebug("DNS Reply - Added answer: Name ptr=0x{0:X4}, Type={1}, IP={2}", Answers[0].NameOffset, Answers[0].Type, Answers[0].Address);
134+
Logger.GlobalLogger?.LogDebug("DNS Reply - Added answer: Name ptr=0x{0:X4}, Type={1}, IP={2}", Answers[0].NameOffset, Answers[0].Type, Answers[0].Address);
135135

136-
Logger.GlobalLogger.LogDebug("DNS Reply total size: {0} bytes", replyData.Length);
136+
Logger.GlobalLogger?.LogDebug("DNS Reply total size: {0} bytes", replyData.Length);
137137

138138
return replyData;
139139
}

devices/DnsServer/DnsServer.cs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public bool Start()
110110
// check if we have entries
111111
if (_dnsEntries.Count == 0)
112112
{
113-
Logger.GlobalLogger.LogWarning("No DNS entries defined. The server will not respond to any queries.");
113+
Logger.GlobalLogger?.LogWarning("No DNS entries defined. The server will not respond to any queries.");
114114

115115
throw new InvalidOperationException();
116116
}
@@ -134,11 +134,11 @@ public bool Start()
134134
}
135135
catch (SocketException ex)
136136
{
137-
Logger.GlobalLogger.LogError(ex, "Socket exception occurred. Code: {0} Message: {1}", ex.ErrorCode, ex.Message);
137+
Logger.GlobalLogger?.LogError(ex, "Socket exception occurred. Code: {0} Message: {1}", ex.ErrorCode, ex.Message);
138138
}
139139
catch (Exception ex)
140140
{
141-
Logger.GlobalLogger.LogError(ex, "Exception occurred. Message: {0}", ex.Message);
141+
Logger.GlobalLogger?.LogError(ex, "Exception occurred. Message: {0}", ex.Message);
142142
}
143143

144144
// reached here, something went wrong
@@ -170,7 +170,7 @@ public void Stop()
170170
}
171171
catch (Exception ex)
172172
{
173-
Logger.GlobalLogger.LogError(ex, "Exception occurred while stopping the server. Message: {0}", ex.Message);
173+
Logger.GlobalLogger?.LogError(ex, "Exception occurred while stopping the server. Message: {0}", ex.Message);
174174
}
175175
}
176176

@@ -190,7 +190,7 @@ public void Stop()
190190

191191
private void DnsWorkerThread()
192192
{
193-
Logger.GlobalLogger.LogInformation("DNS server started.");
193+
Logger.GlobalLogger?.LogInformation("DNS server started.");
194194

195195
byte[] buffer = new byte[MaxDnsUdpPacketSize];
196196

@@ -223,37 +223,37 @@ private void DnsWorkerThread()
223223
}
224224
catch (SocketException ex)
225225
{
226-
Logger.GlobalLogger.LogError(ex, "Socket exception in DNS worker thread. Code: {0} Message: {1}", ex.ErrorCode, ex.Message);
226+
Logger.GlobalLogger?.LogError(ex, "Socket exception in DNS worker thread. Code: {0} Message: {1}", ex.ErrorCode, ex.Message);
227227

228228
break;
229229
}
230230
catch (Exception ex)
231231
{
232-
Logger.GlobalLogger.LogError(ex, "Exception in DNS worker thread. Message: {0}", ex.Message);
232+
Logger.GlobalLogger?.LogError(ex, "Exception in DNS worker thread. Message: {0}", ex.Message);
233233
}
234234
}
235235

236-
Logger.GlobalLogger.LogInformation("DNS server stopped.");
236+
Logger.GlobalLogger?.LogInformation("DNS server stopped.");
237237
}
238238

239239
private bool ProcessDnsRequest(byte[] requestData, ref DnsReply dnsReply)
240240
{
241-
Logger.GlobalLogger.LogDebug("Received DNS request of length {0} bytes.", requestData.Length);
241+
Logger.GlobalLogger?.LogDebug("Received DNS request of length {0} bytes.", requestData.Length);
242242

243243
// Create the DNS reply with the request data and DNS entries
244244
dnsReply = new DnsReply(requestData, DnsEntries);
245245

246246
// Parse the request and generate answers
247247
if (!dnsReply.ParseRequest())
248248
{
249-
Logger.GlobalLogger.LogError("Failed to parse DNS request.");
249+
Logger.GlobalLogger?.LogError("Failed to parse DNS request.");
250250

251251
return false;
252252
}
253253

254254
if (dnsReply.Answers.Length == 0)
255255
{
256-
Logger.GlobalLogger.LogWarning("No DNS answers generated.");
256+
Logger.GlobalLogger?.LogWarning("No DNS answers generated.");
257257

258258
return false;
259259
}
@@ -265,6 +265,7 @@ private bool ProcessDnsRequest(byte[] requestData, ref DnsReply dnsReply)
265265

266266
#region Dispose pattern
267267

268+
/// <inheritdoc/>
268269
protected virtual void Dispose(bool disposing)
269270
{
270271
if (!_disposed)
@@ -278,6 +279,7 @@ protected virtual void Dispose(bool disposing)
278279
}
279280
}
280281

282+
/// <inheritdoc/>
281283
public void Dispose()
282284
{
283285
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
@@ -295,7 +297,7 @@ private void ParseDnsEntries(DnsEntry[] dnsEntries)
295297
{
296298
_dnsEntries.Add(entry.Name, entry.Address);
297299

298-
Logger.GlobalLogger.LogDebug("Added DNS entry: {0} -> {1}", entry.Name, entry.Address);
300+
Logger.GlobalLogger?.LogDebug("Added DNS entry: {0} -> {1}", entry.Name, entry.Address);
299301
}
300302
}
301303
}

0 commit comments

Comments
 (0)