-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
429 lines (366 loc) · 12.6 KB
/
main.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
// Copyright (C) 2022 Lucas Mulling, Mateus Edival
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#define _GNU_SOURCE // for NI_MAXHOST apparently
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <linux/icmp.h>
#include <netdb.h>
#include <netinet/ip.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
const char* dha = NULL; // destiny host address
uint32_t ttl = 64;
uint64_t seq = 1;
uint64_t sentnum = 0;
uint64_t recvnum = 0;
uint64_t leftnum = 0;
// time is stored in usec
suseconds_t hrtt = 0;
suseconds_t lrtt = 0x7FFFFFFF;
suseconds_t ortt = 0;
suseconds_t nrtt = 0;
#define MAXDUP 0x1000 // from ping.c
#define PAYLOADSIZE 56
#define RCVTIMEO 1
uint8_t recvtable[MAXDUP / 8] = { 0 };
bool r = true; // running
bool f = false;
#define PACKETSIZE sizeof(struct iphdr) + sizeof(struct icmphdr) + PAYLOADSIZE
#define ICMPOFF sizeof(struct iphdr)
#define TIMEOFF ICMPOFF + sizeof(struct icmphdr)
uint8_t packetreq[PACKETSIZE];
uint8_t packetrep[PACKETSIZE];
struct iphdr* ip = (struct iphdr*)packetreq;
struct icmphdr* icmp = (struct icmphdr*)(packetreq + ICMPOFF);
struct timeval* timestamp = (struct timeval*)(packetreq + TIMEOFF);
struct iphdr* iprep = (struct iphdr*)packetrep;
struct icmphdr* icmprep = (struct icmphdr*)(packetrep + ICMPOFF);
struct timeval* timestamprep = (struct timeval*)(packetrep + TIMEOFF);
static uint32_t (*sleepfn)(const uint32_t) = sleep;
static uint32_t nullfn(const uint32_t __attribute__((unused)) x) {
;
return 0;
}
static void usage(void) {
fprintf(stderr,
"usage:\n"
"\t./pong [target] [[-f] [-t time_to_live]]\n");
}
// source: https://datatracker.ietf.org/doc/html/rfc1071
static inline __attribute__((always_inline)) uint16_t checksum(
const uint16_t* buffer, size_t len) {
register uint64_t sum = 0;
while (len > 1) {
sum += *buffer++;
len -= 2;
}
if (len) sum += *(uint8_t*)buffer;
sum = (sum & 0xFFFF) + (sum >> 16);
sum += (sum >> 16);
return (uint16_t)~sum;
}
#ifdef DEBUG
#define ERROR(msg) \
fprintf(stderr, __FILE__ ":%d error: %s \n", __LINE__, msg); \
exit(1);
#else
#define ERROR(msg) \
fprintf(stderr, "pong: error: %s\n", msg); \
exit(1);
#endif
static const char* get_host_addr(const char* hname) {
static char host[NI_MAXHOST] = { 0 };
struct addrinfo h;
struct addrinfo* res;
memset(&h, 0, sizeof(struct addrinfo));
h.ai_family = AF_INET; // for ipv4
uint32_t ret;
if ((ret = getaddrinfo(hname, NULL, &h, &res))) {
ERROR(gai_strerror(ret));
}
// get only the first address (if multiple are returned)
getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof(host), NULL, 0,
NI_NUMERICHOST);
freeaddrinfo(res);
return host; // this is fine because we only run this one time
}
static int initsock(const uint16_t __attribute__((unused)) pid) {
int socketd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (socketd < 0) {
ERROR("Fail to create a socket, run with root privileges...");
}
int on = 1;
if (setsockopt(socketd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) == -1) {
ERROR("setsockopt IP_HDRINCL");
}
struct timeval timeo;
timeo.tv_sec = f ? 0 : RCVTIMEO;
timeo.tv_usec = 1;
if (setsockopt(socketd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo)) ==
-1) {
ERROR("setsockopt SO_RCVTIMEO");
}
timeo.tv_usec = 0;
if (setsockopt(socketd, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo)) ==
-1) {
ERROR("setsockopt SO_SNDTIMEO");
}
struct icmp_filter filter;
filter.data = ~((1 << ICMP_DEST_UNREACH) | (1 << ICMP_TIME_EXCEEDED) |
(1 << ICMP_ECHOREPLY));
if (setsockopt(socketd, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter)) ==
-1) {
ERROR("setsockopt ICMP_FILTER");
}
// TODO: figure this out
// struct sock_fprog idfilter;
// setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof filter);
return socketd;
}
static inline bool checkdup(const uint16_t bit) {
if (recvtable[bit >> 3] & (1 << (bit & 0x07))) return true;
recvtable[bit >> 3] |= (1 << (bit & 0x07));
return false;
}
static inline void calcrtt(const struct timeval* timestamprep) {
struct timeval timedif;
struct timeval timenow;
gettimeofday(&timenow, NULL);
timersub(&timenow, timestamprep,
&timedif); // use the time stored in the packet
nrtt = timedif.tv_sec * 10000 + timedif.tv_usec;
if (hrtt < nrtt) hrtt = nrtt;
if (lrtt > nrtt) lrtt = nrtt;
if (!ortt) {
ortt = nrtt;
} else {
ortt = (suseconds_t)((7 / 8.) * (float)ortt) + ((float)nrtt * (1 / 8.));
}
}
static inline void initiphdr(const in_addr_t daddr) {
ip->version = 4;
ip->ihl = 5;
ip->tos = 0;
ip->tot_len = htons(PAYLOADSIZE);
ip->protocol = IPPROTO_ICMP;
ip->ttl = ttl;
ip->daddr = daddr;
}
static inline void initicmphdr(uint16_t id) {
icmp->type = ICMP_ECHO;
icmp->code = 0;
icmp->un.echo.sequence = htons((uint16_t)seq);
icmp->un.echo.id = id;
}
static inline bool chkchksum(struct icmphdr* icmprep) {
uint16_t chksum = icmprep->checksum;
icmprep->checksum = 0;
return chksum == checksum((const uint16_t*)icmprep,
sizeof(struct icmphdr) + PAYLOADSIZE);
}
// source: RFC 792
static const char* icmp_dest_unreach_code[] = {
[0] = "net unreachable",
[1] = "host unreachable",
[2] = "protocol unreachable",
[3] = "port unreachable",
[4] = "fragmentation needed and DF set",
[5] = "source route failed",
""
};
// source: RFC 792
static const char* icmp_time_exceeded_code[] = {
[0] = "time to live exceeded in transit",
[1] = "fragment reassembly time exceeded",
""
};
void sterrh() {
switch (errno) {
case EHOSTUNREACH:
fprintf(stderr, "ERROR: host unreachable!\n");
fflush(stderr);
break;
case ENETUNREACH:
fprintf(stderr, "ERROR: network unreachable!\n");
fflush(stderr);
break;
case ENETDOWN:
fprintf(stderr, "ERROR: network down!\n");
fflush(stderr);
break;
}
}
void ping(const in_addr_t daddr) {
pid_t pid = getpid();
uint16_t id = (uint16_t)(pid >> 16) ^ (pid & 0xFF);
int socketd = initsock(id);
initiphdr(daddr);
initicmphdr(id);
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = daddr;
memset(&servaddr.sin_zero, 0, sizeof(servaddr.sin_zero));
int32_t sentsize = 0;
int32_t recvsize = 0;
fprintf(stdout, "PONGING %s %d bytes of data (%lu total).\n", dha,
PAYLOADSIZE, PACKETSIZE);
fflush(stdout);
while (r || leftnum) {
recvtable[((sentnum + 1) % MAXDUP) >> 3] &=
~(1 << (((sentnum + 1) % MAXDUP) & 0x07));
gettimeofday(timestamp, NULL);
icmp->checksum = 0;
icmp->checksum =
checksum((uint16_t*)icmp, sizeof(struct icmphdr) + PAYLOADSIZE);
// TODO: replace sendto and recvfrom with sendmsg and recvmsg :)
if (!leftnum &&
(sentnum++, sentsize = sendto(socketd, packetreq, PACKETSIZE, 0,
(struct sockaddr*)&servaddr,
sizeof(servaddr))) < 1) {
sterrh();
sleepfn(RCVTIMEO);
continue; // if we can't send keep trying
} else if (errno & EINTR) {
errno = 0;
continue;
}
recv:
if ((recvsize = recvfrom(socketd, packetrep, PACKETSIZE, MSG_WAITALL,
NULL, NULL)) == -1 &&
!(errno & EINTR) && recvsize != PACKETSIZE) {
// we didn't get a reply in time send again with the same seq, if
// flooding don't wait
if (f)
goto incs;
else
continue;
} else if (errno & EINTR) {
if (!f)
--sentnum; // if we got were recvfrom was interrupted, ignore
// the last package we sent
errno = 0;
continue;
}
if (!chkchksum(icmprep)) {
fprintf(stdout, "\x1b[5mBAD CHECKSUM!!!\n\x1b[m");
goto chkf;
}
switch ((++recvnum, icmprep->type)) {
case ICMP_ECHOREPLY: {
// got something that is not ours
if (icmprep->un.echo.id != id) {
--recvnum;
goto recv;
}
struct timeval tsp;
memcpy(&tsp, timestamprep, sizeof(struct timeval));
calcrtt(&tsp);
fprintf(stdout,
"%d bytes from %s icmp_seq=%d ttl=%u time=%.1fms",
recvsize, dha, ntohs(icmprep->un.echo.sequence),
iprep->ttl, nrtt / 1000.0);
fprintf(stdout,
(checkdup(htons(icmprep->un.echo.sequence) % MAXDUP)
? "\x1b[5m DUP!\x1b[0m\n"
: "\n"));
// following the behaviour of ping, DUPs are not counted as lost
// packets
} break;
case ICMP_TIME_EXCEEDED:
fprintf(stdout, "time to live exceeded with ttl= %d code= %s\n",
ttl,
icmp_time_exceeded_code[icmprep->code >= 2
? 2
: icmprep->code]);
break;
case ICMP_DEST_UNREACH:
// don't count DEST_UNREAD as received packets
--recvnum;
fprintf(
stdout, "destination host unreachable! code= %s\n",
icmp_dest_unreach_code[icmprep->code >= 6 ? 6
: icmprep->code]);
break;
default:
// we can't get here because of the filter
break;
}
chkf:
fflush(stdout);
sleepfn(RCVTIMEO);
incs:
if (leftnum)
--leftnum;
else
icmp->un.echo.sequence = htons(++seq);
}
}
static void siginth(int x) {
(void)(x);
r = false;
if (f) leftnum = sentnum - recvnum;
}
static void results(void) {
if (sentnum | recvnum) fprintf(stdout, "\nRESULTS:\n");
if (sentnum && recvnum <= sentnum)
fprintf(stdout, "sent=%lu received=%lu (%.1f%% packet loss.)\n",
sentnum, recvnum, 100 - (100 * recvnum / (float)sentnum));
if (recvnum && ortt)
fprintf(stdout, "min=%.1fms rtt=%.1fms max=%.1fms\n", lrtt / 1000.0,
ortt / 1000.0, hrtt / 1000.0);
}
int main(const int argc, const char** argv) {
if (argc < 2) {
usage();
exit(0);
}
for (int i = 2; i < argc;) {
if (argv[i][0] != '-' || strlen(argv[i]) != 2) {
die:
atexit(usage);
ERROR("Unkown argument...");
}
switch (argv[i][1]) {
case 'f':
f = true;
sleepfn = nullfn;
++i;
break;
case 't':
ttl = atoi(argv[i + 1]);
i += 2;
break;
default:
goto die;
}
}
struct sigaction new;
new.sa_handler = siginth;
new.sa_flags = 0;
sigemptyset(&new.sa_mask);
// NOTE: we can't use signal here because it fucks with the syscalls
// and we lose a packet. Default to the Linus way of handling this
// even tough is "wrong"
// see: https://stackoverflow.com/a/3800915
sigaction(SIGINT, &new, NULL); // handle ^C (ctrl-c)
ping(inet_addr((dha = get_host_addr(argv[1]), atexit(results), dha)));
return 0;
}