97bc8b8df1c8782b429e40655990faef0e5e1c3f
[reactos.git] / base / applications / network / tracert / tracert.c
1 /*
2 * PROJECT: ReactOS trace route utility
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: base/applications/network/tracert.c
5 * PURPOSE: Trace network paths through networks
6 * COPYRIGHT: Copyright 2006 - 2007 Ged Murphy <gedmurphy@reactos.org>
7 *
8 */
9
10 #include "tracert.h"
11
12 //#define TRACERT_DBG
13
14 CHAR cHostname[256]; // target hostname
15 CHAR cDestIP[18]; // target IP
16
17
18 static VOID
19 DebugPrint(LPTSTR lpString, ...)
20 {
21 #ifdef TRACERT_DBG
22 va_list args;
23 va_start(args, lpString);
24 _vtprintf(lpString, args);
25 va_end(args);
26 #else
27 UNREFERENCED_PARAMETER(lpString);
28 #endif
29 }
30
31
32 static VOID
33 Usage(VOID)
34 {
35 _tprintf(_T("\nUsage: tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name\n\n"
36 "Options:\n"
37 " -d Do not resolve addresses to hostnames.\n"
38 " -h maximum_hops Maximum number of hops to search for target.\n"
39 " -j host-list Loose source route along host-list.\n"
40 " -w timeout Wait timeout milliseconds for each reply.\n\n"));
41
42 _tprintf(_T("NOTES\n-----\n"
43 "- Setting TTL values is not currently supported in ReactOS, so the trace will\n"
44 " jump straight to the destination. This feature will be implemented soon.\n"
45 "- Host info is not currently available in ReactOS and will fail with strange\n"
46 " results. Use -d to force it not to resolve IP's.\n"
47 "- For testing purposes, all should work as normal in a Windows environment\n\n"));
48 }
49
50
51 static BOOL
52 ParseCmdline(int argc,
53 LPCTSTR argv[],
54 PAPPINFO pInfo)
55 {
56 INT i;
57
58 if (argc < 2)
59 {
60 Usage();
61 return FALSE;
62 }
63 else
64 {
65 for (i = 1; i < argc; i++)
66 {
67 if (argv[i][0] == _T('-'))
68 {
69 switch (argv[i][1])
70 {
71 case _T('d'):
72 pInfo->bResolveAddresses = FALSE;
73 break;
74
75 case _T('h'):
76 _stscanf(argv[i+1], _T("%d"), &pInfo->iMaxHops);
77 break;
78
79 case _T('j'):
80 _tprintf(_T("-j is not yet implemented.\n"));
81 break;
82
83 case _T('w'):
84 _stscanf(argv[i+1], _T("%d"), &pInfo->iTimeOut);
85 break;
86
87 default:
88 {
89 _tprintf(_T("%s is not a valid option.\n"), argv[i]);
90 Usage();
91 return FALSE;
92 }
93 }
94 }
95 else
96 /* copy target address */
97 _tcsncpy(cHostname, argv[i], 255);
98 }
99 }
100
101 return TRUE;
102 }
103
104
105 static WORD
106 CheckSum(PUSHORT data,
107 UINT size)
108 {
109 DWORD dwSum = 0;
110
111 while (size > 1)
112 {
113 dwSum += *data++;
114 size -= sizeof(USHORT);
115 }
116
117 if (size)
118 dwSum += *(UCHAR*)data;
119
120 dwSum = (dwSum >> 16) + (dwSum & 0xFFFF);
121 dwSum += (dwSum >> 16);
122
123 return (USHORT)(~dwSum);
124 }
125
126
127 static VOID
128 SetupTimingMethod(PAPPINFO pInfo)
129 {
130 LARGE_INTEGER PerformanceCounterFrequency;
131
132 /* check if performance counters are available */
133 pInfo->bUsePerformanceCounter = QueryPerformanceFrequency(&PerformanceCounterFrequency);
134
135 if (pInfo->bUsePerformanceCounter)
136 {
137 /* restrict execution to first processor on SMP systems */
138 if (SetThreadAffinityMask(GetCurrentThread(), 1) == 0)
139 pInfo->bUsePerformanceCounter = FALSE;
140
141 pInfo->TicksPerMs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000;
142 pInfo->TicksPerUs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000000;
143 }
144 else
145 {
146 pInfo->TicksPerMs.QuadPart = 1;
147 pInfo->TicksPerUs.QuadPart = 1;
148 }
149 }
150
151
152 static BOOL
153 ResolveHostname(PAPPINFO pInfo)
154 {
155 HOSTENT *hp;
156 ULONG addr;
157
158 ZeroMemory(&pInfo->dest, sizeof(pInfo->dest));
159
160 /* if address is not a dotted decimal */
161 if ((addr = inet_addr(cHostname))== INADDR_NONE)
162 {
163 if ((hp = gethostbyname(cHostname)) != 0)
164 {
165 //CopyMemory(&pInfo->dest.sin_addr, hp->h_addr, hp->h_length);
166 pInfo->dest.sin_addr = *((struct in_addr *)hp->h_addr);
167 pInfo->dest.sin_family = hp->h_addrtype;
168 }
169 else
170 {
171 _tprintf(_T("Unable to resolve target system name %s.\n"), cHostname);
172 return FALSE;
173 }
174 }
175 else
176 {
177 pInfo->dest.sin_addr.s_addr = addr;
178 pInfo->dest.sin_family = AF_INET;
179 }
180
181 _tcscpy(cDestIP, inet_ntoa(pInfo->dest.sin_addr));
182
183 return TRUE;
184 }
185
186
187 static LONGLONG
188 GetTime(PAPPINFO pInfo)
189 {
190 LARGE_INTEGER Time;
191
192 /* Get the system time using preformance counters if available */
193 if (pInfo->bUsePerformanceCounter)
194 {
195 if (QueryPerformanceCounter(&Time))
196 {
197 return Time.QuadPart;
198 }
199 }
200
201 /* otherwise fall back to GetTickCount */
202 Time.u.LowPart = (DWORD)GetTickCount();
203 Time.u.HighPart = 0;
204
205 return (LONGLONG)Time.u.LowPart;
206 }
207
208
209 static BOOL
210 SetTTL(SOCKET sock,
211 INT iTTL)
212 {
213 if (setsockopt(sock,
214 IPPROTO_IP,
215 IP_TTL,
216 (const char *)&iTTL,
217 sizeof(iTTL)) == SOCKET_ERROR)
218 {
219 DebugPrint(_T("TTL setsockopt failed : %d. \n"), WSAGetLastError());
220 return FALSE;
221 }
222
223 return TRUE;
224 }
225
226
227 static BOOL
228 CreateSocket(PAPPINFO pInfo)
229 {
230 pInfo->icmpSock = WSASocket(AF_INET,
231 SOCK_RAW,
232 IPPROTO_ICMP,
233 0,
234 0,
235 0);
236
237 if (pInfo->icmpSock == INVALID_SOCKET)
238 {
239 INT err = WSAGetLastError();
240 DebugPrint(_T("Could not create socket : %d.\n"), err);
241
242 if (err == WSAEACCES)
243 {
244 _tprintf(_T("\n\nYou must have access to raw sockets (admin) to run this program!\n\n"));
245 }
246
247 return FALSE;
248 }
249
250 return TRUE;
251 }
252
253
254 static VOID
255 PreparePacket(PAPPINFO pInfo,
256 USHORT iSeqNum)
257 {
258 /* assemble ICMP echo request packet */
259 pInfo->SendPacket->icmpheader.type = ECHO_REQUEST;
260 pInfo->SendPacket->icmpheader.code = 0;
261 pInfo->SendPacket->icmpheader.checksum = 0;
262 pInfo->SendPacket->icmpheader.id = (USHORT)GetCurrentProcessId();
263 pInfo->SendPacket->icmpheader.seq = htons((USHORT)iSeqNum);
264
265 /* calculate checksum of packet */
266 pInfo->SendPacket->icmpheader.checksum = CheckSum((PUSHORT)&pInfo->SendPacket->icmpheader,
267 sizeof(ICMP_HEADER) + PACKET_SIZE);
268 }
269
270
271 static INT
272 SendPacket(PAPPINFO pInfo)
273 {
274 INT iSockRet;
275
276 DebugPrint(_T("\nsending packet of %d bytes... "), PACKET_SIZE);
277
278 /* get time packet was sent */
279 pInfo->lTimeStart = GetTime(pInfo);
280
281 iSockRet = sendto(pInfo->icmpSock, //socket
282 (char *)&pInfo->SendPacket->icmpheader,//buffer
283 sizeof(ICMP_HEADER) + PACKET_SIZE,//size of buffer
284 0, //flags
285 (SOCKADDR *)&pInfo->dest, //destination
286 sizeof(pInfo->dest)); //address length
287
288 if (iSockRet == SOCKET_ERROR)
289 {
290 if (WSAGetLastError() == WSAEACCES)
291 {
292 /* FIXME: Is this correct? */
293 _tprintf(_T("\n\nYou must be an administrator to run this program!\n\n"));
294 WSACleanup();
295 HeapFree(GetProcessHeap(), 0, pInfo);
296 exit(-1);
297 }
298 else
299 {
300 DebugPrint(_T("sendto failed %d\n"), WSAGetLastError());
301 }
302 }
303 else
304 {
305 DebugPrint(_T("sent %d bytes\n"), iSockRet);
306 }
307
308 return iSockRet;
309 }
310
311
312 static BOOL
313 ReceivePacket(PAPPINFO pInfo)
314 {
315 TIMEVAL timeVal;
316 FD_SET readFDS;
317 INT iSockRet = 0, iSelRet;
318 INT iFromLen;
319 BOOL bRet = FALSE;
320
321 iFromLen = sizeof(pInfo->source);
322
323 DebugPrint(_T("Receiving packet. Available buffer, %d bytes... "), MAX_PING_PACKET_SIZE);
324
325 /* monitor icmpSock for incomming connections */
326 FD_ZERO(&readFDS);
327 FD_SET(pInfo->icmpSock, &readFDS);
328
329 /* set timeout values */
330 timeVal.tv_sec = pInfo->iTimeOut / 1000;
331 timeVal.tv_usec = pInfo->iTimeOut % 1000;
332
333 iSelRet = select(0,
334 &readFDS,
335 NULL,
336 NULL,
337 &timeVal);
338
339 if (iSelRet == SOCKET_ERROR)
340 {
341 DebugPrint(_T("select() failed in sendPacket() %d\n"), WSAGetLastError());
342 }
343 else if (iSelRet == 0) /* if socket timed out */
344 {
345 _tprintf(_T(" * "));
346 }
347 else if ((iSelRet != SOCKET_ERROR) && (iSelRet != 0))
348 {
349 iSockRet = recvfrom(pInfo->icmpSock, // socket
350 (char *)pInfo->RecvPacket, // buffer
351 MAX_PING_PACKET_SIZE, // size of buffer
352 0, // flags
353 (SOCKADDR *)&pInfo->source, // source address
354 &iFromLen); // address length
355
356 if (iSockRet != SOCKET_ERROR)
357 {
358 /* get time packet was recieved */
359 pInfo->lTimeEnd = GetTime(pInfo);
360 DebugPrint(_T("reveived %d bytes\n"), iSockRet);
361 bRet = TRUE;
362 }
363 else
364 {
365 DebugPrint(_T("recvfrom failed: %d\n"), WSAGetLastError());
366 }
367 }
368
369 return bRet;
370 }
371
372
373 static INT
374 DecodeResponse(PAPPINFO pInfo)
375 {
376 unsigned short header_len = pInfo->RecvPacket->h_len * 4;
377
378 /* cast the recieved packet into an ECHO reply and a TTL Exceed and check the ID*/
379 ECHO_REPLY_HEADER *IcmpHdr = (ECHO_REPLY_HEADER *)((char*)pInfo->RecvPacket + header_len);
380 TTL_EXCEED_HEADER *TTLExceedHdr = (TTL_EXCEED_HEADER *)((char *)pInfo->RecvPacket + header_len);
381
382 /* Make sure the reply is ok */
383 if (PACKET_SIZE < header_len + ICMP_MIN_SIZE)
384 {
385 DebugPrint(_T("too few bytes from %s\n"), inet_ntoa(pInfo->dest.sin_addr));
386 return -2;
387 }
388
389 switch (IcmpHdr->icmpheader.type)
390 {
391 case TTL_EXCEEDED :
392 if (TTLExceedHdr->OrigIcmpHeader.id != (USHORT)GetCurrentProcessId())
393 {
394 /* FIXME: our network stack shouldn't allow this... */
395 /* we've picked up a packet not related to this process probably from another local program. We ignore it */
396 DebugPrint(_T("Rouge packet: header id, process id %d"), TTLExceedHdr->OrigIcmpHeader.id, GetCurrentProcessId());
397 return -1;
398 }
399 _tprintf(_T("%3ld ms"), (ULONG)((pInfo->lTimeEnd - pInfo->lTimeStart) / pInfo->TicksPerMs.QuadPart));
400 return 0;
401
402 case ECHO_REPLY :
403 if (IcmpHdr->icmpheader.id != (USHORT)GetCurrentProcessId())
404 {
405 /* FIXME: our network stack shouldn't allow this... */
406 /* we've picked up a packet not related to this process probably from another local program. We ignore it */
407 DebugPrint(_T("Rouge packet: header id %d, process id %d"), IcmpHdr->icmpheader.id, GetCurrentProcessId());
408 return -1;
409 }
410 _tprintf(_T("%3ld ms"), (ULONG)((pInfo->lTimeEnd - pInfo->lTimeStart) / pInfo->TicksPerMs.QuadPart));
411 return 1;
412
413 case DEST_UNREACHABLE :
414 _tprintf(_T(" * "));
415 return 2;
416 }
417
418 return 0;
419 }
420
421
422 static BOOL
423 AllocateBuffers(PAPPINFO pInfo)
424 {
425 pInfo->SendPacket = (PECHO_REPLY_HEADER)HeapAlloc(GetProcessHeap(),
426 0,
427 sizeof(ECHO_REPLY_HEADER) + PACKET_SIZE);
428 if (!pInfo->SendPacket)
429 return FALSE;
430
431 pInfo->RecvPacket = (PIPv4_HEADER)HeapAlloc(GetProcessHeap(),
432 0,
433 sizeof(IPv4_HEADER) + PACKET_SIZE);
434 if (!pInfo->RecvPacket)
435 {
436 HeapFree(GetProcessHeap(),
437 0,
438 pInfo->SendPacket);
439
440 return FALSE;
441 }
442
443 return TRUE;
444 }
445
446
447 static INT
448 Driver(PAPPINFO pInfo)
449 {
450 INT iHopCount = 1; // hop counter. default max is 30
451 BOOL bFoundTarget = FALSE; // Have we reached our destination yet
452 INT iRecieveReturn; // RecieveReturn return value
453 PECHO_REPLY_HEADER icmphdr;
454 INT iTTL = 1;
455
456 INT ret = -1;
457
458 //temps for getting host name
459 CHAR cHost[256];
460 CHAR cServ[256];
461 CHAR *ip;
462
463 SetupTimingMethod(pInfo);
464
465 if (AllocateBuffers(pInfo) &&
466 ResolveHostname(pInfo) &&
467 CreateSocket(pInfo))
468 {
469 /* print tracing info to screen */
470 _tprintf(_T("\nTracing route to %s [%s]\n"), cHostname, cDestIP);
471 _tprintf(_T("over a maximum of %d hop"), pInfo->iMaxHops);
472 pInfo->iMaxHops > 1 ? _tprintf(_T("s:\n\n")) : _tprintf(_T(":\n\n"));
473
474 /* run until we hit either max hops, or find the target */
475 while ((iHopCount <= pInfo->iMaxHops) &&
476 (bFoundTarget != TRUE))
477 {
478 USHORT iSeqNum = 0;
479 INT i;
480
481 _tprintf(_T("%3d "), iHopCount);
482
483 /* run 3 pings for each hop */
484 for (i = 0; i < 3; i++)
485 {
486 if (SetTTL(pInfo->icmpSock, iTTL) != TRUE)
487 {
488 DebugPrint(_T("error in Setup()\n"));
489 return ret;
490 }
491
492 PreparePacket(pInfo, iSeqNum);
493
494 if (SendPacket(pInfo) != SOCKET_ERROR)
495 {
496 BOOL bAwaitPacket = FALSE; // indicates whether we have recieved a good packet
497
498 do
499 {
500 /* Receive replies until we get a successful read, or a fatal error */
501 if ((iRecieveReturn = ReceivePacket(pInfo)) < 0)
502 {
503 /* FIXME: consider moving this into RecievePacket */
504 /* check the seq num in the packet, if it's bad wait for another */
505 WORD hdrLen = pInfo->RecvPacket->h_len * 4;
506 icmphdr = (ECHO_REPLY_HEADER *)((char*)&pInfo->RecvPacket + hdrLen);
507 if (icmphdr->icmpheader.seq != iSeqNum)
508 {
509 _tprintf(_T("bad sequence number!\n"));
510 continue;
511 }
512 }
513
514 if (iRecieveReturn)
515 {
516 DecodeResponse(pInfo);
517 }
518 else
519 /* packet timed out. Don't wait for it again */
520 bAwaitPacket = FALSE;
521
522 } while (bAwaitPacket);
523 }
524
525 iSeqNum++;
526 _tprintf(_T(" "));
527 }
528
529 if(pInfo->bResolveAddresses)
530 {
531 INT iNameInfoRet; // getnameinfo return value
532 /* gethostbyaddr() and getnameinfo() are
533 * unimplemented in ROS at present.
534 * Alex has advised he will be implementing getnameinfo.
535 * I've used that for the time being for testing in Windows*/
536
537 //ip = inet_addr(inet_ntoa(source.sin_addr));
538 //host = gethostbyaddr((char *)&ip, 4, 0);
539
540 ip = inet_ntoa(pInfo->source.sin_addr);
541
542 iNameInfoRet = getnameinfo((SOCKADDR *)&pInfo->source,
543 sizeof(SOCKADDR),
544 cHost,
545 256,
546 cServ,
547 256,
548 NI_NUMERICSERV);
549 if (iNameInfoRet == 0)
550 {
551 /* if IP address resolved to a hostname,
552 * print the IP address after it */
553 if (lstrcmpA(cHost, ip) != 0)
554 _tprintf(_T("%s [%s]"), cHost, ip);
555 else
556 _tprintf(_T("%s"), cHost);
557 }
558 else
559 {
560 DebugPrint(_T("error: %d"), WSAGetLastError());
561 DebugPrint(_T(" getnameinfo failed: %d"), iNameInfoRet);
562 }
563
564 }
565 else
566 _tprintf(_T("%s"), inet_ntoa(pInfo->source.sin_addr));
567
568 _tprintf(_T("\n"));
569
570 /* check if we've arrived at the target */
571 if (strcmp(cDestIP, inet_ntoa(pInfo->source.sin_addr)) == 0)
572 bFoundTarget = TRUE;
573 else
574 {
575 iTTL++;
576 iHopCount++;
577 Sleep(500);
578 }
579 }
580 _tprintf(_T("\nTrace complete.\n"));
581 ret = 0;
582 }
583
584 return ret;
585 }
586
587
588 static VOID
589 Cleanup(PAPPINFO pInfo)
590 {
591 if (pInfo->icmpSock)
592 closesocket(pInfo->icmpSock);
593
594 WSACleanup();
595
596 if (pInfo->SendPacket)
597 HeapFree(GetProcessHeap(),
598 0,
599 pInfo->SendPacket);
600
601 if (pInfo->RecvPacket)
602 HeapFree(GetProcessHeap(),
603 0,
604 pInfo->RecvPacket);
605 }
606
607
608 #if defined(_UNICODE) && defined(__GNUC__)
609 static
610 #endif
611 int _tmain(int argc, LPCTSTR argv[])
612 {
613 PAPPINFO pInfo;
614 WSADATA wsaData;
615 int ret = -1;
616
617 pInfo = (PAPPINFO)HeapAlloc(GetProcessHeap(),
618 HEAP_ZERO_MEMORY,
619 sizeof(APPINFO));
620 if (pInfo)
621 {
622 pInfo->bResolveAddresses = TRUE;
623 pInfo->iMaxHops = 30;
624 pInfo->iTimeOut = 1000;
625
626 if (ParseCmdline(argc, argv, pInfo))
627 {
628 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
629 {
630 DebugPrint(_T("WSAStartup failed.\n"));
631 }
632 else
633 {
634 ret = Driver(pInfo);
635 Cleanup(pInfo);
636 }
637 }
638
639 HeapFree(GetProcessHeap(),
640 0,
641 pInfo);
642 }
643
644 return ret;
645 }
646
647
648 #if defined(_UNICODE) && defined(__GNUC__)
649 /* HACK - MINGW HAS NO OFFICIAL SUPPORT FOR wmain()!!! */
650 int main( int argc, char **argv )
651 {
652 WCHAR **argvW;
653 int i, j, Ret = 1;
654
655 if ((argvW = malloc(argc * sizeof(WCHAR*))))
656 {
657 /* convert the arguments */
658 for (i = 0, j = 0; i < argc; i++)
659 {
660 if (!(argvW[i] = malloc((strlen(argv[i]) + 1) * sizeof(WCHAR))))
661 {
662 j++;
663 }
664 swprintf(argvW[i], L"%hs", argv[i]);
665 }
666
667 if (j == 0)
668 {
669 /* no error converting the parameters, call wmain() */
670 Ret = wmain(argc, (LPCTSTR *)argvW);
671 }
672
673 /* free the arguments */
674 for (i = 0; i < argc; i++)
675 {
676 if (argvW[i])
677 free(argvW[i]);
678 }
679 free(argvW);
680 }
681
682 return Ret;
683 }
684 #endif