Skip to content

Commit

Permalink
Remove duplicate host lines from mtr results.
Browse files Browse the repository at this point in the history
References traviscross/mtr#499
Closes #80
  • Loading branch information
Daniel15 committed Jan 3, 2024
1 parent f126f30 commit 9669f13
Showing 1 changed file with 38 additions and 11 deletions.
49 changes: 38 additions & 11 deletions src/DnsTools.Worker/Tools/Mtr.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.JavaScript;
using System.Threading.Tasks;
using DnsTools.Worker.Utils;
using Grpc.Core;
Expand All @@ -12,7 +13,9 @@ namespace DnsTools.Worker.Tools
public class Mtr : BaseCliTool<TracerouteRequest, MtrResponse>
{
private const float US_PER_MS = 1000;


private readonly Dictionary<uint, HashSet<string>> _hostIPsAlreadySent = new();

protected override string GetCommand(TracerouteRequest request) => "mtr";

protected override async Task<IReadOnlyList<string>> GetArguments(
Expand All @@ -37,6 +40,21 @@ await writer.WriteAsync(new MtrResponse
{
// Reference: https://github.com/traviscross/mtr/blob/master/FORMATS
var pieces = data.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);

if (pieces[0] == "h")
{
var pos = uint.Parse(pieces[1]);
var ip = pieces[2];
return CheckIfHostIsDuplicate(pos, ip) ? null : new MtrResponse
{
Pos = uint.Parse(pieces[1]),
Host = new MtrHostLine
{
Ip = pieces[2],
}
};
}

return pieces[0] switch
{
"d" => new MtrResponse
Expand All @@ -47,16 +65,7 @@ await writer.WriteAsync(new MtrResponse
Hostname = pieces[2],
}
},

"h" => new MtrResponse
{
Pos = uint.Parse(pieces[1]),
Host = new MtrHostLine
{
Ip = pieces[2],
}
},


"p" => new MtrResponse
{
Pos = uint.Parse(pieces[1]),
Expand Down Expand Up @@ -85,5 +94,23 @@ await writer.WriteAsync(new MtrResponse
}
};
}

/// <summary>
/// Checks if this host line has already been returned during this session, to avoid returning
/// duplicates to the client-side.
/// </summary>
/// <see>https://github.com/traviscross/mtr/issues/499</see>
/// <returns><c>true</c> if this host has already been returned, otherwise <c>false</c></returns>
private bool CheckIfHostIsDuplicate(uint pos, string ip)
{
var ipsAlreadySentForPos = _hostIPsAlreadySent.GetValueOrDefault(pos);
if (ipsAlreadySentForPos == null)
{
ipsAlreadySentForPos = new HashSet<string>();
_hostIPsAlreadySent.Add(pos, ipsAlreadySentForPos);
}

return !ipsAlreadySentForPos.Add(ip);
}
}
}

0 comments on commit 9669f13

Please sign in to comment.