[FORMATTING] Tabs vs space, { } placement, ...

No code change

svn path=/trunk/; revision=29120
This commit is contained in:
Hervé Poussineau 2007-09-20 13:53:38 +00:00
parent b69d44ab8c
commit 8a98cb7fdd

View file

@ -1,11 +1,9 @@
/* /*
* COPYRIGHT: See COPYING in the top level directory * COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS ping utility * PROJECT: ReactOS ping utility
* FILE: apps/net/ping/ping.c * FILE: base/applications/network/ping/ping.c
* PURPOSE: Network test utility * PURPOSE: Network test utility
* PROGRAMMERS: Casper S. Hornstrup (chorns@users.sourceforge.net) * PROGRAMMERS:
* REVISIONS:
* CSH 01/09/2000 Created
*/ */
#include <winsock2.h> #include <winsock2.h>
@ -14,13 +12,9 @@
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#ifndef _MSC_VER #define NDEBUG
/* FIXME: Where should this be? */ #ifndef _MSC_VER
#ifdef CopyMemory
#undef CopyMemory
#endif
#define CopyMemory(Destination, Source, Length) memcpy(Destination, Source, Length);
/* Should be in the header files somewhere (exported by ntdll.dll) */ /* Should be in the header files somewhere (exported by ntdll.dll) */
long atol(const char *str); long atol(const char *str);
@ -33,10 +27,6 @@ char * _i64toa(__int64 value, char *string, int radix);
#endif /* _MSC_VER */ #endif /* _MSC_VER */
#ifdef DBG
#undef DBG
#endif
/* General ICMP constants */ /* General ICMP constants */
#define ICMP_MINSIZE 8 /* Minimum ICMP packet size */ #define ICMP_MINSIZE 8 /* Minimum ICMP packet size */
#define ICMP_MAXSIZE 65535 /* Maximum ICMP packet size */ #define ICMP_MAXSIZE 65535 /* Maximum ICMP packet size */
@ -48,7 +38,8 @@ char * _i64toa(__int64 value, char *string, int radix);
#pragma pack(4) #pragma pack(4)
/* IPv4 header structure */ /* IPv4 header structure */
typedef struct _IPv4_HEADER { typedef struct _IPv4_HEADER
{
unsigned char IHL:4; unsigned char IHL:4;
unsigned char Version:4; unsigned char Version:4;
unsigned char TOS; unsigned char TOS;
@ -63,7 +54,8 @@ typedef struct _IPv4_HEADER {
} IPv4_HEADER, *PIPv4_HEADER; } IPv4_HEADER, *PIPv4_HEADER;
/* ICMP echo request/reply header structure */ /* ICMP echo request/reply header structure */
typedef struct _ICMP_HEADER { typedef struct _ICMP_HEADER
{
unsigned char Type; unsigned char Type;
unsigned char Code; unsigned char Code;
unsigned short Checksum; unsigned short Checksum;
@ -71,7 +63,8 @@ typedef struct _ICMP_HEADER {
unsigned short SeqNum; unsigned short SeqNum;
} ICMP_HEADER, *PICMP_HEADER; } ICMP_HEADER, *PICMP_HEADER;
typedef struct _ICMP_ECHO_PACKET { typedef struct _ICMP_ECHO_PACKET
{
ICMP_HEADER Icmp; ICMP_HEADER Icmp;
LARGE_INTEGER Timestamp; LARGE_INTEGER Timestamp;
} ICMP_ECHO_PACKET, *PICMP_ECHO_PACKET; } ICMP_ECHO_PACKET, *PICMP_ECHO_PACKET;
@ -105,7 +98,7 @@ LARGE_INTEGER TicksPerMs; /* Ticks per millisecond */
LARGE_INTEGER TicksPerUs; /* Ticks per microsecond */ LARGE_INTEGER TicksPerUs; /* Ticks per microsecond */
BOOL UsePerformanceCounter; BOOL UsePerformanceCounter;
#ifdef DBG #ifndef NDEBUG
/* Display the contents of a buffer */ /* Display the contents of a buffer */
static VOID DisplayBuffer( static VOID DisplayBuffer(
PVOID Buffer, PVOID Buffer,
@ -117,14 +110,14 @@ static VOID DisplayBuffer(
printf("Buffer (0x%p) Size (0x%lX).\n", Buffer, Size); printf("Buffer (0x%p) Size (0x%lX).\n", Buffer, Size);
p = (PCHAR)Buffer; p = (PCHAR)Buffer;
for (i = 0; i < Size; i++) { for (i = 0; i < Size; i++)
if (i % 16 == 0) { {
if (i % 16 == 0)
printf("\n"); printf("\n");
}
printf("%02X ", (p[i]) & 0xFF); printf("%02X ", (p[i]) & 0xFF);
} }
} }
#endif /* DBG */ #endif /* !NDEBUG */
/* Display usage information on screen */ /* Display usage information on screen */
static VOID Usage(VOID) static VOID Usage(VOID)
@ -153,20 +146,21 @@ static VOID Reset(VOID)
Timeout = 1000; Timeout = 1000;
UsePerformanceCounter = QueryPerformanceFrequency(&PerformanceCounterFrequency); UsePerformanceCounter = QueryPerformanceFrequency(&PerformanceCounterFrequency);
if (UsePerformanceCounter) { if (UsePerformanceCounter)
{
/* Performance counters may return incorrect results on some multiprocessor /* Performance counters may return incorrect results on some multiprocessor
platforms so we restrict execution on the first processor. This may fail platforms so we restrict execution on the first processor. This may fail
on Windows NT so we fall back to GetCurrentTick() for timing */ on Windows NT so we fall back to GetCurrentTick() for timing */
if (SetThreadAffinityMask (GetCurrentThread(), 1) == 0) { if (SetThreadAffinityMask (GetCurrentThread(), 1) == 0)
UsePerformanceCounter = FALSE; UsePerformanceCounter = FALSE;
}
/* Convert frequency to ticks per millisecond */ /* Convert frequency to ticks per millisecond */
TicksPerMs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000; TicksPerMs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000;
/* And to ticks per microsecond */ /* And to ticks per microsecond */
TicksPerUs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000000; TicksPerUs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000000;
} }
if (!UsePerformanceCounter) { if (!UsePerformanceCounter)
{
/* 1 tick per millisecond for GetCurrentTick() */ /* 1 tick per millisecond for GetCurrentTick() */
TicksPerMs.QuadPart = 1; TicksPerMs.QuadPart = 1;
/* GetCurrentTick() cannot handle microseconds */ /* GetCurrentTick() cannot handle microseconds */
@ -183,7 +177,8 @@ static ULONG GetULONG(LPSTR String)
i = 0; i = 0;
Length = (UINT)_tcslen(String); Length = (UINT)_tcslen(String);
while ((i < Length) && ((String[i] < '0') || (String[i] > '9'))) i++; while ((i < Length) && ((String[i] < '0') || (String[i] > '9'))) i++;
if ((i >= Length) || ((String[i] < '0') || (String[i] > '9'))) { if ((i >= Length) || ((String[i] < '0') || (String[i] > '9')))
{
InvalidOption = TRUE; InvalidOption = TRUE;
return 0; return 0;
} }
@ -198,9 +193,11 @@ static ULONG GetULONG2(LPSTR String1, LPSTR String2, PINT i)
ULONG Value; ULONG Value;
Value = GetULONG(String1); Value = GetULONG(String1);
if (InvalidOption) { if (InvalidOption)
{
InvalidOption = FALSE; InvalidOption = FALSE;
if (String2[0] != '-') { if (String2[0] != '-')
{
Value = GetULONG(String2); Value = GetULONG(String2);
if (!InvalidOption) if (!InvalidOption)
*i += 1; *i += 1;
@ -216,28 +213,26 @@ static BOOL ParseCmdline(int argc, char* argv[])
INT i; INT i;
BOOL ShowUsage; BOOL ShowUsage;
BOOL FoundTarget; BOOL FoundTarget;
//#if 1 if (argc < 2)
// lstrcpy(TargetName, "127.0.0.1");
// PingCount = 1;
// return TRUE;
//#endif
if (argc < 2) {
ShowUsage = TRUE; ShowUsage = TRUE;
} else { else
ShowUsage = FALSE; ShowUsage = FALSE;
}
FoundTarget = FALSE; FoundTarget = FALSE;
InvalidOption = FALSE; InvalidOption = FALSE;
for (i = 1; i < argc; i++) { for (i = 1; i < argc; i++)
if (argv[i][0] == '-') { {
switch (argv[i][1]) { if (argv[i][0] == '-')
{
switch (argv[i][1])
{
case 't': NeverStop = TRUE; break; case 't': NeverStop = TRUE; break;
case 'a': ResolveAddresses = TRUE; break; case 'a': ResolveAddresses = TRUE; break;
case 'n': PingCount = GetULONG2(&argv[i][2], argv[i + 1], &i); break; case 'n': PingCount = GetULONG2(&argv[i][2], argv[i + 1], &i); break;
case 'l': case 'l':
DataSize = GetULONG2(&argv[i][2], argv[i + 1], &i); DataSize = GetULONG2(&argv[i][2], argv[i + 1], &i);
if (DataSize > ICMP_MAXSIZE - sizeof(ICMP_ECHO_PACKET)) { if (DataSize > ICMP_MAXSIZE - sizeof(ICMP_ECHO_PACKET))
{
printf("Bad value for option -l, valid range is from 0 to %d.\n", printf("Bad value for option -l, valid range is from 0 to %d.\n",
ICMP_MAXSIZE - sizeof(ICMP_ECHO_PACKET)); ICMP_MAXSIZE - sizeof(ICMP_ECHO_PACKET));
return FALSE; return FALSE;
@ -252,27 +247,35 @@ static BOOL ParseCmdline(int argc, char* argv[])
Usage(); Usage();
return FALSE; return FALSE;
} }
if (InvalidOption) { if (InvalidOption)
{
printf("Bad option format %s.\n", argv[i]); printf("Bad option format %s.\n", argv[i]);
return FALSE; return FALSE;
} }
} else { }
if (FoundTarget) { else
{
if (FoundTarget)
{
printf("Bad parameter %s.\n", argv[i]); printf("Bad parameter %s.\n", argv[i]);
return FALSE; return FALSE;
} else { }
else
{
lstrcpy(TargetName, argv[i]); lstrcpy(TargetName, argv[i]);
FoundTarget = TRUE; FoundTarget = TRUE;
} }
} }
} }
if ((!ShowUsage) && (!FoundTarget)) { if ((!ShowUsage) && (!FoundTarget))
{
printf("Name or IP address of destination host must be specified.\n"); printf("Name or IP address of destination host must be specified.\n");
return FALSE; return FALSE;
} }
if (ShowUsage) { if (ShowUsage)
{
Usage(); Usage();
return FALSE; return FALSE;
} }
@ -284,7 +287,8 @@ static WORD Checksum(PUSHORT data, UINT size)
{ {
ULONG sum = 0; ULONG sum = 0;
while (size > 1) { while (size > 1)
{
sum += *data++; sum += *data++;
size -= sizeof(USHORT); size -= sizeof(USHORT);
} }
@ -310,13 +314,15 @@ static BOOL Setup(VOID)
wVersionRequested = MAKEWORD(2, 2); wVersionRequested = MAKEWORD(2, 2);
Status = WSAStartup(wVersionRequested, &WsaData); Status = WSAStartup(wVersionRequested, &WsaData);
if (Status != 0) { if (Status != 0)
{
printf("Could not initialize winsock dll.\n"); printf("Could not initialize winsock dll.\n");
return FALSE; return FALSE;
} }
IcmpSock = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, 0); IcmpSock = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, 0);
if (IcmpSock == INVALID_SOCKET) { if (IcmpSock == INVALID_SOCKET)
{
printf("Could not create socket (#%d).\n", WSAGetLastError()); printf("Could not create socket (#%d).\n", WSAGetLastError());
return FALSE; return FALSE;
} }
@ -324,25 +330,25 @@ static BOOL Setup(VOID)
ZeroMemory(&Target, sizeof(Target)); ZeroMemory(&Target, sizeof(Target));
phe = NULL; phe = NULL;
Addr = inet_addr(TargetName); Addr = inet_addr(TargetName);
if (Addr == INADDR_NONE) { if (Addr == INADDR_NONE)
{
phe = gethostbyname(TargetName); phe = gethostbyname(TargetName);
if (phe == NULL) { if (phe == NULL)
{
printf("Unknown host %s.\n", TargetName); printf("Unknown host %s.\n", TargetName);
return FALSE; return FALSE;
} }
} }
if (phe != NULL) { if (phe != NULL)
CopyMemory(&Target.sin_addr, phe->h_addr, phe->h_length); CopyMemory(&Target.sin_addr, phe->h_addr, phe->h_length);
} else { else
Target.sin_addr.s_addr = Addr; Target.sin_addr.s_addr = Addr;
}
if (phe != NULL) { if (phe != NULL)
Target.sin_family = phe->h_addrtype; Target.sin_family = phe->h_addrtype;
} else { else
Target.sin_family = AF_INET; Target.sin_family = AF_INET;
}
TargetIP = inet_ntoa(Target.sin_addr); TargetIP = inet_ntoa(Target.sin_addr);
CurrentSeqNum = 0; CurrentSeqNum = 0;
@ -366,8 +372,10 @@ static VOID Cleanup(VOID)
static VOID QueryTime(PLARGE_INTEGER Time) static VOID QueryTime(PLARGE_INTEGER Time)
{ {
if (UsePerformanceCounter) { if (UsePerformanceCounter)
if (QueryPerformanceCounter(Time) == 0) { {
if (QueryPerformanceCounter(Time) == 0)
{
/* This should not happen, but we fall /* This should not happen, but we fall
back to GetCurrentTick() if it does */ back to GetCurrentTick() if it does */
Time->u.LowPart = (ULONG)GetTickCount(); Time->u.LowPart = (ULONG)GetTickCount();
@ -380,7 +388,9 @@ static VOID QueryTime(PLARGE_INTEGER Time)
UsePerformanceCounter = FALSE; UsePerformanceCounter = FALSE;
} }
} else { }
else
{
Time->u.LowPart = (ULONG)GetTickCount(); Time->u.LowPart = (ULONG)GetTickCount();
Time->u.HighPart = 0; Time->u.HighPart = 0;
} }
@ -414,26 +424,29 @@ static BOOL DecodeResponse(PCHAR buffer, UINT size, PSOCKADDR_IN from)
IphLength = IpHeader->IHL * 4; IphLength = IpHeader->IHL * 4;
if (size < IphLength + ICMP_MINSIZE) { if (size < IphLength + ICMP_MINSIZE)
#ifdef DBG {
#ifndef NDEBUG
printf("Bad size (0x%X < 0x%X)\n", size, IphLength + ICMP_MINSIZE); printf("Bad size (0x%X < 0x%X)\n", size, IphLength + ICMP_MINSIZE);
#endif /* DBG */ #endif /* !NDEBUG */
return FALSE; return FALSE;
} }
Icmp = (PICMP_ECHO_PACKET)(buffer + IphLength); Icmp = (PICMP_ECHO_PACKET)(buffer + IphLength);
if (Icmp->Icmp.Type != ICMPMSG_ECHOREPLY) { if (Icmp->Icmp.Type != ICMPMSG_ECHOREPLY)
#ifdef DBG {
#ifndef NDEBUG
printf("Bad ICMP type (0x%X should be 0x%X)\n", Icmp->Icmp.Type, ICMPMSG_ECHOREPLY); printf("Bad ICMP type (0x%X should be 0x%X)\n", Icmp->Icmp.Type, ICMPMSG_ECHOREPLY);
#endif /* DBG */ #endif /* !NDEBUG */
return FALSE; return FALSE;
} }
if (Icmp->Icmp.Id != (USHORT)GetCurrentProcessId()) { if (Icmp->Icmp.Id != (USHORT)GetCurrentProcessId())
#ifdef DBG {
#ifndef NDEBUG
printf("Bad ICMP id (0x%X should be 0x%X)\n", Icmp->Icmp.Id, (USHORT)GetCurrentProcessId()); printf("Bad ICMP id (0x%X should be 0x%X)\n", Icmp->Icmp.Id, (USHORT)GetCurrentProcessId());
#endif /* DBG */ #endif /* !NDEBUG */
return FALSE; return FALSE;
} }
@ -441,10 +454,13 @@ static BOOL DecodeResponse(PCHAR buffer, UINT size, PSOCKADDR_IN from)
RelativeTime.QuadPart = (LargeTime.QuadPart - Icmp->Timestamp.QuadPart); RelativeTime.QuadPart = (LargeTime.QuadPart - Icmp->Timestamp.QuadPart);
if ((RelativeTime.QuadPart / TicksPerMs.QuadPart) < 1) { if ((RelativeTime.QuadPart / TicksPerMs.QuadPart) < 1)
{
strcpy(Sign, "<"); strcpy(Sign, "<");
strcpy(Time, "1ms"); strcpy(Time, "1ms");
} else { }
else
{
strcpy(Sign, "="); strcpy(Sign, "=");
TimeToMsString(Time, RelativeTime); TimeToMsString(Time, RelativeTime);
} }
@ -452,7 +468,8 @@ static BOOL DecodeResponse(PCHAR buffer, UINT size, PSOCKADDR_IN from)
printf("Reply from %s: bytes=%d time%s%s TTL=%d\n", inet_ntoa(from->sin_addr), printf("Reply from %s: bytes=%d time%s%s TTL=%d\n", inet_ntoa(from->sin_addr),
size - IphLength - sizeof(ICMP_ECHO_PACKET), Sign, Time, IpHeader->TTL); size - IphLength - sizeof(ICMP_ECHO_PACKET), Sign, Time, IpHeader->TTL);
if (RelativeTime.QuadPart < MinRTT.QuadPart || !MinRTTSet) { if (RelativeTime.QuadPart < MinRTT.QuadPart || !MinRTTSet)
{
MinRTT.QuadPart = RelativeTime.QuadPart; MinRTT.QuadPart = RelativeTime.QuadPart;
MinRTTSet = TRUE; MinRTTSet = TRUE;
} }
@ -477,7 +494,8 @@ static BOOL Ping(VOID)
/* Account for extra space for IP header when packet is received */ /* Account for extra space for IP header when packet is received */
Size = DataSize + 128; Size = DataSize + 128;
Buffer = GlobalAlloc(0, Size); Buffer = GlobalAlloc(0, Size);
if (!Buffer) { if (!Buffer)
{
printf("Not enough free resources available.\n"); printf("Not enough free resources available.\n");
return FALSE; return FALSE;
} }
@ -508,24 +526,25 @@ static BOOL Ping(VOID)
Timeval.tv_sec = Timeout / 1000; Timeval.tv_sec = Timeout / 1000;
Timeval.tv_usec = Timeout % 1000; Timeval.tv_usec = Timeout % 1000;
Status = select(0, NULL, &Fds, NULL, &Timeval); Status = select(0, NULL, &Fds, NULL, &Timeval);
if ((Status != SOCKET_ERROR) && (Status != 0)) { if ((Status != SOCKET_ERROR) && (Status != 0))
{
#ifdef DBG #ifndef NDEBUG
printf("Sending packet\n"); printf("Sending packet\n");
DisplayBuffer(Buffer, sizeof(ICMP_ECHO_PACKET) + DataSize); DisplayBuffer(Buffer, sizeof(ICMP_ECHO_PACKET) + DataSize);
printf("\n"); printf("\n");
#endif /* DBG */ #endif /* !NDEBUG */
Status = sendto(IcmpSock, Buffer, sizeof(ICMP_ECHO_PACKET) + DataSize, Status = sendto(IcmpSock, Buffer, sizeof(ICMP_ECHO_PACKET) + DataSize,
0, (SOCKADDR*)&Target, sizeof(Target)); 0, (SOCKADDR*)&Target, sizeof(Target));
SentCount++; SentCount++;
} }
if (Status == SOCKET_ERROR) { if (Status == SOCKET_ERROR)
if (WSAGetLastError() == WSAEHOSTUNREACH) { {
if (WSAGetLastError() == WSAEHOSTUNREACH)
printf("Destination host unreachable.\n"); printf("Destination host unreachable.\n");
} else { else
printf("Could not transmit data (%d).\n", WSAGetLastError()); printf("Could not transmit data (%d).\n", WSAGetLastError());
}
GlobalFree(Buffer); GlobalFree(Buffer);
return FALSE; return FALSE;
} }
@ -537,18 +556,21 @@ static BOOL Ping(VOID)
Timeval.tv_usec = Timeout % 1000; Timeval.tv_usec = Timeout % 1000;
Status = select(0, &Fds, NULL, NULL, &Timeval); Status = select(0, &Fds, NULL, NULL, &Timeval);
if ((Status != SOCKET_ERROR) && (Status != 0)) { if ((Status != SOCKET_ERROR) && (Status != 0))
{
Length = sizeof(From); Length = sizeof(From);
Status = recvfrom(IcmpSock, Buffer, Size, 0, &From, &Length); Status = recvfrom(IcmpSock, Buffer, Size, 0, &From, &Length);
#ifdef DBG #ifndef NDEBUG
printf("Received packet\n"); printf("Received packet\n");
DisplayBuffer(Buffer, Status); DisplayBuffer(Buffer, Status);
printf("\n"); printf("\n");
#endif /* DBG */ #endif /* !NDEBUG */
} }
if (Status == SOCKET_ERROR) { if (Status == SOCKET_ERROR)
if (WSAGetLastError() != WSAETIMEDOUT) { {
if (WSAGetLastError() != WSAETIMEDOUT)
{
printf("Could not receive data (%d).\n", WSAGetLastError()); printf("Could not receive data (%d).\n", WSAGetLastError());
GlobalFree(Buffer); GlobalFree(Buffer);
return FALSE; return FALSE;
@ -556,14 +578,16 @@ static BOOL Ping(VOID)
Status = 0; Status = 0;
} }
if (Status == 0) { if (Status == 0)
{
printf("Request timed out.\n"); printf("Request timed out.\n");
LostCount++; LostCount++;
GlobalFree(Buffer); GlobalFree(Buffer);
return TRUE; return TRUE;
} }
if (!DecodeResponse(Buffer, Status, (PSOCKADDR_IN)&From)) { if (!DecodeResponse(Buffer, Status, (PSOCKADDR_IN)&From))
{
/* FIXME: Wait again as it could be another ICMP message type */ /* FIXME: Wait again as it could be another ICMP message type */
printf("Request timed out (incomplete datagram received).\n"); printf("Request timed out (incomplete datagram received).\n");
LostCount++; LostCount++;
@ -584,13 +608,15 @@ int main(int argc, char* argv[])
Reset(); Reset();
if ((ParseCmdline(argc, argv)) && (Setup())) { if ((ParseCmdline(argc, argv)) && (Setup()))
{
printf("\nPinging %s [%s] with %d bytes of data:\n\n", printf("\nPinging %s [%s] with %d bytes of data:\n\n",
TargetName, TargetIP, DataSize); TargetName, TargetIP, DataSize);
Count = 0; Count = 0;
while ((NeverStop) || (Count < PingCount)) { while ((NeverStop) || (Count < PingCount))
{
Ping(); Ping();
Sleep(Timeout); Sleep(Timeout);
Count++; Count++;
@ -599,11 +625,10 @@ int main(int argc, char* argv[])
Cleanup(); Cleanup();
/* Calculate avarage round trip time */ /* Calculate avarage round trip time */
if ((SentCount - LostCount) > 0) { if ((SentCount - LostCount) > 0)
AvgRTT.QuadPart = SumRTT.QuadPart / (SentCount - LostCount); AvgRTT.QuadPart = SumRTT.QuadPart / (SentCount - LostCount);
} else { else
AvgRTT.QuadPart = 0; AvgRTT.QuadPart = 0;
}
/* Calculate loss percent */ /* Calculate loss percent */
Count = SentCount ? (LostCount * 100) / SentCount : 0; Count = SentCount ? (LostCount * 100) / SentCount : 0;