-
Notifications
You must be signed in to change notification settings - Fork 35
/
ping.c
604 lines (509 loc) · 12.2 KB
/
ping.c
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
//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 <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "ping.h"
#include "error_handling.h"
#include "resolve.h"
#ifdef TCC
#include "tccheader.h"
#endif
int ping_failed_to_send;
float pingperiodseconds;
int precise_ping;
struct sockaddr_in6 psaddr;
socklen_t psaddr_len;
int using_regular_ping;
#ifdef WIN_USE_NO_ADMIN_PING
#ifdef TCC
//...
#else
#include <inaddr.h>
#include <ws2tcpip.h>
#include <ipexport.h>
#include <icmpapi.h>
#include <windows.h>
#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")
#endif
static og_sema_t s_disp;
static og_sema_t s_ping;
void ping_setup(const char * strhost, const char * device)
{
// resolve host
psaddr_len = sizeof(psaddr);
if( strhost )
resolveName((struct sockaddr*) &psaddr, &psaddr_len, strhost, AF_INET); // only resolve ipv4 on windows
else
psaddr.sin6_family = AF_INET;
s_disp = OGCreateSema();
s_ping = OGCreateSema();
//This function is executed first.
}
void listener()
{
static uint8_t listth;
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.
while(1) { OGSleep( 100000 ); }
return;
}
static HANDLE pinghandles[PINGTHREADS];
static void * pingerthread( void * v )
{
uint8_t ping_payload[MAX_PING_SIZE];
HANDLE ih = *((HANDLE*)v);
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];
} repl;
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();
OGLockSema( s_disp );
if( !res )
{
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 singleping(struct sockaddr *addr, socklen_t addr_len )
{
int i;
(void) addr;
(void) addr_len;
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 );
}
static int did_init_threads = 0;
if( !did_init_threads )
{
did_init_threads = 1;
//Launch pinger threads
for( i = 0; i < PINGTHREADS; i++ )
{
HANDLE ih = pinghandles[i] = IcmpCreateFile();
if( ih == INVALID_HANDLE_VALUE )
{
ERRM( "Cannot create ICMP thread %d\n", i );
exit( 0 );
}
OGCreateThread( pingerthread, &pinghandles[i] );
}
}
//This function is executed as a thread after setup.
if( i >= PINGTHREADS-1 ) i = 0;
else i++;
OGUnlockSema( s_ping );
}
void ping(struct sockaddr *addr, socklen_t addr_len )
{
int i;
(void) addr;
(void) addr_len;
using_regular_ping = 1;
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++ )
{
HANDLE ih = pinghandles[i] = IcmpCreateFile();
if( ih == INVALID_HANDLE_VALUE )
{
ERRM( "Cannot create ICMP thread %d\n", i );
exit( 0 );
}
OGCreateThread( pingerthread, &pinghandles[i] );
}
//This function is executed as a thread after setup.
while(1)
{
if( i >= PINGTHREADS-1 ) i = 0;
else i++;
OGUnlockSema( s_ping );
OGUSleep( (int)(pingperiodseconds * 1000000) );
}
}
#else // ! WIN_USE_NO_ADMIN_PING
//The normal way to do it - only problem is Windows needs admin privs.
#ifdef WIN32
#include <winsock2.h>
#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")
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdint.h>
#else // ! WIN32
#ifdef __FreeBSD__
#include <netinet/in.h>
#endif
#include <unistd.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#ifndef SOL_IP
#define SOL_IP IPPROTO_IP
#endif
#endif
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/icmp6.h>
#endif
#include "rawdraw/os_generic.h"
#if defined WIN32 || defined __APPLE__
struct icmphdr
{
uint8_t type;
uint8_t code;
uint16_t checksum;
union
{
struct
{
uint16_t id;
uint16_t sequence;
} echo;
uint32_t gateway;
struct
{
uint16_t __unused;
uint16_t mtu;
} frag;
} un;
};
#endif
#define PACKETSIZE 65536
struct packet
{
#ifdef __FreeBSD__
struct icmp hdr;
unsigned char msg[PACKETSIZE-sizeof(struct icmp)];
#else
struct icmphdr hdr;
unsigned char msg[PACKETSIZE-sizeof(struct icmphdr)];
#endif
};
int sd;
int pid=-1;
uint16_t checksum( const unsigned char * start, uint16_t len )
{
uint16_t i;
const uint16_t * wptr = (uint16_t*) start;
uint32_t csum = 0;
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)
{
const int val=255;
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)
{
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)
{
assert(psaddr.sin6_family == AF_INET || psaddr.sin6_family == AF_INET6);
if( bytes == -1 ) return 0;
if( psaddr.sin6_family == AF_INET ) // ipv4 compare
{
if( buf[9] != IPPROTO_ICMP ) return 0;
if( buf[20] != ICMP_ECHOREPLY ) return 0;
}
else if( psaddr.sin6_family == AF_INET6 ) // ipv6 compare
{
if( buf[0] != ICMP6_ECHO_REPLY ) return 0;
}
return 1;
}
int createSocket()
{
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);
}
// invalid af_family
return -1;
}
void listener()
{
#ifndef WIN32
int sd = createSocket();
setTTL(sd);
#endif
struct sockaddr_in6 addr;
unsigned char buf[66000];
#ifdef WIN32
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
#endif
for (;;)
{
socklen_t addrlenval=sizeof(addr);
int bytes;
#ifdef WIN32
WSAPOLLFD fda[1];
fda[0].fd = sd;
fda[0].events = POLLIN;
WSAPoll(fda, 1, 10);
#endif
keep_retry_quick:
bytes = recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlenval );
if( !isICMPResponse(buf, bytes) ) continue;
// compare the sender
if( using_regular_ping && memcmp(&addr, &psaddr, addrlenval) != 0 ) continue;
// sizeof(packet.hdr) + 20
int offset = 0;
if(addr.sin6_family == AF_INET) // ipv4
{
#ifdef __FreeBSD__
offset = 48;
#else
offset = 28;
#endif
}
else // ipv6
{
offset = 8;
}
if ( bytes > 0 )
display(buf + offset, bytes - offset );
else
{
ERRM("Error: recvfrom failed");
}
goto keep_retry_quick;
}
ERRM( "Fault on listen().\n" );
exit( 0 );
}
void singleping(struct sockaddr *addr, socklen_t addr_len )
{
int cnt=1;
#ifdef WIN32
{
//Setup windows socket for nonblocking io.
unsigned long iMode = 1;
ioctlsocket(sd, FIONBIO, &iMode);
}
#else
if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )
ERRM("Warning: Request nonblocking I/O failed.");
#endif
double stime = OGGetAbsoluteTime();
struct packet pckt;
{
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.
#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 );
#else
pckt.hdr.code = 0;
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 );
#endif
int sr = sendto(sd, (char*)&pckt, sizeof( pckt.hdr ) + rsize , 0, addr, addr_len);
if( sr <= 0 )
{
ping_failed_to_send = 1;
if( using_regular_ping )
{
ERRMB("Ping send failed:\n%s (%d)\n", strerror(errno), errno);
}
}
else
{
ping_failed_to_send = 0;
}
}
}
void ping(struct sockaddr *addr, socklen_t addr_len )
{
int cnt=1;
using_regular_ping = 1;
#ifdef WIN32
{
//Setup windows socket for nonblocking io.
unsigned long iMode = 1;
ioctlsocket(sd, FIONBIO, &iMode);
}
#else
if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )
ERRM("Warning: Request nonblocking I/O failed.");
#endif
double stime = OGGetAbsoluteTime();
struct packet pckt;
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.
#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 );
#else
pckt.hdr.code = 0;
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 );
#endif
int sr = sendto(sd, (char*)&pckt, sizeof( pckt.hdr ) + rsize , 0, addr, addr_len);
if( sr <= 0 )
{
ping_failed_to_send = 1;
if( using_regular_ping )
{
ERRMB("Ping send failed:\n%s (%d)\n", strerror(errno), errno);
}
}
else
{
ping_failed_to_send = 0;
}
if( precise_ping )
{
double ctime;
do
{
ctime = OGGetAbsoluteTime();
if( pingperiodseconds >= 1000 ) stime = ctime;
} while( ctime < stime + pingperiodseconds );
stime += pingperiodseconds;
}
else
{
if( pingperiodseconds > 0 )
{
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.
}
void ping_setup(const char * strhost, const char * device)
{
pid = getpid();
#ifdef WIN32
WSADATA wsaData;
int r = WSAStartup(MAKEWORD(2,2), &wsaData);
if( r )
{
ERRM( "Fault in WSAStartup\n" );
exit( -2 );
}
#endif
#ifdef WIN32
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)
{
printf( "Warning: No IP_TTL.\n" );
}
}
#else
// resolve host
psaddr_len = sizeof(psaddr);
if( strhost )
resolveName((struct sockaddr*) &psaddr, &psaddr_len, strhost, AF_UNSPEC);
else
psaddr.sin6_family = AF_INET;
sd = createSocket();
setTTL(sd);
if(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");
exit( -1 );
}
}
#endif
if ( sd < 0 )
{
ERRM("Error: Could not create raw socket\n");
exit(0);
}
}
#endif // WIN_USE_NO_ADMIN_PING
void do_pinger( )
{
ping((struct sockaddr*) &psaddr, psaddr_len );
}
// used by the ERRMB makro from error_handling.h
char errbuffer[1024];