From 9825a8d59b1fe3003fd41983c6811df923378e0e Mon Sep 17 00:00:00 2001 From: David Auer Date: Thu, 26 Jan 2023 15:21:31 +0100 Subject: [PATCH 1/4] Add clang format from colorchord --- .clang-format | 1 + .gitmodules | 4 ++++ clang-format | 1 + 3 files changed, 6 insertions(+) create mode 120000 .clang-format create mode 160000 clang-format diff --git a/.clang-format b/.clang-format new file mode 120000 index 0000000..7318fca --- /dev/null +++ b/.clang-format @@ -0,0 +1 @@ +clang-format/.clang-format \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index f5e47f9..0dfce43 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,7 @@ [submodule "rawdraw"] path = rawdraw url = https://github.com/cntools/rawdraw +[submodule "clang-format"] + path = clang-format + url = git@github.com:dreua/colorchord.git + branch = clang-format-only diff --git a/clang-format b/clang-format new file mode 160000 index 0000000..97a023b --- /dev/null +++ b/clang-format @@ -0,0 +1 @@ +Subproject commit 97a023b7dd3573454adbbc6d8d83ee11ba713ac0 From 5512d55199dd0a0d9a7c99b0b83bd0b0ea551cb0 Mon Sep 17 00:00:00 2001 From: David Auer Date: Thu, 26 Jan 2023 15:50:32 +0100 Subject: [PATCH 2/4] Add formatting target to makefile --- Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Makefile b/Makefile index 8c9a3c1..b9fdc28 100644 --- a/Makefile +++ b/Makefile @@ -14,6 +14,8 @@ clean : rm -rf *.o *~ cnping cnping.exe cnping_mac searchnet rm -rf rawdraw/*.o +format-all: + find . -iname "*.h" -o -iname "*.c" | xargs clang-format -i # Windows From b287c41e5240e4e9f6780a53116a2701aa1cc601 Mon Sep 17 00:00:00 2001 From: David Auer Date: Thu, 26 Jan 2023 15:50:45 +0100 Subject: [PATCH 3/4] First round of formatting --- cnping.c | 670 +++++++++++++++++++++++++--------------------------- httping.c | 197 ++++++++------- ping.c | 374 ++++++++++++++--------------- resolve.c | 55 +++-- searchnet.c | 76 +++--- 5 files changed, 678 insertions(+), 694 deletions(-) diff --git a/cnping.c b/cnping.c index c70a40b..1266da5 100644 --- a/cnping.c +++ b/cnping.c @@ -1,11 +1,11 @@ -//Copyright (c) 2011-2019 <>< Charles Lohr - Under the MIT/x11 or NewBSD License you choose. +// Copyright (c) 2011-2019 <>< Charles Lohr - Under the MIT/x11 or NewBSD License you choose. #define VERSION "1.0.0" +#include +#include #include #include -#include -#include #include #if defined( WINDOWS ) || defined( WIN32 ) #ifdef _MSC_VER @@ -13,16 +13,16 @@ #endif #include #else - #ifdef __FreeBSD__ - #include - #include - #endif -#include +#ifdef __FreeBSD__ +#include +#include +#endif +#include +#include #include #include -#include #include -#include +#include #endif #ifndef CNFGOGL @@ -30,36 +30,38 @@ #endif #define CNFG_IMPLEMENTATION -#include "rawdraw/os_generic.h" -#include "rawdraw/CNFG.h" -#include "ping.h" #include "error_handling.h" #include "httping.h" +#include "ping.h" +#include "rawdraw/CNFG.h" +#include "rawdraw/os_generic.h" // #### Cross-plattform debugging #### // Windows does not print to Console, use DebugView from SysInternals to // see the output. (Setup: Computer -> Connect Local; Capture -> Capture Win32) // Warning: Debugging on Windows can slow cnping down and lead to wrong measurements! -//#define DEBUG +// #define DEBUG #ifdef DEBUG - char msgbuf[1024]; - #ifdef WIN32 - #define debug(...) \ - snprintf(msgbuf, sizeof(msgbuf), __VA_ARGS__); \ - OutputDebugString(msgbuf); - #else - #define debug(...) printf(__VA_ARGS__); - #endif +char msgbuf[ 1024 ]; +#ifdef WIN32 +#define debug( ... ) \ + snprintf( msgbuf, sizeof( msgbuf ), __VA_ARGS__ ); \ + OutputDebugString( msgbuf ); +#else +#define debug( ... ) printf( __VA_ARGS__ ); +#endif #else - // Let the compiler parse it to catch errors. Compiler will optimize away. - #define debug(...) \ - do { if (0) fprintf(stderr, __VA_ARGS__); } while (0); +// Let the compiler parse it to catch errors. Compiler will optimize away. +#define debug( ... ) \ + do { \ + if ( 0 ) fprintf( stderr, __VA_ARGS__ ); \ + } while ( 0 ); #endif unsigned frames = 0; unsigned long iframeno = 0; short screenx, screeny; -const char * pinghost; +const char *pinghost; float GuiYScaleFactor; int GuiYscaleFactorIsConstant; double globmaxtime, globmintime = 1e20; @@ -67,13 +69,13 @@ double globinterval, globlast; uint64_t globalrx; uint64_t globallost; // Ping Data. Will be overwritten with random bytes when !DEBUG -uint8_t pattern[8] = {0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF}; +uint8_t pattern[ 8 ] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF }; #define PINGCYCLEWIDTH 8192 #define TIMEOUT 4 -double PingSendTimes[PINGCYCLEWIDTH]; -double PingRecvTimes[PINGCYCLEWIDTH]; +double PingSendTimes[ PINGCYCLEWIDTH ]; +double PingRecvTimes[ PINGCYCLEWIDTH ]; int current_cycle = 0; int ExtraPingSize; @@ -85,24 +87,24 @@ WSADATA wsaData; #endif -#define MAX_HISTO_MARKS (TIMEOUT*10000) -uint64_t hist_counts[MAX_HISTO_MARKS]; +#define MAX_HISTO_MARKS ( TIMEOUT * 10000 ) +uint64_t hist_counts[ MAX_HISTO_MARKS ]; void HandleNewPacket( int seqno ) { double Now = OGGetAbsoluteTime(); - PingSendTimes[seqno] = Now; - PingRecvTimes[seqno] = 0; + PingSendTimes[ seqno ] = Now; + PingRecvTimes[ seqno ] = 0; static int timeoutmark; - while( Now - PingSendTimes[timeoutmark] > TIMEOUT ) + while ( Now - PingSendTimes[ timeoutmark ] > TIMEOUT ) { - if( PingRecvTimes[timeoutmark] < PingSendTimes[timeoutmark] ) + if ( PingRecvTimes[ timeoutmark ] < PingSendTimes[ timeoutmark ] ) { HandleGotPacket( timeoutmark, 1 ); } timeoutmark++; - if( timeoutmark >= PINGCYCLEWIDTH ) timeoutmark = 0; + if ( timeoutmark >= PINGCYCLEWIDTH ) timeoutmark = 0; } } @@ -110,32 +112,32 @@ void HandleGotPacket( int seqno, int timeout ) { double Now = OGGetAbsoluteTime(); - if( timeout ) + if ( timeout ) { - if( PingRecvTimes[seqno] < -0.5 ) return; + if ( PingRecvTimes[ seqno ] < -0.5 ) return; globallost++; - PingRecvTimes[seqno] = -1; - hist_counts[MAX_HISTO_MARKS-1]++; + PingRecvTimes[ seqno ] = -1; + hist_counts[ MAX_HISTO_MARKS - 1 ]++; return; } - if( PingRecvTimes[seqno] >= PingSendTimes[seqno] ) return; - if( PingSendTimes[seqno] < 1 ) return; - if( Now - PingSendTimes[seqno] > TIMEOUT ) return; + if ( PingRecvTimes[ seqno ] >= PingSendTimes[ seqno ] ) return; + if ( PingSendTimes[ seqno ] < 1 ) return; + if ( Now - PingSendTimes[ seqno ] > TIMEOUT ) return; - PingRecvTimes[seqno] = OGGetAbsoluteTime(); - double Delta = PingRecvTimes[seqno] - PingSendTimes[seqno]; - if( Delta > globmaxtime ) { globmaxtime = Delta; } - if( Delta < globmintime ) { globmintime = Delta; } + PingRecvTimes[ seqno ] = OGGetAbsoluteTime(); + double Delta = PingRecvTimes[ seqno ] - PingSendTimes[ seqno ]; + if ( Delta > globmaxtime ) { globmaxtime = Delta; } + if ( Delta < globmintime ) { globmintime = Delta; } int slot = Delta * 10000; - if( slot >= MAX_HISTO_MARKS ) slot = MAX_HISTO_MARKS-1; - if( slot < 0 ) slot = 0; - hist_counts[slot]++; + if ( slot >= MAX_HISTO_MARKS ) slot = MAX_HISTO_MARKS - 1; + if ( slot < 0 ) slot = 0; + hist_counts[ slot ]++; - if( globlast > 0.5 ) + if ( globlast > 0.5 ) { - if( Now - globlast > globinterval ) globinterval = Now - globlast; + if ( Now - globlast > globinterval ) globinterval = Now - globlast; } globlast = Now; globalrx++; @@ -153,67 +155,66 @@ void HTTPingCallbackGot( int seqno ) HandleGotPacket( seqno, 0 ); } -void display(uint8_t *buf, int bytes) +void display( uint8_t *buf, int bytes ) { - int reqid = (buf[0] << 24) | (buf[1]<<16) | (buf[2]<<8) | (buf[3]); - debug("Received ping: reqid=%d\n", reqid); - reqid &= (PINGCYCLEWIDTH-1); - if( memcmp( buf+4, pattern, sizeof(pattern) ) != 0 ) return; - debug("Memcmp OK, checked %ld bytes, first values being %x %x %x %x\n", - (long int) sizeof(pattern), pattern[0], pattern[1], pattern[2], pattern[3]) - HandleGotPacket( reqid, 0 ); + int reqid = ( buf[ 0 ] << 24 ) | ( buf[ 1 ] << 16 ) | ( buf[ 2 ] << 8 ) | ( buf[ 3 ] ); + debug( "Received ping: reqid=%d\n", reqid ); + reqid &= ( PINGCYCLEWIDTH - 1 ); + if ( memcmp( buf + 4, pattern, sizeof( pattern ) ) != 0 ) return; + debug( "Memcmp OK, checked %ld bytes, first values being %x %x %x %x\n", + (long int)sizeof( pattern ), pattern[ 0 ], pattern[ 1 ], pattern[ 2 ], pattern[ 3 ] ) + HandleGotPacket( reqid, 0 ); } -int load_ping_packet( uint8_t * buffer, int bufflen ) +int load_ping_packet( uint8_t *buffer, int bufflen ) { - buffer[0] = current_cycle >> 24; - buffer[1] = current_cycle >> 16; - buffer[2] = current_cycle >> 8; - buffer[3] = current_cycle >> 0; + buffer[ 0 ] = current_cycle >> 24; + buffer[ 1 ] = current_cycle >> 16; + buffer[ 2 ] = current_cycle >> 8; + buffer[ 3 ] = current_cycle >> 0; - memcpy( buffer+4, pattern, sizeof(pattern) ); + memcpy( buffer + 4, pattern, sizeof( pattern ) ); - if( ping_failed_to_send ) + if ( ping_failed_to_send ) { - PingSendTimes[(current_cycle+PINGCYCLEWIDTH-1)&(PINGCYCLEWIDTH-1)] = 0; //Unset ping send. + PingSendTimes[ ( current_cycle + PINGCYCLEWIDTH - 1 ) & ( PINGCYCLEWIDTH - 1 ) ] = + 0; // Unset ping send. } - HandleNewPacket( current_cycle&(PINGCYCLEWIDTH-1) ); + HandleNewPacket( current_cycle & ( PINGCYCLEWIDTH - 1 ) ); current_cycle++; return 12 + ExtraPingSize; } -void * PingListen( void * r ) +void *PingListen( void *r ) { listener(); ERRM( "Fault on listen.\n" ); exit( -2 ); } -void * PingSend( void * r ) +void *PingSend( void *r ) { - do_pinger( ); + do_pinger(); ERRM( "Fault on ping.\n" ); exit( -1 ); } - - void HandleKey( int keycode, int bDown ) { - switch( keycode ) + switch ( keycode ) { #if defined( WIN32 ) || defined( WINDOWS ) case 'r': { - char lpFilename[1024]; - char lpDirectory[1024]; + char lpFilename[ 1024 ]; + char lpDirectory[ 1024 ]; GetCurrentDirectory( 1023, lpDirectory ); - GetModuleFileNameA( GetModuleHandle(0), lpFilename, 1023 ); + GetModuleFileNameA( GetModuleHandle( 0 ), lpFilename, 1023 ); CreateProcessA( lpFilename, GetCommandLine(), 0, 0, 1, 0, 0, lpDirectory, 0, 0 ); exit( 0 ); @@ -221,12 +222,12 @@ void HandleKey( int keycode, int bDown ) } #endif case 'f': - if( bDown ) in_frame_mode = !in_frame_mode; - if( !in_frame_mode ) in_histogram_mode = 1; + if ( bDown ) in_frame_mode = !in_frame_mode; + if ( !in_frame_mode ) in_histogram_mode = 1; break; - case 'm': - if( bDown ) in_histogram_mode = !in_histogram_mode; - if( !in_histogram_mode ) in_frame_mode = 1; + case 'm': + if ( bDown ) in_histogram_mode = !in_histogram_mode; + if ( !in_histogram_mode ) in_frame_mode = 1; break; case 'c': memset( hist_counts, 0, sizeof( hist_counts ) ); @@ -237,15 +238,19 @@ void HandleKey( int keycode, int bDown ) globalrx = 0; globallost = 0; break; - case 'q': - exit(0); - break; - + case 'q': exit( 0 ); break; } } -void HandleButton( int x, int y, int button, int bDown ){} -void HandleMotion( int x, int y, int mask ){} -void HandleDestroy() { exit(0); } +void HandleButton( int x, int y, int button, int bDown ) +{ +} +void HandleMotion( int x, int y, int mask ) +{ +} +void HandleDestroy() +{ + exit( 0 ); +} double GetWindMaxPingTime( void ) @@ -253,145 +258,131 @@ double GetWindMaxPingTime( void ) int i; double maxtime = 0; - for( i = 0; i < screenx; i++ ) + for ( i = 0; i < screenx; i++ ) { - int index = ((current_cycle - i - 1) + PINGCYCLEWIDTH) & (PINGCYCLEWIDTH-1); - double st = PingSendTimes[index]; - double rt = PingRecvTimes[index]; + int index = ( ( current_cycle - i - 1 ) + PINGCYCLEWIDTH ) & ( PINGCYCLEWIDTH - 1 ); + double st = PingSendTimes[ index ]; + double rt = PingRecvTimes[ index ]; double dt = 0; - if( rt > st ) + if ( rt > st ) { dt = rt - st; dt *= 1000; - if( dt > maxtime ) maxtime = dt; + if ( dt > maxtime ) maxtime = dt; } } return maxtime; } -void DrawMainText( const char * stbuf ) +void DrawMainText( const char *stbuf ) { int x, y; CNFGColor( 0x000000ff ); - for( x = -1; x < 2; x++ ) for( y = -1; y < 2; y++ ) - { - CNFGPenX = 10+x; CNFGPenY = 10+y; - CNFGDrawText( stbuf, 2 ); - } + for ( x = -1; x < 2; x++ ) + for ( y = -1; y < 2; y++ ) + { + CNFGPenX = 10 + x; + CNFGPenY = 10 + y; + CNFGDrawText( stbuf, 2 ); + } CNFGColor( 0xffffffff ); - CNFGPenX = 10; CNFGPenY = 10; + CNFGPenX = 10; + CNFGPenY = 10; CNFGDrawText( stbuf, 2 ); } void DrawFrameHistogram() { int i; -// double Now = OGGetAbsoluteTime(); + // double Now = OGGetAbsoluteTime(); const int colwid = 50; - int categories = (screenx-50)/colwid; - int maxpingslot = ( globmaxtime*10000.0 ); - int minpingslot = ( globmintime*10000.0 ); - int slots = maxpingslot-minpingslot; + int categories = ( screenx - 50 ) / colwid; + int maxpingslot = ( globmaxtime * 10000.0 ); + int minpingslot = ( globmintime * 10000.0 ); + int slots = maxpingslot - minpingslot; - if( categories <= 2 ) - { - goto nodata; - } + if ( categories <= 2 ) { goto nodata; } else { - int skips = ( (slots)/categories ) + 1; + int skips = ( ( slots ) / categories ) + 1; int slotsmax = maxpingslot / skips + 1; int slotsmin = minpingslot / skips; slots = slotsmax - slotsmin; - if( slots <= 0 ) goto nodata; + if ( slots <= 0 ) goto nodata; - uint64_t samples[slots+2]; - int ssmsMIN[slots+2]; - int ssmsMAX[slots+2]; + uint64_t samples[ slots + 2 ]; + int ssmsMIN[ slots + 2 ]; + int ssmsMAX[ slots + 2 ]; int samp = minpingslot - 1; - if( slots <= 1 ) goto nodata; + if ( slots <= 1 ) goto nodata; memset( samples, 0, sizeof( samples ) ); - if( samp < 0 ) samp = 0; + if ( samp < 0 ) samp = 0; uint64_t highestchart = 0; int tslot = 0; - for( i = slotsmin; i <= slotsmax; i++ ) + for ( i = slotsmin; i <= slotsmax; i++ ) { int j; uint64_t total = 0; - ssmsMIN[tslot] = samp; - for( j = 0; j < skips; j++ ) - { - total += hist_counts[samp++]; - } + ssmsMIN[ tslot ] = samp; + for ( j = 0; j < skips; j++ ) { total += hist_counts[ samp++ ]; } - ssmsMAX[tslot] = samp; - if( total > highestchart ) highestchart = total; - samples[tslot++] = total; + ssmsMAX[ tslot ] = samp; + if ( total > highestchart ) highestchart = total; + samples[ tslot++ ] = total; } - if( highestchart <= 0 ) - { - goto nodata; - } + if ( highestchart <= 0 ) { goto nodata; } int rslots = 0; - for( i = 0; i < slots+1; i++ ) + for ( i = 0; i < slots + 1; i++ ) { - if( samples[i] ) rslots = i; + if ( samples[ i ] ) rslots = i; } rslots++; - for( i = 0; i < rslots; i++ ) + for ( i = 0; i < rslots; i++ ) { CNFGColor( 0x33cc33ff ); int top = 30; - uint64_t samps = samples[i]; + uint64_t samps = samples[ i ]; int bottom = screeny - 50; - int height = samps?(samps * (bottom-top) / highestchart + 1):0; - int startx = (i+1) * (screenx-50) / rslots; - int endx = (i+2) * (screenx-50) / rslots; + int height = samps ? ( samps * ( bottom - top ) / highestchart + 1 ) : 0; + int startx = ( i + 1 ) * ( screenx - 50 ) / rslots; + int endx = ( i + 2 ) * ( screenx - 50 ) / rslots; - if( !in_frame_mode ) + if ( !in_frame_mode ) { - CNFGTackRectangle( startx, bottom-height, endx, bottom + 1 ); + CNFGTackRectangle( startx, bottom - height, endx, bottom + 1 ); CNFGColor( 0x000000ff ); } - else - { - CNFGColor( 0x8080ffff ); - } - CNFGTackSegment( startx, bottom+1, endx, bottom+1 ); + else { CNFGColor( 0x8080ffff ); } + CNFGTackSegment( startx, bottom + 1, endx, bottom + 1 ); - CNFGTackSegment( startx, bottom-height, startx, bottom+1 ); - CNFGTackSegment( endx, bottom-height, endx, bottom+1 ); + CNFGTackSegment( startx, bottom - height, startx, bottom + 1 ); + CNFGTackSegment( endx, bottom - height, endx, bottom + 1 ); - CNFGTackSegment( startx, bottom-height, endx, bottom-height ); - char stbuf[1024]; + CNFGTackSegment( startx, bottom - height, endx, bottom - height ); + char stbuf[ 1024 ]; int log10 = 1; int64_t ll = samps; - while( ll >= 10 ) + while ( ll >= 10 ) { ll /= 10; log10++; } - if( !in_frame_mode ) - { - CNFGColor( 0xffffffff ); - } - else - { - CNFGColor( 0x8080ffff ); - } + if ( !in_frame_mode ) { CNFGColor( 0xffffffff ); } + else { CNFGColor( 0x8080ffff ); } - CNFGPenX = startx + (8-log10) * 4; CNFGPenY = bottom+3; + CNFGPenX = startx + ( 8 - log10 ) * 4; + CNFGPenY = bottom + 3; #ifdef WIN32 sprintf( stbuf, "%I64u", samps ); #else @@ -399,19 +390,24 @@ void DrawFrameHistogram() #endif CNFGDrawText( stbuf, 2 ); - CNFGPenX = startx; CNFGPenY = bottom+14; - sprintf( stbuf, "%5.1fms\n%5.1fms", ssmsMIN[i]/10.0, ssmsMAX[i]/10.0 ); + CNFGPenX = startx; + CNFGPenY = bottom + 14; + sprintf( stbuf, "%5.1fms\n%5.1fms", ssmsMIN[ i ] / 10.0, ssmsMAX[ i ] / 10.0 ); CNFGDrawText( stbuf, 2 ); } - char stt[1024]; + char stt[ 1024 ]; #ifdef WIN32 - snprintf( stt, 1024, "Host: %s\nHistorical max %9.2fms\nBiggest interval%9.2fms\nHistorical packet loss %I64u/%I64u = %6.3f%%", + snprintf( stt, 1024, + "Host: %s\nHistorical max %9.2fms\nBiggest interval%9.2fms\nHistorical packet loss " + "%I64u/%I64u = %6.3f%%", #else - snprintf( stt, 1024, "Host: %s\nHistorical max %9.2fms\nBiggest interval%9.2fms\nHistorical packet loss %lu/%lu = %6.3f%%", + snprintf( stt, 1024, + "Host: %s\nHistorical max %9.2fms\nBiggest interval%9.2fms\nHistorical packet loss " + "%lu/%lu = %6.3f%%", #endif - pinghost, globmaxtime*1000.0, globinterval*1000.0, globallost, globalrx, globallost*100.0/(globalrx+globallost) ); - if( !in_frame_mode ) - DrawMainText( stt ); + pinghost, globmaxtime * 1000.0, globinterval * 1000.0, globallost, globalrx, + globallost * 100.0 / ( globalrx + globallost ) ); + if ( !in_frame_mode ) DrawMainText( stt ); return; } nodata: @@ -436,32 +432,31 @@ void DrawFrame( void ) double loss = 100.00; double windmaxtime = GetWindMaxPingTime(); - for( i = 0; i < screenx; i++ ) + for ( i = 0; i < screenx; i++ ) { - int index = ((current_cycle - i - 1) + PINGCYCLEWIDTH) & (PINGCYCLEWIDTH-1); - double st = PingSendTimes[index]; - double rt = PingRecvTimes[index]; + int index = ( ( current_cycle - i - 1 ) + PINGCYCLEWIDTH ) & ( PINGCYCLEWIDTH - 1 ); + double st = PingSendTimes[ index ]; + double rt = PingRecvTimes[ index ]; double dt = 0; - if( rt > st ) // ping received + if ( rt > st ) // ping received { CNFGColor( 0xffffffff ); dt = rt - st; dt *= 1000; totaltime += dt; - if( dt < mintime ) mintime = dt; - if( dt > maxtime ) maxtime = dt; + if ( dt < mintime ) mintime = dt; + if ( dt > maxtime ) maxtime = dt; totalcountok++; - if( last < 0) - last = dt; + if ( last < 0 ) last = dt; } - else if (st != 0) // ping sent but not received + else if ( st != 0 ) // ping sent but not received { CNFGColor( 0xff0000ff ); dt = now - st; dt *= 1000; - if( i > 5 ) totalcountloss++; //Get a freebie on the first 5. + if ( i > 5 ) totalcountloss++; // Get a freebie on the first 5. } else // no ping sent for this point in time (after startup) { @@ -469,56 +464,53 @@ void DrawFrame( void ) dt = 99 * 1000; // assume 99s to fill screen black } - if (!GuiYscaleFactorIsConstant) - { - GuiYScaleFactor = (screeny - 50) / windmaxtime; - } + if ( !GuiYscaleFactorIsConstant ) { GuiYScaleFactor = ( screeny - 50 ) / windmaxtime; } - int h = dt*GuiYScaleFactor; + int h = dt * GuiYScaleFactor; int top = screeny - h; - if( top < 0 ) top = 0; - CNFGTackSegment( i, screeny-1, i, top ); + if ( top < 0 ) top = 0; + CNFGTackSegment( i, screeny - 1, i, top ); } double avg = totaltime / totalcountok; - loss = (double) totalcountloss / (totalcountok + totalcountloss) * 100; + loss = (double)totalcountloss / ( totalcountok + totalcountloss ) * 100; - for( i = 0; i < screenx; i++ ) + for ( i = 0; i < screenx; i++ ) { - int index = ((current_cycle - i - 1) + PINGCYCLEWIDTH) & (PINGCYCLEWIDTH-1); - double st = PingSendTimes[index]; - double rt = PingRecvTimes[index]; + int index = ( ( current_cycle - i - 1 ) + PINGCYCLEWIDTH ) & ( PINGCYCLEWIDTH - 1 ); + double st = PingSendTimes[ index ]; + double rt = PingRecvTimes[ index ]; double dt = 0; - if( rt > st ) + if ( rt > st ) { dt = rt - st; dt *= 1000; - stddev += (dt-avg)*(dt-avg); + stddev += ( dt - avg ) * ( dt - avg ); } } stddev /= totalcountok; - stddev = sqrt(stddev); + stddev = sqrt( stddev ); - int avg_gui = avg*GuiYScaleFactor; - int stddev_gui = stddev*GuiYScaleFactor; + int avg_gui = avg * GuiYScaleFactor; + int stddev_gui = stddev * GuiYScaleFactor; CNFGColor( 0x00ff00ff ); int l = avg_gui; - CNFGTackSegment( 0, screeny-l, screenx, screeny - l ); - l = (avg_gui) + (stddev_gui); - CNFGTackSegment( 0, screeny-l, screenx, screeny - l ); - l = (avg_gui) - (stddev_gui); - CNFGTackSegment( 0, screeny-l, screenx, screeny - l ); + CNFGTackSegment( 0, screeny - l, screenx, screeny - l ); + l = ( avg_gui ) + ( stddev_gui ); + CNFGTackSegment( 0, screeny - l, screenx, screeny - l ); + l = ( avg_gui ) - ( stddev_gui ); + CNFGTackSegment( 0, screeny - l, screenx, screeny - l ); - char stbuf[2048]; - char * sptr = &stbuf[0]; + char stbuf[ 2048 ]; + char *sptr = &stbuf[ 0 ]; - sptr += sprintf( sptr, + sptr += sprintf( sptr, "Last:%6.2f ms Host: %s\n" "Min :%6.2f ms\n" "Max :%6.2f ms Historical max: %5.2f ms\n" @@ -528,8 +520,9 @@ void DrawFrame( void ) #else "Std :%6.2f ms Historical loss: %lu/%lu %5.3f%%\n" #endif - "Loss:%6.1f %%", last, pinghost, mintime, maxtime, globmaxtime*1000, avg, globinterval*1000.0, stddev, - globallost, globalrx, globallost*100.0f/(globalrx+globallost), loss ); + "Loss:%6.1f %%", + last, pinghost, mintime, maxtime, globmaxtime * 1000, avg, globinterval * 1000.0, stddev, + globallost, globalrx, globallost * 100.0f / ( globalrx + globallost ), loss ); DrawMainText( stbuf ); OGUSleep( 1000 ); @@ -537,25 +530,25 @@ void DrawFrame( void ) #ifdef WIN32 -const char * glargv[10]; +const char *glargv[ 10 ]; int glargc = 0; -int RegString( int write, char * data, DWORD len ) +int RegString( int write, char *data, DWORD len ) { HKEY hKey; - if( RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\cnping", 0, NULL, - REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL) == ERROR_SUCCESS) + if ( RegCreateKeyExA( HKEY_CURRENT_USER, "Software\\cnping", 0, NULL, REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, NULL, &hKey, NULL ) == ERROR_SUCCESS ) { - if( write ) + if ( write ) { - RegSetValueExA( hKey, "history", 0, REG_SZ, (uint8_t*)data, len ); + RegSetValueExA( hKey, "history", 0, REG_SZ, (uint8_t *)data, len ); return 0; } else { DWORD type; - if( RegGetValueA( hKey, "", "history", 0x02, &type, data, &len ) == ERROR_SUCCESS ) - { + if ( RegGetValueA( hKey, "", "history", 0x02, &type, data, &len ) == ERROR_SUCCESS ) + { return 0; } return -16; @@ -563,113 +556,107 @@ int RegString( int write, char * data, DWORD len ) RegCloseKey( hKey ); } - else - { - return -15; - } + else { return -15; } } -INT_PTR CALLBACK TextEntry( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) +INT_PTR CALLBACK TextEntry( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - switch( uMsg ) + switch ( uMsg ) { - case WM_INITDIALOG: - SetDlgItemText(hwndDlg, 4, "0.02"); - SetDlgItemText(hwndDlg, 5, "0" ); + case WM_INITDIALOG: + SetDlgItemText( hwndDlg, 4, "0.02" ); + SetDlgItemText( hwndDlg, 5, "0" ); - char data[1024]; - if( !RegString( 0, data, sizeof( data ) ) ) - { - SetDlgItemText(hwndDlg, 3, data); - } + char data[ 1024 ]; + if ( !RegString( 0, data, sizeof( data ) ) ) { SetDlgItemText( hwndDlg, 3, data ); } - return 0; - case WM_COMMAND: - switch( wParam>>24 ) - { - case 4: case 3: return 0; //keyboard input - case 1: case 2: return 0; //focus changed. - case 0: + return 0; + case WM_COMMAND: + switch ( wParam >> 24 ) { - int id = wParam & 0xffffff; - if( id == 8 || id == 2 ) - { - exit( -1 ); - } - - char Address[128]; GetDlgItemText(hwndDlg, 3, Address, sizeof(Address)); - char Period[128]; GetDlgItemText(hwndDlg, 4, Period, sizeof(Period)); - char Extra[128]; GetDlgItemText(hwndDlg, 5, Extra, sizeof(Extra)); - char Scaling[128]; GetDlgItemText(hwndDlg, 6, Scaling, sizeof(Scaling)); - - if( strlen( Address ) ) + case 4: + case 3: return 0; // keyboard input + case 1: + case 2: return 0; // focus changed. + case 0: { - RegString( 1, Address, strlen( Address ) ); - - glargc = 2; - glargv[1] = strdup( Address ); - if( strlen( Period ) ) + int id = wParam & 0xffffff; + if ( id == 8 || id == 2 ) { exit( -1 ); } + + char Address[ 128 ]; + GetDlgItemText( hwndDlg, 3, Address, sizeof( Address ) ); + char Period[ 128 ]; + GetDlgItemText( hwndDlg, 4, Period, sizeof( Period ) ); + char Extra[ 128 ]; + GetDlgItemText( hwndDlg, 5, Extra, sizeof( Extra ) ); + char Scaling[ 128 ]; + GetDlgItemText( hwndDlg, 6, Scaling, sizeof( Scaling ) ); + + if ( strlen( Address ) ) { - glargc = 3; - glargv[2] = strdup( Period ); - if( strlen( Extra ) ) + RegString( 1, Address, strlen( Address ) ); + + glargc = 2; + glargv[ 1 ] = strdup( Address ); + if ( strlen( Period ) ) { - glargc = 4; - glargv[3] = strdup( Extra ); - if( strlen( Scaling ) ) + glargc = 3; + glargv[ 2 ] = strdup( Period ); + if ( strlen( Extra ) ) { - glargc = 5; - glargv[4] = strdup( Scaling ); + glargc = 4; + glargv[ 3 ] = strdup( Extra ); + if ( strlen( Scaling ) ) + { + glargc = 5; + glargv[ 4 ] = strdup( Scaling ); + } } } } + EndDialog( hwndDlg, 0 ); + return 0; // User pressed enter. } - EndDialog(hwndDlg, 0); - return 0; //User pressed enter. } - } -/* return 0; - case WM_CTLCOLORBTN: - //printf( "ctr %p %p %p\n", uMsg, wParam, lParam ); - //return 0; - case 32: case 512: case 132: case 24: case 70: - case 127: case 783: case 28: case 134: case 6: case 7: - case 8: case 312: case 15: case 71: case 133: case 307: - case 20: case 310: case 33: - return 0; -*/ + /* return 0; + case WM_CTLCOLORBTN: + //printf( "ctr %p %p %p\n", uMsg, wParam, lParam ); + //return 0; + case 32: case 512: case 132: case 24: case 70: + case 127: case 783: case 28: case 134: case 6: case 7: + case 8: case 312: case 15: case 71: case 133: case 307: + case 20: case 310: case 33: + return 0; + */ } return 0; } #endif -int main( int argc, const char ** argv ) +int main( int argc, const char **argv ) { - char title[1024]; + char title[ 1024 ]; int i; double ThisTime; double LastFPSTime = OGGetAbsoluteTime(); double LastFrameTime = OGGetAbsoluteTime(); double SecToWait; double frameperiodseconds; - const char * device = NULL; + const char *device = NULL; #ifdef WIN32 - ShowWindow (GetConsoleWindow(), SW_HIDE); + ShowWindow( GetConsoleWindow(), SW_HIDE ); #endif - srand( (uintmax_t)(OGGetAbsoluteTime()*100000) ); - #ifndef DEBUG - for( i = 0; i < sizeof( pattern ); i++ ) - { - pattern[i] = rand(); - } - #endif + srand( (uintmax_t)( OGGetAbsoluteTime() * 100000 ) ); +#ifndef DEBUG + for ( i = 0; i < sizeof( pattern ); i++ ) { pattern[ i ] = rand(); } +#endif CNFGBGColor = 0x000080ff; #ifdef WIN32 - if( argc < 2 ) + if ( argc < 2 ) { - DialogBox(0, "IPDialog", 0, TextEntry ); + DialogBox( 0, "IPDialog", 0, TextEntry ); argc = glargc; argv = glargv; } @@ -677,33 +664,33 @@ int main( int argc, const char ** argv ) pingperiodseconds = 0.02; ExtraPingSize = 0; - title[0] = 0; + title[ 0 ] = 0; GuiYScaleFactor = 0; - //We need to process all the unmarked parameters. + // We need to process all the unmarked parameters. int argcunmarked = 1; int displayhelp = 0; - for( i = 1; i < argc; i++ ) + for ( i = 1; i < argc; i++ ) { - const char * thisargv = argv[i]; - if( thisargv[0] == '-' ) + const char *thisargv = argv[ i ]; + if ( thisargv[ 0 ] == '-' ) { int np = ++i; - if( np >= argc ) + if ( np >= argc ) { displayhelp = 1; break; } - const char * nextargv = argv[np]; - //Parameter-based field. - switch( thisargv[1] ) + const char *nextargv = argv[ np ]; + // Parameter-based field. + switch ( thisargv[ 1 ] ) { case 'h': pinghost = nextargv; break; case 'p': pingperiodseconds = atof( nextargv ); break; case 's': ExtraPingSize = atoi( nextargv ); break; case 'y': GuiYScaleFactor = atof( nextargv ); break; - case 't': sprintf(title, "%s", nextargv); break; + case 't': sprintf( title, "%s", nextargv ); break; case 'm': in_histogram_mode = 1; break; case 'I': device = nextargv; break; default: displayhelp = 1; break; @@ -711,54 +698,49 @@ int main( int argc, const char ** argv ) } else { - //Unmarked fields - switch( argcunmarked++ ) + // Unmarked fields + switch ( argcunmarked++ ) { case 1: pinghost = thisargv; break; case 2: pingperiodseconds = atof( thisargv ); break; case 3: ExtraPingSize = atoi( thisargv ); break; case 4: GuiYScaleFactor = atof( thisargv ); break; - case 5: sprintf(title, "%s", thisargv ); break; + case 5: sprintf( title, "%s", thisargv ); break; default: displayhelp = 1; } } } - if( title[0] == 0 ) - { - sprintf( title, "%s - cnping "VERSION, pinghost ); - } + if ( title[ 0 ] == 0 ) { sprintf( title, "%s - cnping " VERSION, pinghost ); } - if( GuiYScaleFactor > 0 ) - { - GuiYscaleFactorIsConstant = 1; - } + if ( GuiYScaleFactor > 0 ) { GuiYscaleFactorIsConstant = 1; } - if( !pinghost ) - { - displayhelp = 1; - } + if ( !pinghost ) { displayhelp = 1; } - if( displayhelp ) + if ( displayhelp ) { - ERRM( "cnping "VERSION" Usage: cnping [host] [period] [extra size] [y-axis scaling] [window title]\n" - " (-h) [host] -- domain, IP address of ping target for ICMP or http host, i.e. http://google.com\n" - " (-p) [period] -- period in seconds (optional), default 0.02 \n" - " (-s) [extra size] -- ping packet extra size (above 12), optional, default = 0 \n" - " (-y) [const y-axis scaling] -- use a fixed scaling factor instead of auto scaling (optional)\n" - " (-t) [window title] -- the title of the window (optional)\n" - " (-I) [interface] -- Sets source interface (i.e. eth0)\n"); + ERRM( "cnping " VERSION + " Usage: cnping [host] [period] [extra size] [y-axis scaling] [window title]\n" + " (-h) [host] -- domain, IP address of ping target for ICMP or " + "http host, i.e. http://google.com\n" + " (-p) [period] -- period in seconds (optional), default 0.02 \n" + " (-s) [extra size] -- ping packet extra size (above 12), optional, " + "default = 0 \n" + " (-y) [const y-axis scaling] -- use a fixed scaling factor instead of auto " + "scaling (optional)\n" + " (-t) [window title] -- the title of the window (optional)\n" + " (-I) [interface] -- Sets source interface (i.e. eth0)\n" ); return -1; } #if defined( WIN32 ) || defined( WINDOWS ) - if(device) + if ( device ) { - ERRM("Error: Device option is not implemented on your platform. PRs welcome.\n"); + ERRM( "Error: Device option is not implemented on your platform. PRs welcome.\n" ); exit( -1 ); } - - if( WSAStartup(MAKEWORD(2,2), &wsaData) ) + + if ( WSAStartup( MAKEWORD( 2, 2 ), &wsaData ) ) { ERRM( "Fault in WSAStartup\n" ); exit( -2 ); @@ -767,21 +749,21 @@ int main( int argc, const char ** argv ) #else CNFGSetupWMClass( title, 320, 155, "cnping", "cnping" ); #endif - - if( memcmp( pinghost, "http://", 7 ) == 0 ) + + if ( memcmp( pinghost, "http://", 7 ) == 0 ) { - StartHTTPing( pinghost+7, pingperiodseconds, device ); + StartHTTPing( pinghost + 7, pingperiodseconds, device ); } else { - char* protoEnd = strstr( pinghost, "://" ); + char *protoEnd = strstr( pinghost, "://" ); if ( protoEnd ) { int protoSize = protoEnd - pinghost; - char protoBuffer[protoSize + 1]; + char protoBuffer[ protoSize + 1 ]; memcpy( protoBuffer, pinghost, protoSize ); - protoBuffer[protoSize] = '\0'; + protoBuffer[ protoSize ] = '\0'; ERRM( "Protocol \"%s\" is not supported\n", protoBuffer ); exit( -1 ); } @@ -792,9 +774,9 @@ int main( int argc, const char ** argv ) } - frameperiodseconds = fmin(.2, fmax(.03, pingperiodseconds)); + frameperiodseconds = fmin( .2, fmax( .03, pingperiodseconds ) ); - while(1) + while ( 1 ) { iframeno++; CNFGHandleInput(); @@ -803,17 +785,12 @@ int main( int argc, const char ** argv ) CNFGColor( 0xffffffff ); CNFGGetDimensions( &screenx, &screeny ); - if( in_frame_mode ) - { - DrawFrame(); - } + if ( in_frame_mode ) { DrawFrame(); } - if( in_histogram_mode ) - { - DrawFrameHistogram(); - } + if ( in_histogram_mode ) { DrawFrameHistogram(); } - CNFGPenX = 100; CNFGPenY = 100; + CNFGPenX = 100; + CNFGPenY = 100; CNFGColor( 0xff0000ff ); CNFGDrawText( errbuffer, 3 ); @@ -822,19 +799,18 @@ int main( int argc, const char ** argv ) CNFGSwapBuffers(); ThisTime = OGGetAbsoluteTime(); - if( ThisTime > LastFPSTime + 1 ) + if ( ThisTime > LastFPSTime + 1 ) { frames = 0; - LastFPSTime+=1; + LastFPSTime += 1; } SecToWait = frameperiodseconds - ( ThisTime - LastFrameTime ); LastFrameTime += frameperiodseconds; - //printf("iframeno = %d; SecToWait = %f; pingperiodseconds = %f; frameperiodseconds = %f \n", iframeno, SecToWait, pingperiodseconds, frameperiodseconds); - if( SecToWait > 0 ) - OGUSleep( (int)( SecToWait * 1000000 ) ); + // printf("iframeno = %d; SecToWait = %f; pingperiodseconds = %f; frameperiodseconds = %f + // \n", iframeno, SecToWait, pingperiodseconds, frameperiodseconds); + if ( SecToWait > 0 ) OGUSleep( (int)( SecToWait * 1000000 ) ); } - return(0); + return ( 0 ); } - diff --git a/httping.c b/httping.c index 14b569b..70f54b8 100644 --- a/httping.c +++ b/httping.c @@ -1,53 +1,54 @@ #include "httping.h" +#include "resolve.h" #include #include #include #include #include -#include "resolve.h" #ifndef TCC -#include #include +#include #else #include "tccheader.h" #endif #if defined( WIN32 ) || defined( WINDOWS ) - #ifdef TCC - #else - #include - #endif - #define SOL_TCP IPPROTO_TCP +#ifdef TCC #else - #include - #include - #include - #include +#include +#endif +#define SOL_TCP IPPROTO_TCP +#else +#include +#include +#include +#include #endif -#include "rawdraw/os_generic.h" #include "error_handling.h" +#include "rawdraw/os_generic.h" #ifndef MSG_NOSIGNAL - #define MSG_NOSIGNAL 0 +#define MSG_NOSIGNAL 0 #endif #define HTTPTIMEOUT 3.0 -//Callbacks (when started/received) +// Callbacks (when started/received) void HTTPingCallbackStart( int seqno ); void HTTPingCallbackGot( int seqno ); -//Don't dynamically allocate resources here, since execution may be stopped arbitrarily. -void DoHTTPing( const char * addy, double minperiod, int * seqnoptr, volatile double * timeouttime, int * socketptr, volatile int * getting_host_by_name, const char * device) +// Don't dynamically allocate resources here, since execution may be stopped arbitrarily. +void DoHTTPing( const char *addy, double minperiod, int *seqnoptr, volatile double *timeouttime, + int *socketptr, volatile int *getting_host_by_name, const char *device ) { -#if defined(WIN32) || defined(WINDOWS) - (void) device; // option is not available for windows. Suppress unused warning. +#if defined( WIN32 ) || defined( WINDOWS ) + (void)device; // option is not available for windows. Suppress unused warning. WSADATA wsaData; - int r = WSAStartup(MAKEWORD(2,2), &wsaData); - if( r ) + int r = WSAStartup( MAKEWORD( 2, 2 ), &wsaData ); + if ( r ) { ERRM( "Fault in WSAStartup\n" ); exit( -2 ); @@ -57,42 +58,43 @@ void DoHTTPing( const char * addy, double minperiod, int * seqnoptr, volatile do socklen_t serveraddr_len; int serverresolve; int httpsock; - int addylen = strlen(addy); - char hostname[addylen+1]; + int addylen = strlen( addy ); + char hostname[ addylen + 1 ]; memcpy( hostname, addy, addylen + 1 ); - char * eportmarker = strchr( hostname, ':' ); - char * eurl = strchr( hostname, '/' ); + char *eportmarker = strchr( hostname, ':' ); + char *eurl = strchr( hostname, '/' ); int portno = 80; - if( eportmarker ) + if ( eportmarker ) { - portno = atoi( eportmarker+1 ); + portno = atoi( eportmarker + 1 ); *eportmarker = 0; } else { - if( eurl ) - *eurl = 0; + if ( eurl ) *eurl = 0; } /* gethostbyname: get the server's DNS entry */ - serveraddr_len = sizeof(serveraddr); + serveraddr_len = sizeof( serveraddr ); *getting_host_by_name = 1; - serverresolve = resolveName((struct sockaddr*) &serveraddr, &serveraddr_len, hostname, AF_UNSPEC); + serverresolve = + resolveName( (struct sockaddr *)&serveraddr, &serveraddr_len, hostname, AF_UNSPEC ); *getting_host_by_name = 0; - if (serverresolve != 1) { - ERRMB("ERROR, no such host as \"%s\"\n", hostname); + if ( serverresolve != 1 ) + { + ERRMB( "ERROR, no such host as \"%s\"\n", hostname ); goto fail; } /* build the server's Internet address */ - serveraddr.sin6_port = htons(portno); + serveraddr.sin6_port = htons( portno ); reconnect: - *socketptr = httpsock = socket(serveraddr.sin6_family, SOCK_STREAM, 0); - if (httpsock < 0) + *socketptr = httpsock = socket( serveraddr.sin6_family, SOCK_STREAM, 0 ); + if ( httpsock < 0 ) { ERRMB( "Error opening socket\n" ); return; @@ -100,74 +102,95 @@ void DoHTTPing( const char * addy, double minperiod, int * seqnoptr, volatile do int sockVal = 1; // using char* for sockVal for windows - if (setsockopt(httpsock, SOL_TCP, TCP_NODELAY, (char*) &sockVal, 4) != 0) + if ( setsockopt( httpsock, SOL_TCP, TCP_NODELAY, (char *)&sockVal, 4 ) != 0 ) { - ERRM( "Error: Failed to set TCP_NODELAY\n"); + ERRM( "Error: Failed to set TCP_NODELAY\n" ); // not a critical error, we can continue } #if !defined( WIN32 ) && !defined( WINDOWS ) - if(device) + if ( device ) { - if( setsockopt(httpsock, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device) +1) != 0) + if ( setsockopt( httpsock, SOL_SOCKET, SO_BINDTODEVICE, device, strlen( device ) + 1 ) != + 0 ) { - ERRM("Error: Failed to set Device option.\n"); + ERRM( "Error: Failed to set Device option.\n" ); exit( -1 ); } } #endif // not windows /* connect: create a connection with the server */ - if (connect(httpsock, (struct sockaddr*)&serveraddr, serveraddr_len) < 0) + if ( connect( httpsock, (struct sockaddr *)&serveraddr, serveraddr_len ) < 0 ) { - ERRMB( "%s: ERROR connecting: %s (%d)\n", hostname, strerror(errno), errno ); + ERRMB( "%s: ERROR connecting: %s (%d)\n", hostname, strerror( errno ), errno ); goto fail; } #ifdef __APPLE__ int opt = 1; - setsockopt(httpsock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); + setsockopt( httpsock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof( opt ) ); #endif - errbuffer[0] = 0; + errbuffer[ 0 ] = 0; - while( 1 ) + while ( 1 ) { - char buf[8192]; + char buf[ 8192 ]; - int n = sprintf( buf, "HEAD %s HTTP/1.1\r\nConnection: keep-alive\r\nHost: %s\r\n\r\n", eurl?eurl:"/favicon.ico", hostname ); + int n = sprintf( buf, "HEAD %s HTTP/1.1\r\nConnection: keep-alive\r\nHost: %s\r\n\r\n", + eurl ? eurl : "/favicon.ico", hostname ); - (*seqnoptr) ++; + ( *seqnoptr )++; HTTPingCallbackStart( *seqnoptr ); int rs = send( httpsock, buf, n, MSG_NOSIGNAL ); double starttime = *timeouttime = OGGetAbsoluteTime(); int breakout = 0; - if( rs != n ) breakout = 1; + if ( rs != n ) breakout = 1; int endstate = 0; - while( !breakout ) + while ( !breakout ) { #ifdef WIN32 - n = recv( httpsock, buf, sizeof(buf)-1, 0); + n = recv( httpsock, buf, sizeof( buf ) - 1, 0 ); #else - n = recv( httpsock, buf, sizeof(buf)-1, MSG_PEEK); - if( n > 0 ) n = read( httpsock, buf, sizeof(buf)-1); - else if( n == 0 ) break; //FIN received + n = recv( httpsock, buf, sizeof( buf ) - 1, MSG_PEEK ); + if ( n > 0 ) + n = read( httpsock, buf, sizeof( buf ) - 1 ); + else if ( n == 0 ) + break; // FIN received #endif - - if( n < 0 ) return; - + + if ( n < 0 ) return; + int i; - for( i = 0; i < n; i++ ) + for ( i = 0; i < n; i++ ) { - char c = buf[i]; - switch( endstate ) + char c = buf[ i ]; + switch ( endstate ) { - case 0: if( c == '\r' ) endstate++; break; - case 1: if( c == '\n' ) endstate++; else endstate = 0; break; - case 2: if( c == '\r' ) endstate++; else endstate = 0; break; - case 3: if( c == '\n' && i == n-1) breakout = 1; else endstate = 0; break; + case 0: + if ( c == '\r' ) endstate++; + break; + case 1: + if ( c == '\n' ) + endstate++; + else + endstate = 0; + break; + case 2: + if ( c == '\r' ) + endstate++; + else + endstate = 0; + break; + case 3: + if ( c == '\n' && i == n - 1 ) + breakout = 1; + else + endstate = 0; + break; } } } @@ -175,10 +198,10 @@ void DoHTTPing( const char * addy, double minperiod, int * seqnoptr, volatile do HTTPingCallbackGot( *seqnoptr ); - double delay_time = minperiod - (*timeouttime - starttime); - if( delay_time > 0 ) - usleep( (int)(delay_time * 1000000) ); - if( !breakout ) { + double delay_time = minperiod - ( *timeouttime - starttime ); + if ( delay_time > 0 ) usleep( (int)( delay_time * 1000000 ) ); + if ( !breakout ) + { #ifdef WIN32 closesocket( httpsock ); #else @@ -194,9 +217,9 @@ void DoHTTPing( const char * addy, double minperiod, int * seqnoptr, volatile do struct HTTPPingLaunch { - const char * addy; + const char *addy; double minperiod; - const char * device; + const char *device; volatile double timeout_time; volatile int failed; @@ -205,35 +228,40 @@ struct HTTPPingLaunch volatile int getting_host_by_name; }; -static void * DeployPing( void * v ) +static void *DeployPing( void *v ) { - struct HTTPPingLaunch *hpl = (struct HTTPPingLaunch*)v; + struct HTTPPingLaunch *hpl = (struct HTTPPingLaunch *)v; hpl->socket = 0; hpl->getting_host_by_name = 0; - DoHTTPing( hpl->addy, hpl->minperiod, &hpl->seqno, &hpl->timeout_time, &hpl->socket, &hpl->getting_host_by_name, hpl->device ); + DoHTTPing( hpl->addy, hpl->minperiod, &hpl->seqno, &hpl->timeout_time, &hpl->socket, + &hpl->getting_host_by_name, hpl->device ); hpl->failed = 1; return 0; } -static void * PingRunner( void * v ) +static void *PingRunner( void *v ) { - struct HTTPPingLaunch *hpl = (struct HTTPPingLaunch*)v; + struct HTTPPingLaunch *hpl = (struct HTTPPingLaunch *)v; hpl->seqno = 0; - while( 1 ) + while ( 1 ) { hpl->timeout_time = OGGetAbsoluteTime(); og_thread_t thd = OGCreateThread( DeployPing, hpl ); - while( 1 ) + while ( 1 ) { double Now = OGGetAbsoluteTime(); double usl = hpl->timeout_time - Now + HTTPTIMEOUT; - if( usl > 0 ) usleep( (int)(usl*1000000 + 1000)); - else usleep( 10000 ); - - if( hpl->timeout_time + HTTPTIMEOUT < Now && !hpl->getting_host_by_name ) //Can't terminate in the middle of a gethostbyname operation otherwise bad things can happen. + if ( usl > 0 ) + usleep( (int)( usl * 1000000 + 1000 ) ); + else + usleep( 10000 ); + + if ( hpl->timeout_time + HTTPTIMEOUT < Now && + !hpl->getting_host_by_name ) // Can't terminate in the middle of a gethostbyname + // operation otherwise bad things can happen. { - if( hpl->socket ) + if ( hpl->socket ) { #ifdef WIN32 closesocket( hpl->socket ); @@ -250,7 +278,7 @@ static void * PingRunner( void * v ) return 0; } -int StartHTTPing( const char * addy, double minperiod, const char * device) +int StartHTTPing( const char *addy, double minperiod, const char *device ) { struct HTTPPingLaunch *hpl = malloc( sizeof( struct HTTPPingLaunch ) ); hpl->addy = addy; @@ -259,6 +287,3 @@ int StartHTTPing( const char * addy, double minperiod, const char * device) OGCreateThread( PingRunner, hpl ); return 0; } - - - diff --git a/ping.c b/ping.c index 053da6a..f271152 100644 --- a/ping.c +++ b/ping.c @@ -1,17 +1,17 @@ -//Copyright 2017 <>< C. Lohr, under the MIT/x11 License -//Rewritten from Sean Walton and Macmillan Publishers. -//Most of it was rewritten but the header was never updated. -//Now I finished the job. +// Copyright 2017 <>< C. Lohr, under the MIT/x11 License +// Rewritten from Sean Walton and Macmillan Publishers. +// Most of it was rewritten but the header was never updated. +// Now I finished the job. -#include -#include -#include -#include -#include -#include #include "ping.h" #include "error_handling.h" #include "resolve.h" +#include +#include +#include +#include +#include +#include #ifdef TCC #include "tccheader.h" @@ -26,176 +26,166 @@ socklen_t psaddr_len; #ifdef WIN_USE_NO_ADMIN_PING #ifdef TCC - //... +//... #else +#include #include -#include #include -#include #include +#include #endif #include "rawdraw/os_generic.h" - #define MAX_PING_SIZE 16384 #define PINGTHREADS 100 #if !defined( MINGW_BUILD ) && !defined( TCC ) - #pragma comment(lib, "Ws2_32.lib") - #pragma comment(lib, "iphlpapi.lib") +#pragma comment( lib, "Ws2_32.lib" ) +#pragma comment( lib, "iphlpapi.lib" ) #endif static og_sema_t s_disp; static og_sema_t s_ping; -void ping_setup(const char * strhost, const char * device) +void ping_setup( const char *strhost, const char *device ) { // resolve host - psaddr_len = sizeof(psaddr); - resolveName((struct sockaddr*) &psaddr, &psaddr_len, strhost, AF_INET); // only resolve ipv4 on windows + psaddr_len = sizeof( psaddr ); + resolveName( + (struct sockaddr *)&psaddr, &psaddr_len, strhost, AF_INET ); // only resolve ipv4 on windows s_disp = OGCreateSema(); s_ping = OGCreateSema(); - //This function is executed first. + // This function is executed first. } void listener() { static uint8_t listth; - if( listth ) return; + if ( listth ) return; listth = 1; OGUnlockSema( s_disp ); - //Normally needs to call display(buf + 28, bytes - 28 ); on successful ping. - //This function is executed as a thread after setup. - //Really, we just use the s_disp semaphore to make sure we only launch disp's at correct times. + // Normally needs to call display(buf + 28, bytes - 28 ); on successful ping. + // This function is executed as a thread after setup. + // Really, we just use the s_disp semaphore to make sure we only launch disp's at correct times. - while(1) { OGSleep( 100000 ); } + while ( 1 ) { OGSleep( 100000 ); } return; } -static HANDLE pinghandles[PINGTHREADS]; +static HANDLE pinghandles[ PINGTHREADS ]; -static void * pingerthread( void * v ) +static void *pingerthread( void *v ) { - uint8_t ping_payload[MAX_PING_SIZE]; + uint8_t ping_payload[ MAX_PING_SIZE ]; - HANDLE ih = *((HANDLE*)v); + HANDLE ih = *( (HANDLE *)v ); - int timeout_ms = pingperiodseconds * (PINGTHREADS-1) * 1000; - while(1) + int timeout_ms = pingperiodseconds * ( PINGTHREADS - 1 ) * 1000; + while ( 1 ) { OGLockSema( s_ping ); int rl = load_ping_packet( ping_payload, sizeof( ping_payload ) ); struct repl_t { ICMP_ECHO_REPLY rply; - uint8_t err_data[16384]; + uint8_t err_data[ 16384 ]; } repl; - DWORD res = IcmpSendEcho( ih, - ((struct sockaddr_in*) &psaddr)->sin_addr.s_addr, ping_payload, rl, - 0, &repl, sizeof( repl ), - timeout_ms ); + DWORD res = IcmpSendEcho( ih, ( (struct sockaddr_in *)&psaddr )->sin_addr.s_addr, + ping_payload, rl, 0, &repl, sizeof( repl ), timeout_ms ); int err; - if( !res ) err = GetLastError(); + if ( !res ) err = GetLastError(); OGLockSema( s_disp ); - if( !res ) - { - if( err == 11050 ) - { - printf( "GENERAL FAILURE\n" ); - } - else - { - printf( "ERROR: %d\n", err ); - } - } - if( res ) + if ( !res ) { - display( repl.rply.Data, rl ); + if ( err == 11050 ) { printf( "GENERAL FAILURE\n" ); } + else { printf( "ERROR: %d\n", err ); } } + if ( res ) { display( repl.rply.Data, rl ); } OGUnlockSema( s_disp ); } return 0; } -void ping(struct sockaddr *addr, socklen_t addr_len ) +void ping( struct sockaddr *addr, socklen_t addr_len ) { int i; - (void) addr; - (void) addr_len; + (void)addr; + (void)addr_len; - if( psaddr.sin6_family != AF_INET ) + if ( psaddr.sin6_family != AF_INET ) { // ipv6 ICMP Ping is not supported on windows ERRM( "ERROR: ipv6 ICMP Ping is not supported on windows\n" ); exit( -1 ); } - //Launch pinger threads - for( i = 0; i < PINGTHREADS; i++ ) + // Launch pinger threads + for ( i = 0; i < PINGTHREADS; i++ ) { - HANDLE ih = pinghandles[i] = IcmpCreateFile(); - if( ih == INVALID_HANDLE_VALUE ) + HANDLE ih = pinghandles[ i ] = IcmpCreateFile(); + if ( ih == INVALID_HANDLE_VALUE ) { ERRM( "Cannot create ICMP thread %d\n", i ); exit( 0 ); } - OGCreateThread( pingerthread, &pinghandles[i] ); + OGCreateThread( pingerthread, &pinghandles[ i ] ); } - //This function is executed as a thread after setup. + // This function is executed as a thread after setup. - while(1) + while ( 1 ) { - if( i >= PINGTHREADS-1 ) i = 0; - else i++; + if ( i >= PINGTHREADS - 1 ) + i = 0; + else + i++; OGUnlockSema( s_ping ); - OGUSleep( (int)(pingperiodseconds * 1000000) ); + OGUSleep( (int)( pingperiodseconds * 1000000 ) ); } } - #else // ! WIN_USE_NO_ADMIN_PING -//The normal way to do it - only problem is Windows needs admin privs. +// The normal way to do it - only problem is Windows needs admin privs. #ifdef WIN32 - #include - #define SOL_IP 0 - #define F_SETFL 4 - #define ICMP_ECHO 8 - #define IP_TTL 2 - #define O_NONBLOCK 04000 +#include +#define SOL_IP 0 +#define F_SETFL 4 +#define ICMP_ECHO 8 +#define IP_TTL 2 +#define O_NONBLOCK 04000 #ifndef MINGW_BUILD - #pragma comment(lib, "Ws2_32.lib") +#pragma comment( lib, "Ws2_32.lib" ) #endif - #include - #include - #include - #include +#include +#include +#include +#include #else // ! WIN32 - #ifdef __FreeBSD__ - #include - #endif - #include - #include - #include - #include - #if defined(__APPLE__) || defined(__FreeBSD__) - #ifndef SOL_IP - #define SOL_IP IPPROTO_IP - #endif - #endif - #include - #include - #include +#ifdef __FreeBSD__ +#include +#endif +#include +#include +#include +#include +#if defined( __APPLE__ ) || defined( __FreeBSD__ ) +#ifndef SOL_IP +#define SOL_IP IPPROTO_IP +#endif +#endif +#include +#include +#include #endif #include "rawdraw/os_generic.h" @@ -203,88 +193,86 @@ void ping(struct sockaddr *addr, socklen_t addr_len ) #if defined WIN32 || defined __APPLE__ struct icmphdr { - uint8_t type; - uint8_t code; - uint16_t checksum; + uint8_t type; + uint8_t code; + uint16_t checksum; union { struct { - uint16_t id; - uint16_t sequence; + uint16_t id; + uint16_t sequence; } echo; - uint32_t gateway; + uint32_t gateway; struct { - uint16_t __unused; - uint16_t mtu; + uint16_t __unused; + uint16_t mtu; } frag; } un; }; #endif -#define PACKETSIZE 65536 +#define PACKETSIZE 65536 struct packet { #ifdef __FreeBSD__ struct icmp hdr; - unsigned char msg[PACKETSIZE-sizeof(struct icmp)]; + unsigned char msg[ PACKETSIZE - sizeof( struct icmp ) ]; #else struct icmphdr hdr; - unsigned char msg[PACKETSIZE-sizeof(struct icmphdr)]; + unsigned char msg[ PACKETSIZE - sizeof( struct icmphdr ) ]; #endif }; int sd; -int pid=-1; +int pid = -1; -uint16_t checksum( const unsigned char * start, uint16_t len ) +uint16_t checksum( const unsigned char *start, uint16_t len ) { uint16_t i; - const uint16_t * wptr = (uint16_t*) start; + const uint16_t *wptr = (uint16_t *)start; uint32_t csum = 0; - for (i=1;i>16) - csum = (csum & 0xFFFF)+(csum >> 16); - //csum = (csum>>8) | ((csum&0xff)<<8); + for ( i = 1; i < len; i += 2 ) csum += (uint32_t)( *( wptr++ ) ); + if ( len & 1 ) // See if there's an odd number of bytes? + csum += *(uint8_t *)wptr; + if ( csum >> 16 ) csum = ( csum & 0xFFFF ) + ( csum >> 16 ); + // csum = (csum>>8) | ((csum&0xff)<<8); return ~csum; } // setsockopt TTL to 255 -void setTTL(int sock) +void setTTL( int sock ) { - const int val=255; + const int val = 255; - assert(psaddr.sin6_family == AF_INET || psaddr.sin6_family == AF_INET6); + assert( psaddr.sin6_family == AF_INET || psaddr.sin6_family == AF_INET6 ); - if ( setsockopt(sd, (psaddr.sin6_family == AF_INET) ? SOL_IP : SOL_IPV6, IP_TTL, &val, sizeof(val)) != 0) + if ( setsockopt( sd, ( psaddr.sin6_family == AF_INET ) ? SOL_IP : SOL_IPV6, IP_TTL, &val, + sizeof( val ) ) != 0 ) { - ERRM("Error: Failed to set TTL option. Are you root? Or can do sock_raw sockets?\n"); + ERRM( "Error: Failed to set TTL option. Are you root? Or can do sock_raw sockets?\n" ); exit( -1 ); } } // 0 = failed, 1 = this is a ICMP Response -int isICMPResponse(unsigned char* buf, int bytes) +int isICMPResponse( unsigned char *buf, int bytes ) { - assert(psaddr.sin6_family == AF_INET || psaddr.sin6_family == AF_INET6); + assert( psaddr.sin6_family == AF_INET || psaddr.sin6_family == AF_INET6 ); - if( bytes == -1 ) return 0; + if ( bytes == -1 ) return 0; - if( psaddr.sin6_family == AF_INET ) // ipv4 compare + if ( psaddr.sin6_family == AF_INET ) // ipv4 compare { - if( buf[9] != IPPROTO_ICMP ) return 0; - if( buf[20] != ICMP_ECHOREPLY ) return 0; - + if ( buf[ 9 ] != IPPROTO_ICMP ) return 0; + if ( buf[ 20 ] != ICMP_ECHOREPLY ) return 0; } - else if( psaddr.sin6_family == AF_INET6 ) // ipv6 compare + else if ( psaddr.sin6_family == AF_INET6 ) // ipv6 compare { - if( buf[0] != ICMP6_ECHO_REPLY ) return 0; + if ( buf[ 0 ] != ICMP6_ECHO_REPLY ) return 0; } return 1; @@ -292,13 +280,10 @@ int isICMPResponse(unsigned char* buf, int bytes) int createSocket() { - if( psaddr.sin6_family == AF_INET ) - { - return socket(PF_INET, SOCK_RAW, IPPROTO_ICMP); - } - else if( psaddr.sin6_family == AF_INET6 ) + if ( psaddr.sin6_family == AF_INET ) { return socket( PF_INET, SOCK_RAW, IPPROTO_ICMP ); } + else if ( psaddr.sin6_family == AF_INET6 ) { - return socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6); + return socket( PF_INET6, SOCK_RAW, IPPROTO_ICMPV6 ); } // invalid af_family @@ -310,36 +295,36 @@ void listener() #ifndef WIN32 int sd = createSocket(); - setTTL(sd); + setTTL( sd ); #endif struct sockaddr_in6 addr; - unsigned char buf[66000]; + unsigned char buf[ 66000 ]; #ifdef WIN32 - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL ); #endif - for (;;) + for ( ;; ) { - socklen_t addrlenval=sizeof(addr); + socklen_t addrlenval = sizeof( addr ); int bytes; #ifdef WIN32 - WSAPOLLFD fda[1]; - fda[0].fd = sd; - fda[0].events = POLLIN; - WSAPoll(fda, 1, 10); + WSAPOLLFD fda[ 1 ]; + fda[ 0 ].fd = sd; + fda[ 0 ].events = POLLIN; + WSAPoll( fda, 1, 10 ); #endif - keep_retry_quick: + keep_retry_quick: - bytes = recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlenval ); - if( !isICMPResponse(buf, bytes) ) continue; + bytes = recvfrom( sd, buf, sizeof( buf ), 0, (struct sockaddr *)&addr, &addrlenval ); + if ( !isICMPResponse( buf, bytes ) ) continue; // compare the sender - if( memcmp(&addr, &psaddr, addrlenval) != 0 ) continue; + if ( memcmp( &addr, &psaddr, addrlenval ) != 0 ) continue; // sizeof(packet.hdr) + 20 int offset = 0; - if(addr.sin6_family == AF_INET) // ipv4 + if ( addr.sin6_family == AF_INET ) // ipv4 { #ifdef __FreeBSD__ offset = 48; @@ -353,11 +338,8 @@ void listener() } if ( bytes > 0 ) - display(buf + offset, bytes - offset ); - else - { - ERRM("Error: recvfrom failed"); - } + display( buf + offset, bytes - offset ); + else { ERRM( "Error: recvfrom failed" ); } goto keep_retry_quick; } @@ -366,84 +348,80 @@ void listener() exit( 0 ); } -void ping(struct sockaddr *addr, socklen_t addr_len ) +void ping( struct sockaddr *addr, socklen_t addr_len ) { - int cnt=1; + int cnt = 1; #ifdef WIN32 { - //Setup windows socket for nonblocking io. + // Setup windows socket for nonblocking io. unsigned long iMode = 1; - ioctlsocket(sd, FIONBIO, &iMode); + ioctlsocket( sd, FIONBIO, &iMode ); } #else - if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 ) - ERRM("Warning: Request nonblocking I/O failed."); + if ( fcntl( sd, F_SETFL, O_NONBLOCK ) != 0 ) ERRM( "Warning: Request nonblocking I/O failed." ); #endif double stime = OGGetAbsoluteTime(); struct packet pckt; - do - { + do { int rsize = load_ping_packet( pckt.msg, sizeof( pckt.msg ) ); - memset( &pckt.hdr, 0, sizeof( pckt.hdr ) ); //This needs to be here, but I don't know why, since I think the struct is fully populated. + memset( &pckt.hdr, 0, sizeof( pckt.hdr ) ); // This needs to be here, but I don't know why, + // since I think the struct is fully populated. #ifdef __FreeBSD__ pckt.hdr.icmp_code = 0; pckt.hdr.icmp_type = ICMP_ECHO; pckt.hdr.icmp_id = pid; pckt.hdr.icmp_seq = cnt++; - pckt.hdr.icmp_cksum = checksum((const unsigned char *)&pckt, sizeof( pckt.hdr ) + rsize ); + pckt.hdr.icmp_cksum = checksum( (const unsigned char *)&pckt, sizeof( pckt.hdr ) + rsize ); #else pckt.hdr.code = 0; - pckt.hdr.type = (psaddr.sin6_family == AF_INET) ? ICMP_ECHO : ICMP6_ECHO_REQUEST; + pckt.hdr.type = ( psaddr.sin6_family == AF_INET ) ? ICMP_ECHO : ICMP6_ECHO_REQUEST; pckt.hdr.un.echo.id = pid; pckt.hdr.un.echo.sequence = cnt++; - pckt.hdr.checksum = checksum((const unsigned char *)&pckt, sizeof( pckt.hdr ) + rsize ); + pckt.hdr.checksum = checksum( (const unsigned char *)&pckt, sizeof( pckt.hdr ) + rsize ); #endif - int sr = sendto(sd, (char*)&pckt, sizeof( pckt.hdr ) + rsize , 0, addr, addr_len); + int sr = sendto( sd, (char *)&pckt, sizeof( pckt.hdr ) + rsize, 0, addr, addr_len ); - if( sr <= 0 ) + if ( sr <= 0 ) { ping_failed_to_send = 1; - ERRMB("Ping send failed:\n%s (%d)\n", strerror(errno), errno); - } - else - { - ping_failed_to_send = 0; + ERRMB( "Ping send failed:\n%s (%d)\n", strerror( errno ), errno ); } + else { ping_failed_to_send = 0; } - if( precise_ping ) + if ( precise_ping ) { double ctime; - do - { + do { ctime = OGGetAbsoluteTime(); - if( pingperiodseconds >= 1000 ) stime = ctime; - } while( ctime < stime + pingperiodseconds ); + if ( pingperiodseconds >= 1000 ) stime = ctime; + } while ( ctime < stime + pingperiodseconds ); stime += pingperiodseconds; } else { - if( pingperiodseconds > 0 ) + if ( pingperiodseconds > 0 ) { - uint32_t dlw = 1000000.0*pingperiodseconds; + uint32_t dlw = 1000000.0 * pingperiodseconds; OGUSleep( dlw ); } } - } while( pingperiodseconds >= 0 ); - //close( sd ); //Hacky, we don't close here because SD doesn't come from here, rather from ping_setup. We may want to run this multiple times. + } while ( pingperiodseconds >= 0 ); + // close( sd ); //Hacky, we don't close here because SD doesn't come from here, rather from + // ping_setup. We may want to run this multiple times. } -void ping_setup(const char * strhost, const char * device) +void ping_setup( const char *strhost, const char *device ) { pid = getpid(); #ifdef WIN32 WSADATA wsaData; - int r = WSAStartup(MAKEWORD(2,2), &wsaData); - if( r ) + int r = WSAStartup( MAKEWORD( 2, 2 ), &wsaData ); + if ( r ) { ERRM( "Fault in WSAStartup\n" ); exit( -2 ); @@ -452,28 +430,30 @@ void ping_setup(const char * strhost, const char * device) #ifdef WIN32 - sd = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, 0, 0, WSA_FLAG_OVERLAPPED); + sd = WSASocket( AF_INET, SOCK_RAW, IPPROTO_ICMP, 0, 0, WSA_FLAG_OVERLAPPED ); { int lttl = 0xff; - if (setsockopt(sd, IPPROTO_IP, IP_TTL, (const char*)<tl, sizeof(lttl)) == SOCKET_ERROR) + if ( setsockopt( sd, IPPROTO_IP, IP_TTL, (const char *)<tl, sizeof( lttl ) ) == + SOCKET_ERROR ) { printf( "Warning: No IP_TTL.\n" ); } } #else // resolve host - psaddr_len = sizeof(psaddr); - resolveName((struct sockaddr*) &psaddr, &psaddr_len, strhost, AF_UNSPEC); + psaddr_len = sizeof( psaddr ); + resolveName( (struct sockaddr *)&psaddr, &psaddr_len, strhost, AF_UNSPEC ); sd = createSocket(); - setTTL(sd); + setTTL( sd ); - if(device) + if ( device ) { - if( setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device) +1) != 0) + if ( setsockopt( sd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen( device ) + 1 ) != 0 ) { - ERRM("Error: Failed to set Device option. Are you root? Or can do sock_raw sockets?\n"); + ERRM( "Error: Failed to set Device option. Are you root? Or can do sock_raw " + "sockets?\n" ); exit( -1 ); } } @@ -481,20 +461,18 @@ void ping_setup(const char * strhost, const char * device) #endif if ( sd < 0 ) { - ERRM("Error: Could not create raw socket\n"); - exit(0); + ERRM( "Error: Could not create raw socket\n" ); + exit( 0 ); } - } #endif // WIN_USE_NO_ADMIN_PING -void do_pinger( ) +void do_pinger() { - ping((struct sockaddr*) &psaddr, psaddr_len ); + ping( (struct sockaddr *)&psaddr, psaddr_len ); } // used by the ERRMB makro from error_handling.h -char errbuffer[1024]; - +char errbuffer[ 1024 ]; diff --git a/resolve.c b/resolve.c index ca7cd8b..d528ee3 100644 --- a/resolve.c +++ b/resolve.c @@ -1,75 +1,78 @@ #include "resolve.h" +#include "error_handling.h" #include #include #include -#include "error_handling.h" #ifdef WIN32 - #include +#include #else // !WIN32 - #include // inet_pton (parsing ipv4 and ipv6 notation) +#include // inet_pton (parsing ipv4 and ipv6 notation) - #include - #include - #include +#include +#include +#include #endif -int resolveName(struct sockaddr* addr, socklen_t* addr_len, const char* hostname, int family) +int resolveName( struct sockaddr *addr, socklen_t *addr_len, const char *hostname, int family ) { int result; - struct addrinfo* res = NULL; + struct addrinfo *res = NULL; // zero addr - memset(addr, 0, *addr_len); + memset( addr, 0, *addr_len ); // try to parse ipv4 - if(family == AF_UNSPEC || family == AF_INET) { - result = inet_pton(AF_INET, hostname, &((struct sockaddr_in*) addr)->sin_addr); - if(result == 1) + if ( family == AF_UNSPEC || family == AF_INET ) + { + result = inet_pton( AF_INET, hostname, &( (struct sockaddr_in *)addr )->sin_addr ); + if ( result == 1 ) { addr->sa_family = AF_INET; - *addr_len = sizeof(struct sockaddr_in); + *addr_len = sizeof( struct sockaddr_in ); return 1; } } // try to parse ipv6 - if(family == AF_UNSPEC || family == AF_INET6) { - result = inet_pton(AF_INET6, hostname, &((struct sockaddr_in6*) addr)->sin6_addr); - if(result == 1) + if ( family == AF_UNSPEC || family == AF_INET6 ) + { + result = inet_pton( AF_INET6, hostname, &( (struct sockaddr_in6 *)addr )->sin6_addr ); + if ( result == 1 ) { addr->sa_family = AF_INET6; - *addr_len = sizeof(struct sockaddr_in6); + *addr_len = sizeof( struct sockaddr_in6 ); return 1; } } // try to resolve DNS struct addrinfo hints; - memset(&hints, 0, sizeof(struct addrinfo)); + memset( &hints, 0, sizeof( struct addrinfo ) ); hints.ai_family = family; // AF_UNSPEC, AF_INET, AF_INET6 hints.ai_socktype = 0; // 0 = any, SOCK_STREAM, SOCK_DGRAM hints.ai_protocol = 0; // 0 = any hints.ai_flags = 0; // no flags - result = getaddrinfo(hostname, NULL, &hints, &res); - if( result != 0) + result = getaddrinfo( hostname, NULL, &hints, &res ); + if ( result != 0 ) { - ERRM( "Error: cannot resolve hostname %s: %s\n", hostname, gai_strerror(result) ); + ERRM( "Error: cannot resolve hostname %s: %s\n", hostname, gai_strerror( result ) ); exit( -1 ); } - if(res->ai_addrlen > *addr_len) + if ( res->ai_addrlen > *addr_len ) { // error - this should not happen - ERRM( "Error addr is to short. required length: %d, available length: %d", res->ai_addrlen, *addr_len ); - freeaddrinfo(res); + ERRM( "Error addr is to short. required length: %d, available length: %d", res->ai_addrlen, + *addr_len ); + freeaddrinfo( res ); exit( -1 ); } - memcpy(addr, res->ai_addr, res->ai_addrlen); + memcpy( addr, res->ai_addr, res->ai_addrlen ); *addr_len = res->ai_addrlen; - freeaddrinfo(res); + freeaddrinfo( res ); return 1; } diff --git a/searchnet.c b/searchnet.c index 3c268c0..6224061 100644 --- a/searchnet.c +++ b/searchnet.c @@ -1,87 +1,89 @@ -#include #include "ping.h" -#include -#include +#include "rawdraw/os_generic.h" #include +#include #include +#include #include -#include "rawdraw/os_generic.h" +#include uint32_t my_random_key; -uint8_t send_id[4]; +uint8_t send_id[ 4 ]; -void * PingListen( void * r ) +void *PingListen( void *r ) { listener(); printf( "Fault on listen.\n" ); exit( -2 ); } -void display(uint8_t *buf, int bytes) +void display( uint8_t *buf, int bytes ) { - uint32_t reqid = ((uint32_t)buf[0+1] << 24) | (buf[1+1]<<16) | (buf[2+1]<<8) | (buf[3+1]); + uint32_t reqid = ( (uint32_t)buf[ 0 + 1 ] << 24 ) | ( buf[ 1 + 1 ] << 16 ) | + ( buf[ 2 + 1 ] << 8 ) | ( buf[ 3 + 1 ] ); - if( reqid != my_random_key ) return; + if ( reqid != my_random_key ) return; - printf( "%d.%d.%d.%d\n", buf[4+1], buf[5+1], buf[6+1], buf[7+1] ); + printf( "%d.%d.%d.%d\n", buf[ 4 + 1 ], buf[ 5 + 1 ], buf[ 6 + 1 ], buf[ 7 + 1 ] ); } -int load_ping_packet( uint8_t * buffer, int bufflen ) +int load_ping_packet( uint8_t *buffer, int bufflen ) { - buffer[0+1] = my_random_key >> 24; - buffer[1+1] = my_random_key >> 16; - buffer[2+1] = my_random_key >> 8; - buffer[3+1] = my_random_key >> 0; + buffer[ 0 + 1 ] = my_random_key >> 24; + buffer[ 1 + 1 ] = my_random_key >> 16; + buffer[ 2 + 1 ] = my_random_key >> 8; + buffer[ 3 + 1 ] = my_random_key >> 0; - buffer[4+1] = send_id[0]; - buffer[5+1] = send_id[1]; - buffer[6+1] = send_id[2]; - buffer[7+1] = send_id[3]; + buffer[ 4 + 1 ] = send_id[ 0 ]; + buffer[ 5 + 1 ] = send_id[ 1 ]; + buffer[ 6 + 1 ] = send_id[ 2 ]; + buffer[ 7 + 1 ] = send_id[ 3 ]; return 12; } -int main( int argc, char ** argv ) +int main( int argc, char **argv ) { uint32_t offset; int mask; in_addr_t base; - char dispip[32]; + char dispip[ 32 ]; float speed; ping_setup(); OGCreateThread( PingListen, 0 ); - srand( ((int)(OGGetAbsoluteTime()*10000)) ); + srand( ( (int)( OGGetAbsoluteTime() * 10000 ) ) ); my_random_key = rand(); - if( argc != 4 ) + if ( argc != 4 ) { - fprintf( stderr, "Usage: [searchnet IP net] [mask (single #, i.e. 24)] [speed (in seconds per attempt)]\n" ); + fprintf( stderr, "Usage: [searchnet IP net] [mask (single #, i.e. 24)] [speed (in seconds " + "per attempt)]\n" ); return -1; } - base = ntohl(inet_addr( argv[1] )); - mask = 1<<(32-atoi(argv[2])); - speed = atof(argv[3]); + base = ntohl( inet_addr( argv[ 1 ] ) ); + mask = 1 << ( 32 - atoi( argv[ 2 ] ) ); + speed = atof( argv[ 3 ] ); - base &= ~(mask-1); + base &= ~( mask - 1 ); printf( "Base: %08x / Mask: %08x\n", base, mask ); - for( offset = 0; offset < mask; offset++ ) + for ( offset = 0; offset < mask; offset++ ) { uint32_t cur = base + offset; - sprintf( dispip, "%d.%d.%d.%d", (cur>>24)&0xff, (cur>>16)&0xff, (cur>>8)&0xff, (cur)&0xff ); - send_id[0] = (cur>>24)&0xff; - send_id[1] = (cur>>16)&0xff; - send_id[2] = (cur>>8)&0xff; - send_id[3] = (cur)&0xff; -// printf( "Pinging: %s\n", dispip ); + sprintf( dispip, "%d.%d.%d.%d", ( cur >> 24 ) & 0xff, ( cur >> 16 ) & 0xff, + ( cur >> 8 ) & 0xff, (cur)&0xff ); + send_id[ 0 ] = ( cur >> 24 ) & 0xff; + send_id[ 1 ] = ( cur >> 16 ) & 0xff; + send_id[ 2 ] = ( cur >> 8 ) & 0xff; + send_id[ 3 ] = (cur)&0xff; + // printf( "Pinging: %s\n", dispip ); pingperiodseconds = -1; do_pinger( dispip ); - OGUSleep( (int)(speed * 1000000) ); + OGUSleep( (int)( speed * 1000000 ) ); } return 0; } - From 143efe55311fb1dceb28447f4003334dadcfc7b9 Mon Sep 17 00:00:00 2001 From: David Auer Date: Thu, 26 Jan 2023 15:43:35 +0100 Subject: [PATCH 4/4] Second format run --- cnping.c | 10 +++++----- error_handling.h | 35 ++++++++++++++++++++++++++++------- httping.c | 4 ++-- httping.h | 8 ++++---- ping.c | 12 ++++++------ ping.h | 30 +++++++++++++++--------------- resolve.c | 4 ++-- resolve.h | 11 ++++++----- searchnet.c | 2 +- 9 files changed, 69 insertions(+), 47 deletions(-) diff --git a/cnping.c b/cnping.c index 1266da5..ff874ee 100644 --- a/cnping.c +++ b/cnping.c @@ -399,11 +399,11 @@ void DrawFrameHistogram() #ifdef WIN32 snprintf( stt, 1024, "Host: %s\nHistorical max %9.2fms\nBiggest interval%9.2fms\nHistorical packet loss " - "%I64u/%I64u = %6.3f%%", + "%I64u/%I64u = %6.3f%%", #else snprintf( stt, 1024, "Host: %s\nHistorical max %9.2fms\nBiggest interval%9.2fms\nHistorical packet loss " - "%lu/%lu = %6.3f%%", + "%lu/%lu = %6.3f%%", #endif pinghost, globmaxtime * 1000.0, globinterval * 1000.0, globallost, globalrx, globallost * 100.0 / ( globalrx + globallost ) ); @@ -722,12 +722,12 @@ int main( int argc, const char **argv ) ERRM( "cnping " VERSION " Usage: cnping [host] [period] [extra size] [y-axis scaling] [window title]\n" " (-h) [host] -- domain, IP address of ping target for ICMP or " - "http host, i.e. http://google.com\n" + "http host, i.e. http://google.com\n" " (-p) [period] -- period in seconds (optional), default 0.02 \n" " (-s) [extra size] -- ping packet extra size (above 12), optional, " - "default = 0 \n" + "default = 0 \n" " (-y) [const y-axis scaling] -- use a fixed scaling factor instead of auto " - "scaling (optional)\n" + "scaling (optional)\n" " (-t) [window title] -- the title of the window (optional)\n" " (-I) [interface] -- Sets source interface (i.e. eth0)\n" ); return -1; diff --git a/error_handling.h b/error_handling.h index 673c3fa..b4509e0 100644 --- a/error_handling.h +++ b/error_handling.h @@ -1,22 +1,43 @@ #ifndef _ERROR_HANDLING #define _ERROR_HANDLING -extern char errbuffer[1024]; +extern char errbuffer[ 1024 ]; #ifdef WIN32 #ifndef _MSC_VER -#define ERRM(x...) { sprintf( errbuffer, x ); MessageBox( 0, errbuffer, "cnping", 0 ); } -#define ERRMB(x...) { sprintf( errbuffer, x ); } +#define ERRM( x... ) \ + { \ + sprintf( errbuffer, x ); \ + MessageBox( 0, errbuffer, "cnping", 0 ); \ + } +#define ERRMB( x... ) \ + { \ + sprintf( errbuffer, x ); \ + } #else -#define ERRM(...) { sprintf( errbuffer, __VA_ARGS__ ); MessageBox( 0, errbuffer, "cnping", 0 ); } -#define ERRMB(...) { sprintf( errbuffer, __VA_ARGS__ ); } +#define ERRM( ... ) \ + { \ + sprintf( errbuffer, __VA_ARGS__ ); \ + MessageBox( 0, errbuffer, "cnping", 0 ); \ + } +#define ERRMB( ... ) \ + { \ + sprintf( errbuffer, __VA_ARGS__ ); \ + } #endif #else -#define ERRM(x...) { fprintf( stderr, x ); } -#define ERRMB(x...) { sprintf( errbuffer, x); fprintf( stderr, x ); } +#define ERRM( x... ) \ + { \ + fprintf( stderr, x ); \ + } +#define ERRMB( x... ) \ + { \ + sprintf( errbuffer, x ); \ + fprintf( stderr, x ); \ + } #endif diff --git a/httping.c b/httping.c index 70f54b8..bd326a8 100644 --- a/httping.c +++ b/httping.c @@ -20,10 +20,10 @@ #endif #define SOL_TCP IPPROTO_TCP #else -#include +#include #include #include -#include +#include #endif #include "error_handling.h" diff --git a/httping.h b/httping.h index 8e65f87..9fde037 100644 --- a/httping.h +++ b/httping.h @@ -1,12 +1,12 @@ #ifndef _HTTPING_H #define _HTTPING_H -//Callbacks (when started/received) +// Callbacks (when started/received) void HTTPingCallbackStart( int seqno ); void HTTPingCallbackGot( int seqno ); -//addy should be google.com/blah or something like that. Do not include prefixing http://. Port numbers OK. -int StartHTTPing( const char * addy, double minperiod, const char * device); +// addy should be google.com/blah or something like that. Do not include prefixing http://. Port +// numbers OK. +int StartHTTPing( const char *addy, double minperiod, const char *device ); #endif - diff --git a/ping.c b/ping.c index f271152..9aedd88 100644 --- a/ping.c +++ b/ping.c @@ -166,26 +166,26 @@ void ping( struct sockaddr *addr, socklen_t addr_len ) #ifndef MINGW_BUILD #pragma comment( lib, "Ws2_32.lib" ) #endif +#include #include #include #include -#include #else // ! WIN32 #ifdef __FreeBSD__ #include #endif -#include -#include -#include #include +#include +#include +#include #if defined( __APPLE__ ) || defined( __FreeBSD__ ) #ifndef SOL_IP #define SOL_IP IPPROTO_IP #endif #endif +#include #include #include -#include #endif #include "rawdraw/os_generic.h" @@ -453,7 +453,7 @@ void ping_setup( const char *strhost, const char *device ) if ( setsockopt( sd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen( device ) + 1 ) != 0 ) { ERRM( "Error: Failed to set Device option. Are you root? Or can do sock_raw " - "sockets?\n" ); + "sockets?\n" ); exit( -1 ); } } diff --git a/ping.h b/ping.h index e6b8463..515d124 100644 --- a/ping.h +++ b/ping.h @@ -3,31 +3,31 @@ #include #ifdef WIN32 - typedef int socklen_t; - struct sockaddr; +typedef int socklen_t; +struct sockaddr; #else - #include +#include #endif -unsigned short checksum(const unsigned char *b, uint16_t len); +unsigned short checksum( const unsigned char *b, uint16_t len ); -//Callback (when received) -void display(uint8_t *buf, int bytes); +// Callback (when received) +void display( uint8_t *buf, int bytes ); -//Callback (before sending) -//return value = # of bytes to send in ping message. -int load_ping_packet( uint8_t * buffer, int buffersize ); +// Callback (before sending) +// return value = # of bytes to send in ping message. +int load_ping_packet( uint8_t *buffer, int buffersize ); void listener(); -void ping(struct sockaddr *addr, socklen_t addr_len ); -void do_pinger( ); +void ping( struct sockaddr *addr, socklen_t addr_len ); +void do_pinger(); -//If pingperiodseconds = -1, run ping/do_pinger once and exit. +// If pingperiodseconds = -1, run ping/do_pinger once and exit. extern float pingperiodseconds; -extern int precise_ping; //if 0, use minimal CPU, but ping send-outs are only approximate, if 1, spinlock until precise time for ping is hit. +extern int precise_ping; // if 0, use minimal CPU, but ping send-outs are only approximate, if 1, + // spinlock until precise time for ping is hit. extern int ping_failed_to_send; -void ping_setup(const char * strhost, const char * device); +void ping_setup( const char *strhost, const char *device ); #endif - diff --git a/resolve.c b/resolve.c index d528ee3..f35b9d1 100644 --- a/resolve.c +++ b/resolve.c @@ -10,9 +10,9 @@ #else // !WIN32 #include // inet_pton (parsing ipv4 and ipv6 notation) -#include -#include #include +#include +#include #endif int resolveName( struct sockaddr *addr, socklen_t *addr_len, const char *hostname, int family ) diff --git a/resolve.h b/resolve.h index 79f7b2a..ad0f391 100644 --- a/resolve.h +++ b/resolve.h @@ -2,10 +2,10 @@ #define _RESOLVE_H #ifdef WIN32 - typedef int socklen_t; - struct sockaddr; +typedef int socklen_t; +struct sockaddr; #else - #include +#include #endif // try to parse hostname @@ -13,7 +13,8 @@ // * as ipv6 notation (abcd:ef00::1) // * as hostname (resolve DNS) // returns 1 on success -// family can be used to force ipv4 or ipv6. Use AF_UNSPEC (allow both), AF_INET or AF_INET6 to force ipv4 or ipv6 -int resolveName(struct sockaddr* addr, socklen_t* addr_len, const char* hostname, int family); +// family can be used to force ipv4 or ipv6. Use AF_UNSPEC (allow both), AF_INET or AF_INET6 to +// force ipv4 or ipv6 +int resolveName( struct sockaddr *addr, socklen_t *addr_len, const char *hostname, int family ); #endif diff --git a/searchnet.c b/searchnet.c index 6224061..b7e9611 100644 --- a/searchnet.c +++ b/searchnet.c @@ -59,7 +59,7 @@ int main( int argc, char **argv ) if ( argc != 4 ) { fprintf( stderr, "Usage: [searchnet IP net] [mask (single #, i.e. 24)] [speed (in seconds " - "per attempt)]\n" ); + "per attempt)]\n" ); return -1; }