download tracert.c
Language: C
Copyright: Copyright 2006 - 2007 Ged Murphy
LOC: 514
Project Info
ReactOS
Server: ReactOS
Type: svn
...plications\network\tracert\
   tracert.c
   tracert.h
   tracert.rbuild
   tracert.rc

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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
 /*
 * PROJECT:     ReactOS trace route utility
 * LICENSE:     GPL - See COPYING in the top level directory
 * FILE:        base/applications/network/tracert.c
 * PURPOSE:     Trace network paths through networks
 * COPYRIGHT:   Copyright 2006 - 2007 Ged Murphy <gedmurphy@reactos.org>
 *
 */

#include "tracert.h"

//#define TRACERT_DBG

CHAR cHostname[256];            // target hostname
CHAR cDestIP[18];               // target IP


static VOID
DebugPrint(LPTSTR lpString, ...)
{
#ifdef TRACERT_DBG
    va_list args;
    va_start(args, lpString);
    _vtprintf(lpString, args);
    va_end(args);
#else
    UNREFERENCED_PARAMETER(lpString);
#endif
}


static VOID
Usage(VOID)
{
    _tprintf(_T("\nUsage: tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name\n\n"
                "Options:\n"
                "    -d                 Do not resolve addresses to hostnames.\n"
                "    -h maximum_hops    Maximum number of hops to search for target.\n"
                "    -j host-list       Loose source route along host-list.\n"
                "    -w timeout         Wait timeout milliseconds for each reply.\n\n"));

    _tprintf(_T("NOTES\n-----\n"
           "- Setting TTL values is not currently supported in ReactOS, so the trace will\n"
           "  jump straight to the destination. This feature will be implemented soon.\n"
           "- Host info is not currently available in ReactOS and will fail with strange\n"
           "  results. Use -d to force it not to resolve IP's.\n"
           "- For testing purposes, all should work as normal in a Windows environment\n\n"));
}


static BOOL
ParseCmdline(int argc,
             LPCTSTR argv[],
             PAPPINFO pInfo)
{
    INT i;

    if (argc < 2)
    {
       Usage();
       return FALSE;
    }
    else
    {
        for (i = 1; i < argc; i++)
        {
            if (argv[i][0] == _T('-'))
            {
                switch (argv[i][1])
                {
                    case _T('d'):
                        pInfo->bResolveAddresses = FALSE;
                    break;

                    case _T('h'):
                        _stscanf(argv[i+1], _T("%d"), &pInfo->iMaxHops);
                    break;

                    case _T('j'):
                        _tprintf(_T("-j is not yet implemented.\n"));
                    break;

                    case _T('w'):
                        _stscanf(argv[i+1], _T("%d"), &pInfo->iTimeOut);
                    break;

                    default:
                    {
                        _tprintf(_T("%s is not a valid option.\n"), argv[i]);
                        Usage();
                        return FALSE;
                    }
                }
            }
            else
               /* copy target address */
               _tcsncpy(cHostname, argv[i], 255);
        }
    }

    return TRUE;
}


static WORD
CheckSum(PUSHORT data,
         UINT size)
{
    DWORD dwSum = 0;

    while (size > 1)
    {
        dwSum += *data++;
        size -= sizeof(USHORT);
    }

    if (size)
        dwSum += *(UCHAR*)data;

    dwSum = (dwSum >> 16) + (dwSum & 0xFFFF);
    dwSum += (dwSum >> 16);

    return (USHORT)(~dwSum);
}


static VOID
SetupTimingMethod(PAPPINFO pInfo)
{
    LARGE_INTEGER PerformanceCounterFrequency;

    /* check if performance counters are available */
    pInfo->bUsePerformanceCounter = QueryPerformanceFrequency(&PerformanceCounterFrequency);

    if (pInfo->bUsePerformanceCounter)
    {
        /* restrict execution to first processor on SMP systems */
        if (SetThreadAffinityMask(GetCurrentThread(), 1) == 0)
            pInfo->bUsePerformanceCounter = FALSE;

        pInfo->TicksPerMs.QuadPart  = PerformanceCounterFrequency.QuadPart / 1000;
        pInfo->TicksPerUs.QuadPart  = PerformanceCounterFrequency.QuadPart / 1000000;
    }
    else
    {
        pInfo->TicksPerMs.QuadPart = 1;
        pInfo->TicksPerUs.QuadPart = 1;
    }
}


static BOOL
ResolveHostname(PAPPINFO pInfo)
{
    HOSTENT *hp;
    ULONG addr;

    ZeroMemory(&pInfo->dest, sizeof(pInfo->dest));

    /* if address is not a dotted decimal */
    if ((addr = inet_addr(cHostname))== INADDR_NONE)
    {
       if ((hp = gethostbyname(cHostname)) != 0)
       {
          //CopyMemory(&pInfo->dest.sin_addr, hp->h_addr, hp->h_length);
          pInfo->dest.sin_addr = *((struct in_addr *)hp->h_addr);
          pInfo->dest.sin_family = hp->h_addrtype;
       }
       else
       {
          _tprintf(_T("Unable to resolve target system name %s.\n"), cHostname);
          return FALSE;
       }
    }
    else
    {
        pInfo->dest.sin_addr.s_addr = addr;
        pInfo->dest.sin_family = AF_INET;
    }

    _tcscpy(cDestIP, inet_ntoa(pInfo->dest.sin_addr));

    return TRUE;
}


static LONGLONG
GetTime(PAPPINFO pInfo)
{
    LARGE_INTEGER Time;

    /* Get the system time using preformance counters if available */
    if (pInfo->bUsePerformanceCounter)
    {
        if (QueryPerformanceCounter(&Time))
        {
            return Time.QuadPart;
        }
    }

    /* otherwise fall back to GetTickCount */
    Time.u.LowPart = (DWORD)GetTickCount();
    Time.u.HighPart = 0;

    return (LONGLONG)Time.u.LowPart;
}


static BOOL
SetTTL(SOCKET sock,
       INT iTTL)
{
    if (setsockopt(sock,
                   IPPROTO_IP,
                   IP_TTL,
                   (const char *)&iTTL,
                   sizeof(iTTL)) == SOCKET_ERROR)
    {
       DebugPrint(_T("TTL setsockopt failed : %d. \n"), WSAGetLastError());
       return FALSE;
    }

    return TRUE;
}


static BOOL
CreateSocket(PAPPINFO pInfo)
{
    pInfo->icmpSock = WSASocket(AF_INET,
                                SOCK_RAW,
                                IPPROTO_ICMP,
                                0,
                                0,
                                0);

    if (pInfo->icmpSock == INVALID_SOCKET)
    {
        INT err = WSAGetLastError();
        DebugPrint(_T("Could not create socket : %d.\n"), err);

        if (err == WSAEACCES)
        {
            _tprintf(_T("\n\nYou must have access to raw sockets (admin) to run this program!\n\n"));
        }

        return FALSE;
    }

    return TRUE;
}


static VOID
PreparePacket(PAPPINFO pInfo,
              USHORT iSeqNum)
{
    /* assemble ICMP echo request packet */
    pInfo->SendPacket->icmpheader.type     = ECHO_REQUEST;
    pInfo->SendPacket->icmpheader.code     = 0;
    pInfo->SendPacket->icmpheader.checksum = 0;
    pInfo->SendPacket->icmpheader.id       = (USHORT)GetCurrentProcessId();
    pInfo->SendPacket->icmpheader.seq      = iSeqNum;

    /* calculate checksum of packet */
    pInfo->SendPacket->icmpheader.checksum  = CheckSum((PUSHORT)&pInfo->SendPacket,
                                                       sizeof(ICMP_HEADER) + PACKET_SIZE);
}


static INT
SendPacket(PAPPINFO pInfo)
{
    INT iSockRet;

    DebugPrint(_T("\nsending packet of %d bytes... "), PACKET_SIZE);

    /* get time packet was sent */
    pInfo->lTimeStart = GetTime(pInfo);

    iSockRet = sendto(pInfo->icmpSock,              //socket
                      (char *)pInfo->SendPacket,   //buffer
                      PACKET_SIZE,                  //size of buffer
                      0,                            //flags
                      (SOCKADDR *)&pInfo->dest,     //destination
                      sizeof(pInfo->dest));         //address length

    if (iSockRet == SOCKET_ERROR)
    {
        if (WSAGetLastError() == WSAEACCES)
        {
            /* FIXME: Is this correct? */
            _tprintf(_T("\n\nYou must be an administrator to run this program!\n\n"));
            WSACleanup();
            HeapFree(GetProcessHeap(), 0, pInfo);
            exit(-1);
        }
        else
        {
            DebugPrint(_T("sendto failed %d\n"), WSAGetLastError());
        }
    }
    else
    {
        DebugPrint(_T("sent %d bytes\n"), iSockRet);
    }

    return iSockRet;
}


static BOOL
ReceivePacket(PAPPINFO pInfo)
{
    TIMEVAL timeVal;
    FD_SET readFDS;
    INT iSockRet = 0, iSelRet;
    INT iFromLen;
    BOOL bRet = FALSE;

    iFromLen = sizeof(pInfo->source);

    DebugPrint(_T("Receiving packet. Available buffer, %d bytes... "), MAX_PING_PACKET_SIZE);

    /* monitor icmpSock for incomming connections */
    FD_ZERO(&readFDS);
    FD_SET(pInfo->icmpSock, &readFDS);

    /* set timeout values */
    timeVal.tv_sec  = pInfo->iTimeOut / 1000;
    timeVal.tv_usec = pInfo->iTimeOut % 1000;

    iSelRet = select(0,
                     &readFDS,
                     NULL,
                     NULL,
                     &timeVal);

    if (iSelRet == SOCKET_ERROR)
    {
        DebugPrint(_T("select() failed in sendPacket() %d\n"), WSAGetLastError());
    }
    else if (iSelRet == 0) /* if socket timed out */
    {
        _tprintf(_T("   *  "));
    }
    else if ((iSelRet != SOCKET_ERROR) && (iSelRet != 0))
    {
        iSockRet = recvfrom(pInfo->icmpSock,            // socket
                           (char *)pInfo->RecvPacket,  // buffer
                           MAX_PING_PACKET_SIZE,        // size of buffer
                           0,                           // flags
                           (SOCKADDR *)&pInfo->source,  // source address
                           &iFromLen);                  // address length

        if (iSockRet != SOCKET_ERROR)
        {
            /* get time packet was recieved */
            pInfo->lTimeEnd = GetTime(pInfo);
            DebugPrint(_T("reveived %d bytes\n"), iSockRet);
            bRet = TRUE;
        }
        else
        {
            DebugPrint(_T("recvfrom failed: %d\n"), WSAGetLastError());
        }
    }

    return bRet;
}


static INT
DecodeResponse(PAPPINFO pInfo)
{
    unsigned short header_len = pInfo->RecvPacket->h_len * 4;

    /* cast the recieved packet into an ECHO reply and a TTL Exceed and check the ID*/
    ECHO_REPLY_HEADER *IcmpHdr = (ECHO_REPLY_HEADER *)((char*)pInfo->RecvPacket + header_len);
    TTL_EXCEED_HEADER *TTLExceedHdr = (TTL_EXCEED_HEADER *)((char *)pInfo->RecvPacket + header_len);

    /* Make sure the reply is ok */
    if (PACKET_SIZE < header_len + ICMP_MIN_SIZE)
    {
        DebugPrint(_T("too few bytes from %s\n"), inet_ntoa(pInfo->dest.sin_addr));
        return -2;
    }

    switch (IcmpHdr->icmpheader.type)
    {
           case TTL_EXCEEDED :
                if (TTLExceedHdr->OrigIcmpHeader.id != (USHORT)GetCurrentProcessId())
                {
                /* FIXME: our network stack shouldn't allow this... */
                /* we've picked up a packet not related to this process probably from another local program. We ignore it */
                    DebugPrint(_T("Rouge packet: header id,  process id  %d"), TTLExceedHdr->OrigIcmpHeader.id, GetCurrentProcessId());
                    return -1;
                }
                _tprintf(_T("%3Ld ms"), (pInfo->lTimeEnd - pInfo->lTimeStart) / pInfo->TicksPerMs.QuadPart);
                return 0;

           case ECHO_REPLY :
                if (IcmpHdr->icmpheader.id != (USHORT)GetCurrentProcessId())
                {
                /* FIXME: our network stack shouldn't allow this... */
                /* we've picked up a packet not related to this process probably from another local program. We ignore it */
                    DebugPrint(_T("Rouge packet: header id %d, process id  %d"), IcmpHdr->icmpheader.id, GetCurrentProcessId());
                    return -1;
                }
                _tprintf(_T("%3Ld ms"), (pInfo->lTimeEnd - pInfo->lTimeStart) / pInfo->TicksPerMs.QuadPart);
                return 1;

           case DEST_UNREACHABLE :
                _tprintf(_T("  *  "));
                return 2;
    }

    return 0;
}


static BOOL
AllocateBuffers(PAPPINFO pInfo)
{
    pInfo->SendPacket = (PECHO_REPLY_HEADER)HeapAlloc(GetProcessHeap(),
                                                      0,
                                                      sizeof(ECHO_REPLY_HEADER) + PACKET_SIZE);
    if (!pInfo->SendPacket)
        return FALSE;

    pInfo->RecvPacket = (PIPv4_HEADER)HeapAlloc(GetProcessHeap(),
                                                0,
                                                sizeof(IPv4_HEADER) + PACKET_SIZE);
    if (!pInfo->RecvPacket)
    {
        HeapFree(GetProcessHeap(),
                 0,
                 pInfo->SendPacket);

        return FALSE;
    }

    return TRUE;
}


static INT
Driver(PAPPINFO pInfo)
{
    INT iHopCount = 1;              // hop counter. default max is 30
    BOOL bFoundTarget = FALSE;      // Have we reached our destination yet
    INT iRecieveReturn;             // RecieveReturn return value
    PECHO_REPLY_HEADER icmphdr;
    INT iTTL = 1;

    INT ret = -1;

    //temps for getting host name
    CHAR cHost[256];
    CHAR cServ[256];
    CHAR *ip;

    SetupTimingMethod(pInfo);

    if (AllocateBuffers(pInfo) &&
        ResolveHostname(pInfo) &&
        CreateSocket(pInfo))
    {
        /* print tracing info to screen */
        _tprintf(_T("\nTracing route to %s [%s]\n"), cHostname, cDestIP);
        _tprintf(_T("over a maximum of %d hop"), pInfo->iMaxHops);
        pInfo->iMaxHops > 1 ? _tprintf(_T("s:\n\n")) : _tprintf(_T(":\n\n"));

        /* run until we hit either max hops, or find the target */
        while ((iHopCount <= pInfo->iMaxHops) &&
               (bFoundTarget != TRUE))
        {
            USHORT iSeqNum = 0;
            INT i;

            _tprintf(_T("%3d   "), iHopCount);

            /* run 3 pings for each hop */
            for (i = 0; i < 3; i++)
            {
                if (SetTTL(pInfo->icmpSock, iTTL) != TRUE)
                {
                    DebugPrint(_T("error in Setup()\n"));
                    return ret;
                }

                PreparePacket(pInfo, iSeqNum);

                if (SendPacket(pInfo) != SOCKET_ERROR)
                {
                    BOOL bAwaitPacket = FALSE; // indicates whether we have recieved a good packet

                    do
                    {
                        /* Receive replies until we get a successful read, or a fatal error */
                        if ((iRecieveReturn = ReceivePacket(pInfo)) < 0)
                        {
                            /* FIXME: consider moving this into RecievePacket */
                            /* check the seq num in the packet, if it's bad wait for another */
                            WORD hdrLen = pInfo->RecvPacket->h_len * 4;
                            icmphdr = (ECHO_REPLY_HEADER *)((char*)&pInfo->RecvPacket + hdrLen);
                            if (icmphdr->icmpheader.seq != iSeqNum)
                            {
                                _tprintf(_T("bad sequence number!\n"));
                                continue;
                            }
                        }

                        if (iRecieveReturn)
                        {
                            DecodeResponse(pInfo);
                        }
                        else
                            /* packet timed out. Don't wait for it again */
                            bAwaitPacket = FALSE;

                    } while (bAwaitPacket);
                }

                iSeqNum++;
                _tprintf(_T("   "));
            }

            if(pInfo->bResolveAddresses)
            {
                INT iNameInfoRet;               // getnameinfo return value
               /* gethostbyaddr() and getnameinfo() are
                * unimplemented in ROS at present.
                * Alex has advised he will be implementing getnameinfo.
                * I've used that for the time being for testing in Windows*/

                  //ip = inet_addr(inet_ntoa(source.sin_addr));
                  //host = gethostbyaddr((char *)&ip, 4, 0);

                  ip = inet_ntoa(pInfo->source.sin_addr);

                  iNameInfoRet = getnameinfo((SOCKADDR *)&pInfo->source,
                                             sizeof(SOCKADDR),
                                             cHost,
                                             256,
                                             cServ,
                                             256,
                                             NI_NUMERICSERV);
                  if (iNameInfoRet == 0)
                  {
                     /* if IP address resolved to a hostname,
                      * print the IP address after it */
                      if (lstrcmpA(cHost, ip) != 0)
                          _tprintf(_T("%s [%s]"), cHost, ip);
                      else
                          _tprintf(_T("%s"), cHost);
                  }
                  else
                  {
                      DebugPrint(_T("error: %d"), WSAGetLastError());
                      DebugPrint(_T(" getnameinfo failed: %d"), iNameInfoRet);
                  }

            }
            else
               _tprintf(_T("%s"), inet_ntoa(pInfo->source.sin_addr));

            _tprintf(_T("\n"));

            /* check if we've arrived at the target */
            if (strcmp(cDestIP, inet_ntoa(pInfo->source.sin_addr)) == 0)
                bFoundTarget = TRUE;
            else
            {
                iTTL++;
                iHopCount++;
                Sleep(500);
            }
        }
        _tprintf(_T("\nTrace complete.\n"));
        ret = 0;
    }

    return ret;
}


static VOID
Cleanup(PAPPINFO pInfo)
{
    if (pInfo->icmpSock)
        closesocket(pInfo->icmpSock);

    WSACleanup();

    if (pInfo->SendPacket)
        HeapFree(GetProcessHeap(),
                 0,
                 pInfo->SendPacket);

    if (pInfo->SendPacket)
        HeapFree(GetProcessHeap(),
                 0,
                 pInfo->RecvPacket);
}


#if defined(_UNICODE) && defined(__GNUC__)
static
#endif
int _tmain(int argc, LPCTSTR argv[])
{
    PAPPINFO pInfo;
    WSADATA wsaData;
    int ret = -1;

    pInfo = (PAPPINFO)HeapAlloc(GetProcessHeap(),
                                HEAP_ZERO_MEMORY,
                                sizeof(APPINFO));
    if (pInfo)
    {
        pInfo->bResolveAddresses = TRUE;
        pInfo->iMaxHops = 30;
        pInfo->iTimeOut = 1000;

        if (ParseCmdline(argc, argv, pInfo))
        {
            if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
            {
                DebugPrint(_T("WSAStartup failed.\n"));
            }
            else
            {
                ret = Driver(pInfo);
                Cleanup(pInfo);
            }
        }

        HeapFree(GetProcessHeap(),
                 0,
                 pInfo);
    }

    return ret;
}


#if defined(_UNICODE) && defined(__GNUC__)
/* HACK - MINGW HAS NO OFFICIAL SUPPORT FOR wmain()!!! */
int main( int argc, char **argv )
{
    WCHAR **argvW;
    int i, j, Ret = 1;

    if ((argvW = malloc(argc * sizeof(WCHAR*))))
    {
        /* convert the arguments */
        for (i = 0, j = 0; i < argc; i++)
        {
            if (!(argvW[i] = malloc((strlen(argv[i]) + 1) * sizeof(WCHAR))))
            {
                j++;
            }
            swprintf(argvW[i], L"%hs", argv[i]);
        }

        if (j == 0)
        {
            /* no error converting the parameters, call wmain() */
            Ret = wmain(argc, (LPCTSTR *)argvW);
        }

        /* free the arguments */
        for (i = 0; i < argc; i++)
        {
            if (argvW[i])
                free(argvW[i]);
        }
        free(argvW);
    }

    return Ret;
}
#endif

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us