Repository navigation
Expand file tree
/
Copy pathTracerouteWindows.cpp
More file actions
534 lines (478 loc) · 22.4 KB
/
Copy pathTracerouteWindows.cpp
File metadata and controls
534 lines (478 loc) · 22.4 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// Native Windows traceroute implementation.
// ICMP probes use IP Helper and require no elevation. UDP probes use Winsock
// raw ICMP capture and therefore require an elevated process on Windows.
#include "Traceroute.h"
#include <iphlpapi.h>
#include <icmpapi.h>
#include <mstcpip.h>
#ifndef SIO_UDP_CONNRESET
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12)
#endif
#include <algorithm>
#include <future>
#include <iostream>
#include <mutex>
#include "NameResolver.h"
namespace TracerouteWindowsInternal {
constexpr size_t ICMP_HEADER_SIZE = 8;
constexpr size_t IPV4_HEADER_SIZE = 20;
constexpr size_t IPV6_HEADER_SIZE = 40;
constexpr uint8_t ICMP_TIME_EXCEEDED = 11;
constexpr uint8_t ICMP_DEST_UNREACHABLE = 3;
constexpr uint8_t ICMPV6_TIME_EXCEEDED = 3;
constexpr uint8_t ICMPV6_DEST_UNREACHABLE = 1;
#pragma pack(push, 1)
struct Ipv4Header {
uint8_t mVersionIhl;
uint8_t mTos;
uint16_t mTotalLength;
uint16_t mId;
uint16_t mFragment;
uint8_t mTtl;
uint8_t mProtocol;
uint16_t mChecksum;
uint32_t mSource;
uint32_t mDestination;
};
struct Ipv6Header {
uint32_t mVersionFlow;
uint16_t mPayloadLength;
uint8_t mNextHeader;
uint8_t mHopLimit;
uint8_t mSource[16];
uint8_t mDestination[16];
};
struct IcmpHeader {
uint8_t mType;
uint8_t mCode;
uint16_t mChecksum;
uint32_t mRest;
};
struct UdpHeader {
uint16_t mSourcePort;
uint16_t mDestinationPort;
uint16_t mLength;
uint16_t mChecksum;
};
#pragma pack(pop)
struct NativeProbeResult {
TracerouteProbeResult mProbe;
uint8_t mIcmpType = 0;
uint8_t mIcmpCode = 0;
bool mIsDestination = false;
TracerouteError mError = TracerouteError::SUCCESS;
};
bool ensureWinsock() {
static std::once_flag lOnce;
static bool lReady = false;
std::call_once(lOnce, [] {
WSADATA lData{};
lReady = WSAStartup(MAKEWORD(2, 2), &lData) == 0;
});
return lReady;
}
std::string addressToString(const sockaddr_storage& aAddress) {
char lBuffer[INET6_ADDRSTRLEN]{};
if (aAddress.ss_family == AF_INET) {
const auto* lpAddress = reinterpret_cast<const sockaddr_in*>(&aAddress);
return inet_ntop(AF_INET, &lpAddress->sin_addr,
lBuffer, sizeof(lBuffer)) ? lBuffer : "";
}
if (aAddress.ss_family == AF_INET6) {
const auto* lpAddress = reinterpret_cast<const sockaddr_in6*>(&aAddress);
return inet_ntop(AF_INET6, &lpAddress->sin6_addr,
lBuffer, sizeof(lBuffer)) ? lBuffer : "";
}
return "";
}
std::string ipv4ToString(IPAddr aAddress) {
IN_ADDR lAddress{};
lAddress.S_un.S_addr = aAddress;
char lBuffer[INET_ADDRSTRLEN]{};
return InetNtopA(AF_INET, &lAddress, lBuffer, sizeof(lBuffer)) ? lBuffer : "";
}
std::string ipv6ToString(const IPV6_ADDRESS_EX& aAddress) {
IN6_ADDR lAddress{};
std::memcpy(&lAddress, aAddress.sin6_addr, sizeof(lAddress));
char lBuffer[INET6_ADDRSTRLEN]{};
return InetNtopA(AF_INET6, &lAddress, lBuffer, sizeof(lBuffer)) ? lBuffer : "";
}
NativeProbeResult probeIcmp(const sockaddr_storage& aDestination, bool aIsV6,
int32_t aTtl, const TracerouteConfig& aConfig) {
NativeProbeResult lResult;
HANDLE lHandle = aIsV6 ? Icmp6CreateFile() : IcmpCreateFile();
if (lHandle == INVALID_HANDLE_VALUE) {
lResult.mError = TracerouteError::SOCKET_CREATE_ERROR;
return lResult;
}
const size_t lPayloadSize = aConfig.mPacketSize - ICMP_HEADER_SIZE;
std::vector<uint8_t> lPayload(lPayloadSize, 0x54);
IP_OPTION_INFORMATION lOptions{};
lOptions.Ttl = static_cast<UCHAR>(aTtl);
if (!aIsV6) {
const auto* lpDestination = reinterpret_cast<const sockaddr_in*>(&aDestination);
std::vector<uint8_t> lReplyBuffer(sizeof(ICMP_ECHO_REPLY) + lPayload.size() + 8);
const DWORD lReplies = IcmpSendEcho(
lHandle, lpDestination->sin_addr.s_addr,
lPayload.empty() ? nullptr : lPayload.data(), static_cast<WORD>(lPayload.size()),
&lOptions, lReplyBuffer.data(), static_cast<DWORD>(lReplyBuffer.size()),
static_cast<DWORD>(aConfig.mTimeoutMs));
if (lReplies > 0) {
const auto* lpReply = reinterpret_cast<const ICMP_ECHO_REPLY*>(lReplyBuffer.data());
if (lpReply->Status == IP_SUCCESS || lpReply->Status == IP_TTL_EXPIRED_TRANSIT ||
(lpReply->Status >= IP_DEST_NET_UNREACHABLE && lpReply->Status <= IP_DEST_PORT_UNREACHABLE)) {
lResult.mProbe.mResponded = true;
lResult.mProbe.mRttMicroseconds = static_cast<int64_t>(lpReply->RoundTripTime) * 1000;
lResult.mProbe.mIpAddress = ipv4ToString(lpReply->Address);
lResult.mIsDestination = lpReply->Status == IP_SUCCESS;
lResult.mIcmpType = lResult.mIsDestination ? 0
: lpReply->Status == IP_TTL_EXPIRED_TRANSIT ? ICMP_TIME_EXCEEDED
: ICMP_DEST_UNREACHABLE;
}
}
} else {
sockaddr_in6 lSource{};
lSource.sin6_family = AF_INET6;
auto lDestination = *reinterpret_cast<const sockaddr_in6*>(&aDestination);
std::vector<uint8_t> lReplyBuffer(sizeof(ICMPV6_ECHO_REPLY) + lPayload.size() + 32);
const DWORD lReplies = Icmp6SendEcho2(
lHandle, nullptr, nullptr, nullptr, &lSource, &lDestination,
lPayload.empty() ? nullptr : lPayload.data(), static_cast<WORD>(lPayload.size()),
&lOptions, lReplyBuffer.data(), static_cast<DWORD>(lReplyBuffer.size()),
static_cast<DWORD>(aConfig.mTimeoutMs));
if (lReplies > 0) {
const auto* lpReply = reinterpret_cast<const ICMPV6_ECHO_REPLY*>(lReplyBuffer.data());
if (lpReply->Status == IP_SUCCESS || lpReply->Status == IP_TTL_EXPIRED_TRANSIT ||
lpReply->Status == IP_DEST_UNREACHABLE || lpReply->Status == IP_DEST_NO_ROUTE ||
lpReply->Status == IP_DEST_ADDR_UNREACHABLE) {
lResult.mProbe.mResponded = true;
lResult.mProbe.mRttMicroseconds = static_cast<int64_t>(lpReply->RoundTripTime) * 1000;
lResult.mProbe.mIpAddress = ipv6ToString(lpReply->Address);
lResult.mIsDestination = lpReply->Status == IP_SUCCESS;
lResult.mIcmpType = lResult.mIsDestination ? 129
: lpReply->Status == IP_TTL_EXPIRED_TRANSIT ? ICMPV6_TIME_EXCEEDED
: ICMPV6_DEST_UNREACHABLE;
}
}
}
IcmpCloseHandle(lHandle);
return lResult;
}
bool parseUdpResponse(const uint8_t* aData, size_t aLength, bool aIsV6,
uint16_t aExpectedPort, const sockaddr_storage& aDestination,
NativeProbeResult& rResult) {
size_t lOuterOffset = 0;
if (!aIsV6) {
if (aLength < IPV4_HEADER_SIZE + sizeof(IcmpHeader)) return false;
const auto* lpOuterIp = reinterpret_cast<const Ipv4Header*>(aData);
lOuterOffset = static_cast<size_t>(lpOuterIp->mVersionIhl & 0x0F) * 4;
if (lOuterOffset < IPV4_HEADER_SIZE || aLength < lOuterOffset + sizeof(IcmpHeader)) return false;
} else if (aLength >= IPV6_HEADER_SIZE && (aData[0] >> 4) == 6) {
lOuterOffset = IPV6_HEADER_SIZE;
}
const auto* lpIcmp = reinterpret_cast<const IcmpHeader*>(aData + lOuterOffset);
const bool lRelevant = !aIsV6
? (lpIcmp->mType == ICMP_TIME_EXCEEDED || lpIcmp->mType == ICMP_DEST_UNREACHABLE)
: (lpIcmp->mType == ICMPV6_TIME_EXCEEDED || lpIcmp->mType == ICMPV6_DEST_UNREACHABLE);
if (!lRelevant) return false;
const size_t lEmbeddedOffset = lOuterOffset + sizeof(IcmpHeader);
size_t lTransportOffset = 0;
if (!aIsV6) {
if (aLength < lEmbeddedOffset + IPV4_HEADER_SIZE + sizeof(UdpHeader)) return false;
const auto* lpIp = reinterpret_cast<const Ipv4Header*>(aData + lEmbeddedOffset);
const size_t lIpLength = static_cast<size_t>(lpIp->mVersionIhl & 0x0F) * 4;
if (lIpLength < IPV4_HEADER_SIZE || aLength < lEmbeddedOffset + lIpLength + sizeof(UdpHeader)) {
return false;
}
const auto* lpDestination = reinterpret_cast<const sockaddr_in*>(&aDestination);
if (lpIp->mDestination != lpDestination->sin_addr.s_addr) return false;
lTransportOffset = lEmbeddedOffset + lIpLength;
} else {
if (aLength < lEmbeddedOffset + IPV6_HEADER_SIZE + sizeof(UdpHeader)) return false;
const auto* lpIp = reinterpret_cast<const Ipv6Header*>(aData + lEmbeddedOffset);
const auto* lpDestination = reinterpret_cast<const sockaddr_in6*>(&aDestination);
if ((ntohl(lpIp->mVersionFlow) >> 28) != 6 ||
std::memcmp(lpIp->mDestination, &lpDestination->sin6_addr, 16) != 0) return false;
lTransportOffset = lEmbeddedOffset + IPV6_HEADER_SIZE;
}
const auto* lpUdp = reinterpret_cast<const UdpHeader*>(aData + lTransportOffset);
if (ntohs(lpUdp->mDestinationPort) != aExpectedPort) return false;
rResult.mIcmpType = lpIcmp->mType;
rResult.mIcmpCode = lpIcmp->mCode;
rResult.mIsDestination = !aIsV6
? lpIcmp->mType == ICMP_DEST_UNREACHABLE && lpIcmp->mCode == 3
: lpIcmp->mType == ICMPV6_DEST_UNREACHABLE && lpIcmp->mCode == 4;
return true;
}
NativeProbeResult probeUdp(const sockaddr_storage& aDestination, socklen_t aDestinationLength,
bool aIsV6, int32_t aTtl, uint16_t aDestinationPort,
const TracerouteConfig& aConfig) {
NativeProbeResult lResult;
const int lFamily = aIsV6 ? AF_INET6 : AF_INET;
SOCKET lReceiveSocket = socket(lFamily, SOCK_RAW, aIsV6 ? IPPROTO_ICMPV6 : IPPROTO_ICMP);
if (lReceiveSocket == INVALID_SOCKET) {
lResult.mError = WSAGetLastError() == WSAEACCES
? TracerouteError::PERMISSION_DENIED : TracerouteError::SOCKET_CREATE_ERROR;
return lResult;
}
SOCKET lSendSocket = socket(lFamily, SOCK_DGRAM, IPPROTO_UDP);
if (lSendSocket == INVALID_SOCKET) {
closesocket(lReceiveSocket);
lResult.mError = TracerouteError::SOCKET_CREATE_ERROR;
return lResult;
}
if (!aIsV6) {
sockaddr_in lLocal{};
lLocal.sin_family = AF_INET;
lLocal.sin_addr.s_addr = INADDR_ANY;
static_cast<void>(bind(lReceiveSocket, reinterpret_cast<sockaddr*>(&lLocal),
sizeof(lLocal)));
static_cast<void>(setsockopt(lSendSocket, IPPROTO_IP, IP_TTL,
reinterpret_cast<const char*>(&aTtl), sizeof(aTtl)));
} else {
sockaddr_in6 lLocal{};
lLocal.sin6_family = AF_INET6;
lLocal.sin6_addr = in6addr_any;
static_cast<void>(bind(lReceiveSocket, reinterpret_cast<sockaddr*>(&lLocal),
sizeof(lLocal)));
static_cast<void>(setsockopt(lSendSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
reinterpret_cast<const char*>(&aTtl), sizeof(aTtl)));
}
sockaddr_storage lDestination = aDestination;
if (aIsV6) reinterpret_cast<sockaddr_in6*>(&lDestination)->sin6_port = htons(aDestinationPort);
else reinterpret_cast<sockaddr_in*>(&lDestination)->sin_port = htons(aDestinationPort);
// A connected UDP socket lets Winsock report the destination's ICMP port
// unreachable as WSAECONNRESET, independently of raw-packet formatting.
BOOL lReportUdpReset = TRUE;
DWORD lBytesReturned = 0;
static_cast<void>(WSAIoctl(lSendSocket, SIO_UDP_CONNRESET,
&lReportUdpReset, sizeof(lReportUdpReset), nullptr, 0,
&lBytesReturned, nullptr, nullptr));
if (connect(lSendSocket, reinterpret_cast<const sockaddr*>(&lDestination),
aDestinationLength) == SOCKET_ERROR) {
closesocket(lSendSocket);
closesocket(lReceiveSocket);
lResult.mError = TracerouteError::SEND_ERROR;
return lResult;
}
std::vector<uint8_t> lPayload(aConfig.mPacketSize - sizeof(UdpHeader), 0x55);
const auto lStart = std::chrono::steady_clock::now();
const int lSent = send(lSendSocket, reinterpret_cast<const char*>(lPayload.data()),
static_cast<int>(lPayload.size()), 0);
if (lSent == SOCKET_ERROR) {
closesocket(lSendSocket);
closesocket(lReceiveSocket);
lResult.mError = TracerouteError::SEND_ERROR;
return lResult;
}
const auto lDeadline = lStart + std::chrono::milliseconds(aConfig.mTimeoutMs);
while (std::chrono::steady_clock::now() < lDeadline) {
const auto lRemaining = std::chrono::duration_cast<std::chrono::milliseconds>(
lDeadline - std::chrono::steady_clock::now()).count();
timeval lTimeout{};
lTimeout.tv_sec = static_cast<long>(lRemaining / 1000);
lTimeout.tv_usec = static_cast<long>((lRemaining % 1000) * 1000);
fd_set lReadSet;
FD_ZERO(&lReadSet);
FD_SET(lReceiveSocket, &lReadSet);
FD_SET(lSendSocket, &lReadSet);
if (select(0, &lReadSet, nullptr, nullptr, &lTimeout) <= 0) break;
if (FD_ISSET(lSendSocket, &lReadSet)) {
uint8_t lDiscard[1]{};
const int lReceived = recv(lSendSocket, reinterpret_cast<char*>(lDiscard),
sizeof(lDiscard), 0);
if (lReceived == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET) {
lResult.mProbe.mResponded = true;
lResult.mProbe.mRttMicroseconds =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - lStart).count();
lResult.mProbe.mIpAddress = addressToString(aDestination);
lResult.mIcmpType = aIsV6 ? ICMPV6_DEST_UNREACHABLE : ICMP_DEST_UNREACHABLE;
lResult.mIcmpCode = aIsV6 ? 4 : 3;
lResult.mIsDestination = true;
break;
}
}
if (!FD_ISSET(lReceiveSocket, &lReadSet)) continue;
std::vector<uint8_t> lBuffer(2048);
sockaddr_storage lFrom{};
int lFromLength = sizeof(lFrom);
const int lReceived = recvfrom(lReceiveSocket, reinterpret_cast<char*>(lBuffer.data()),
static_cast<int>(lBuffer.size()), 0,
reinterpret_cast<sockaddr*>(&lFrom), &lFromLength);
if (lReceived <= 0) continue;
if (parseUdpResponse(lBuffer.data(), static_cast<size_t>(lReceived), aIsV6,
aDestinationPort, aDestination, lResult)) {
lResult.mProbe.mResponded = true;
lResult.mProbe.mRttMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - lStart).count();
lResult.mProbe.mIpAddress = addressToString(lFrom);
break;
}
}
closesocket(lSendSocket);
closesocket(lReceiveSocket);
return lResult;
}
void computeHopStatistics(TracerouteHop& rHop) {
int64_t lSum = 0;
int64_t lMinimum = INT64_MAX;
int64_t lMaximum = INT64_MIN;
int32_t lCount = 0;
for (const auto& lProbe : rHop.mProbes) {
if (!lProbe.mResponded) continue;
lSum += lProbe.mRttMicroseconds;
lMinimum = (std::min)(lMinimum, lProbe.mRttMicroseconds);
lMaximum = (std::max)(lMaximum, lProbe.mRttMicroseconds);
lCount++;
if (rHop.mIpAddress.empty()) rHop.mIpAddress = lProbe.mIpAddress;
}
if (lCount > 0) {
rHop.mResponded = true;
rHop.mAvgRttMicroseconds = lSum / lCount;
rHop.mMinRttMicroseconds = lMinimum;
rHop.mMaxRttMicroseconds = lMaximum;
}
}
} // namespace TracerouteWindowsInternal
Traceroute::Traceroute() = default;
Traceroute::~Traceroute() = default;
bool Traceroute::canTrace() {
if (!TracerouteWindowsInternal::ensureWinsock()) return false;
HANDLE lHandle = IcmpCreateFile();
if (lHandle == INVALID_HANDLE_VALUE) return false;
IcmpCloseHandle(lHandle);
return true;
}
bool Traceroute::isIPv6Available() {
if (!TracerouteWindowsInternal::ensureWinsock()) return false;
HANDLE lHandle = Icmp6CreateFile();
if (lHandle == INVALID_HANDLE_VALUE) return false;
IcmpCloseHandle(lHandle);
return true;
}
void Traceroute::setOnHopResult(OnHopResultCallback aCallback) {
mOnHopResult = std::move(aCallback);
}
bool Traceroute::resolveDestination(const std::string& aHost, TracerouteIpVersion aIpVersion,
sockaddr_storage& rAddr, socklen_t& rAddrLen, bool& rIsV6) {
const auto lFamily = aIpVersion == TracerouteIpVersion::V4 ? NameResolverFamily::IPV4
: aIpVersion == TracerouteIpVersion::V6 ? NameResolverFamily::IPV6
: NameResolverFamily::ANY;
const auto lResolution = NameResolver::resolve(aHost, 0, lFamily);
if (!lResolution.succeeded() || lResolution.mEndpoints.empty()) return false;
const auto& lEndpoint = lResolution.mEndpoints.front();
rIsV6 = lEndpoint.mAddress.isIPv6();
return lEndpoint.toSockaddr(rAddr, rAddrLen);
}
std::string Traceroute::resolveHostname(const sockaddr_storage& aAddr, socklen_t aAddrLen) {
const auto lAddress = IpAddress::fromSockaddr(
reinterpret_cast<const sockaddr*>(&aAddr), aAddrLen);
if (!lAddress) return {};
const auto lResult = NameResolver::reverseLookup(*lAddress);
return lResult.succeeded() ? lResult.mHostname : std::string{};
}
std::string Traceroute::addrToString(const sockaddr_storage& aAddr) {
const auto lAddress = IpAddress::fromSockaddr(
reinterpret_cast<const sockaddr*>(&aAddr),
aAddr.ss_family == AF_INET
? static_cast<socklen_t>(sizeof(sockaddr_in))
: static_cast<socklen_t>(sizeof(sockaddr_in6)));
return lAddress ? lAddress->toString() : std::string{};
}
TracerouteResult Traceroute::trace(const std::string& aDestination, const TracerouteConfig& aConfig) {
TracerouteResult lResult;
lResult.mDestinationHostname = aDestination;
const uint32_t lHighestPort = static_cast<uint32_t>(aConfig.mDestPort) +
static_cast<uint32_t>((std::max)(aConfig.mMaxHops, 0)) *
static_cast<uint32_t>((std::max)(aConfig.mProbesPerHop, 0)) +
static_cast<uint32_t>((std::max)(aConfig.mProbesPerHop - 1, 0));
if (aConfig.mMaxHops <= 0 || aConfig.mMaxHops > 255 || aConfig.mTimeoutMs <= 0 ||
aConfig.mProbesPerHop <= 0 || aConfig.mPacketSize < TracerouteWindowsInternal::ICMP_HEADER_SIZE ||
(aConfig.mProtocol == TracerouteProtocol::UDP && lHighestPort > UINT16_MAX)) {
lResult.mError = TracerouteError::INVALID_CONFIG;
return lResult;
}
sockaddr_storage lDestination{};
socklen_t lDestinationLength = 0;
bool lIsV6 = false;
if (!resolveDestination(aDestination, aConfig.mIpVersion,
lDestination, lDestinationLength, lIsV6)) {
lResult.mError = TracerouteError::INVALID_ADDRESS;
return lResult;
}
lResult.mDestinationIp = addrToString(lDestination);
lResult.mIpVersion = lIsV6 ? TracerouteIpVersion::V6 : TracerouteIpVersion::V4;
if (aConfig.mVerbose) {
std::cout << "Tracing route to " << aDestination
<< " (" << lResult.mDestinationIp << ")"
<< ", IPv" << (lIsV6 ? '6' : '4')
<< ", " << aConfig.mMaxHops << " hops max"
<< ", " << aConfig.mPacketSize << " byte packets"
<< std::endl;
}
for (int32_t lTtl = 1; lTtl <= aConfig.mMaxHops; ++lTtl) {
TracerouteHop lHop;
lHop.mHopNumber = lTtl;
lHop.mProbes.resize(aConfig.mProbesPerHop);
auto lProbe = [&](int32_t aProbeIndex) {
if (aConfig.mProtocol == TracerouteProtocol::ICMP) {
return TracerouteWindowsInternal::probeIcmp(lDestination, lIsV6, lTtl, aConfig);
}
const uint16_t lPort = static_cast<uint16_t>(
aConfig.mDestPort + lTtl * aConfig.mProbesPerHop + aProbeIndex);
return TracerouteWindowsInternal::probeUdp(
lDestination, lDestinationLength, lIsV6, lTtl, lPort, aConfig);
};
std::vector<TracerouteWindowsInternal::NativeProbeResult> lNativeResults;
lNativeResults.reserve(aConfig.mProbesPerHop);
if (aConfig.mParallelProbes) {
std::vector<std::future<TracerouteWindowsInternal::NativeProbeResult>> lFutures;
for (int32_t lIndex = 0; lIndex < aConfig.mProbesPerHop; ++lIndex) {
lFutures.push_back(std::async(std::launch::async, lProbe, lIndex));
}
for (auto& lFuture : lFutures) lNativeResults.push_back(lFuture.get());
} else {
for (int32_t lIndex = 0; lIndex < aConfig.mProbesPerHop; ++lIndex) {
lNativeResults.push_back(lProbe(lIndex));
}
}
for (size_t lIndex = 0; lIndex < lNativeResults.size(); ++lIndex) {
const auto& lNative = lNativeResults[lIndex];
lHop.mProbes[lIndex] = lNative.mProbe;
if (lNative.mProbe.mResponded) {
lHop.mIcmpType = lNative.mIcmpType;
lHop.mIcmpCode = lNative.mIcmpCode;
lHop.mIsDestination = lHop.mIsDestination || lNative.mIsDestination;
}
if (lNative.mError != TracerouteError::SUCCESS) lHop.mError = lNative.mError;
}
TracerouteWindowsInternal::computeHopStatistics(lHop);
if (aConfig.mResolveHostnames && lHop.mResponded && !lHop.mIpAddress.empty()) {
sockaddr_storage lHopAddress{};
socklen_t lHopAddressLength = lIsV6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in);
if (lIsV6) {
auto* lpAddress = reinterpret_cast<sockaddr_in6*>(&lHopAddress);
lpAddress->sin6_family = AF_INET6;
InetPtonA(AF_INET6, lHop.mIpAddress.c_str(), &lpAddress->sin6_addr);
} else {
auto* lpAddress = reinterpret_cast<sockaddr_in*>(&lHopAddress);
lpAddress->sin_family = AF_INET;
InetPtonA(AF_INET, lHop.mIpAddress.c_str(), &lpAddress->sin_addr);
}
lHop.mHostname = resolveHostname(lHopAddress, lHopAddressLength);
}
if (mOnHopResult) mOnHopResult(lHop);
lResult.mHops.push_back(lHop);
lResult.mHopCount = lTtl;
if (lHop.mIsDestination) {
lResult.mReachedDestination = true;
if (aConfig.mStopOnDestination) break;
}
if (lHop.mError != TracerouteError::SUCCESS) {
lResult.mError = lHop.mError;
break;
}
}
return lResult;
}