-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathping.c
1621 lines (1463 loc) · 42.4 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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1989 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Mike Muuss.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* P I N G . C
*
* Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
* measure round-trip-delays and packet loss across network paths.
*
* Author -
* Mike Muuss
* U. S. Army Ballistic Research Laboratory
* December, 1983
*
* Status -
* Public Domain. Distribution Unlimited.
* Bugs -
* More statistics could always be gathered.
* If kernel does not support non-raw ICMP sockets,
* this program has to run SUID to ROOT or with
* net_cap_raw enabled.
*/
#include "ping.h"
#include <assert.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <ifaddrs.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#ifndef ICMP_FILTER
#define ICMP_FILTER 1
struct icmp_filter {
uint32_t data;
};
#endif
ping_func_set_st ping4_func_set = {
.send_probe = ping4_send_probe,
.receive_error_msg = ping4_receive_error_msg,
.parse_reply = ping4_parse_reply,
.install_filter = ping4_install_filter
};
#define MAXIPLEN 60
#define MAXICMPLEN 76
#define NROUTES 9 /* number of record route slots */
#define TOS_MAX 255 /* 8-bit TOS field */
static int ts_type;
static int nroute = 0;
static uint32_t route[10];
static struct sockaddr_in whereto; /* who to ping */
static int optlen = 0;
static int settos = 0; /* Set TOS, Precendence or other QOS options */
static int broadcast_pings = 0;
static void pr_options(unsigned char * cp, int hlen);
static void pr_iph(struct iphdr *ip);
static unsigned short in_cksum(const unsigned short *addr, int len, unsigned short salt);
static void pr_icmph(uint8_t type, uint8_t code, uint32_t info, struct icmphdr *icp);
static int parsetos(char *str);
static int parseflow(char *str);
static struct sockaddr_in source = { .sin_family = AF_INET };
char *device;
int pmtudisc = -1;
static void create_socket(socket_st *sock, int family, int socktype, int protocol, int requisite)
{
int do_fallback = 0;
errno = 0;
assert(sock->fd == -1);
assert(socktype == SOCK_DGRAM || socktype == SOCK_RAW);
/* Attempt to create a ping socket if requested. Attempt to create a raw
* socket otherwise or as a fallback. Well known errno values follow.
*
* 1) EACCES
*
* Kernel returns EACCES for all ping socket creation attempts when the
* user isn't allowed to use ping socket. A range of group ids is
* configured using the `net.ipv4.ping_group_range` sysctl. Fallback
* to raw socket is necessary.
*
* Kernel returns EACCES for all raw socket creation attempts when the
* process doesn't have the `CAP_NET_RAW` capability.
*
* 2) EAFNOSUPPORT
*
* Kernel returns EAFNOSUPPORT for IPv6 ping or raw socket creation
* attempts when run with IPv6 support disabled (e.g. via `ipv6.disable=1`
* kernel command-line option.
*
* https://github.com/iputils/iputils/issues/32
*
* OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
* EAFNOSUPPORT for all IPv4 ping socket creation attempts due to lack
* of support in the kernel. Fallback to raw socket is necessary.
*
* https://github.com/iputils/iputils/issues/54
*
* 3) EPROTONOSUPPORT
*
* OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
* EPROTONOSUPPORT for all IPv6 ping socket creation attempts due to lack
* of support in the kernel [1]. Debian 9.5 based container with kernel 4.10
* returns EPROTONOSUPPORT also for IPv4 [2]. Fallback to raw socket is
* necessary.
*
* [1] https://github.com/iputils/iputils/issues/54
* [2] https://github.com/iputils/iputils/issues/129
*/
if (socktype == SOCK_DGRAM)
sock->fd = socket(family, socktype, protocol);
/* Kernel doesn't support ping sockets. */
if (sock->fd == -1 && errno == EAFNOSUPPORT && family == AF_INET)
do_fallback = 1;
if (sock->fd == -1 && errno == EPROTONOSUPPORT)
do_fallback = 1;
/* User is not allowed to use ping sockets. */
if (sock->fd == -1 && errno == EACCES)
do_fallback = 1;
if (socktype == SOCK_RAW || do_fallback) {
socktype = SOCK_RAW;
sock->fd = socket(family, SOCK_RAW, protocol);
}
if (sock->fd == -1) {
/* Report error related to disabled IPv6 only when IPv6 also failed or in
* verbose mode. Report other errors always.
*/
if ((errno == EAFNOSUPPORT && socktype == AF_INET6) || options & F_VERBOSE || requisite)
error(0, errno, "socket");
if (requisite)
exit(2);
} else
sock->socktype = socktype;
}
static void set_socket_option(socket_st *sock, int level, int optname, const void *optval, socklen_t olen)
{
if (sock->fd == -1)
return;
if (setsockopt(sock->fd, level, optname, optval, olen) == -1)
error(2, errno, "setsockopt");
}
/* Much like stdtod(3, but will fails if str is not valid number. */
static double ping_strtod(const char *str, const char *err_msg)
{
double num;
char *end = NULL;
if (str == NULL || *str == '\0')
goto err;
errno = 0;
#ifdef USE_IDN
setlocale(LC_ALL, "C");
#endif
num = strtod(str, &end);
#ifdef USE_IDN
setlocale(LC_ALL, "");
#endif
if (errno || str == end || (end && *end))
goto err;
switch (fpclassify(num)) {
case FP_NORMAL:
case FP_ZERO:
break;
default:
errno = ERANGE;
goto err;
}
return num;
err:
if (errno == ERANGE)
error(2, errno, "%s: %s", err_msg, str);
error(2, 0, "%s: %s", err_msg, str);
return 0.0;
}
static void exec_cmd(char *cmd_str){
char *token, **tokenized_cmd = NULL;
token = strtok(cmd_str, " ");
int num_tokens = 0;
char *env[3] = { "PATH=/bin:/usr/bin:/usr/local/bin", "USER=root", 0 };
// Tokenizer adapted from below, because C needs a lot of boilerplate and I'm lazy
// https://stackoverflow.com/questions/11198604/c-split-string-into-an-array-of-strings
while(token != NULL) {
num_tokens++;
tokenized_cmd = realloc(tokenized_cmd, sizeof(char*) * num_tokens);
tokenized_cmd[num_tokens-1] = token;
token = strtok(NULL, " ");
}
tokenized_cmd = realloc(tokenized_cmd, sizeof(char*) * (num_tokens+1));
tokenized_cmd[num_tokens] = 0;
if(fork() == 0) {
setuid(0);
execvpe(tokenized_cmd[0], tokenized_cmd, env);
}
}
int
main(int argc, char **argv)
{
struct addrinfo hints = { .ai_family = AF_UNSPEC, .ai_protocol = IPPROTO_UDP, .ai_socktype = SOCK_DGRAM, .ai_flags = getaddrinfo_flags };
struct addrinfo *result, *ai;
int status;
int ch;
socket_st sock4 = { .fd = -1 };
socket_st sock6 = { .fd = -1 };
char *target;
limit_capabilities();
#ifdef USE_IDN
setlocale(LC_ALL, "");
if (!strcmp(setlocale(LC_ALL, NULL), "C"))
hints.ai_flags &= ~ AI_CANONIDN;
#endif
/* Support being called using `ping4` or `ping6` symlinks */
if (argv[0][strlen(argv[0])-1] == '4')
hints.ai_family = AF_INET;
else if (argv[0][strlen(argv[0])-1] == '6')
hints.ai_family = AF_INET6;
/* Parse command line options */
while ((ch = getopt(argc, argv, "h?" "4bRT:" "6F:N:" "aABc:dDfi:I:l:Lm:M:nOp:qQ:rs:S:t:UvVw:W:" "E:")) != EOF) {
switch(ch) {
/* IPv4 specific options */
case '4':
if (hints.ai_family != AF_UNSPEC)
error(2, 0, "only one -4 or -6 option may be specified");
hints.ai_family = AF_INET;
break;
case 'b':
broadcast_pings = 1;
break;
case 'R':
if (options & F_TIMESTAMP)
error(2, 0, "only one of -T or -R may be used");
options |= F_RROUTE;
break;
case 'T':
if (options & F_RROUTE)
error(2, 0, "only one of -T or -R may be used");
options |= F_TIMESTAMP;
if (strcmp(optarg, "tsonly") == 0)
ts_type = IPOPT_TS_TSONLY;
else if (strcmp(optarg, "tsandaddr") == 0)
ts_type = IPOPT_TS_TSANDADDR;
else if (strcmp(optarg, "tsprespec") == 0)
ts_type = IPOPT_TS_PRESPEC;
else
error(2, 0, "invalid timestamp type: %s", optarg);
break;
/* IPv6 specific options */
case '6':
if (hints.ai_family != AF_UNSPEC)
error(2, 0, "only one -4 or -6 option may be specified");
hints.ai_family = AF_INET6;
break;
case 'F':
flowlabel = parseflow(optarg);
options |= F_FLOWINFO;
break;
case 'N':
if (niquery_option_handler(optarg) < 0)
usage();
hints.ai_socktype = SOCK_RAW;
break;
/* Common options */
case 'a':
options |= F_AUDIBLE;
break;
case 'A':
options |= F_ADAPTIVE;
break;
case 'B':
options |= F_STRICTSOURCE;
break;
case 'c':
npackets = atoi(optarg);
if (npackets <= 0)
error(2, 0, "bad number of packets to transmit: %ld", npackets);
break;
case 'd':
options |= F_SO_DEBUG;
break;
case 'D':
options |= F_PTIMEOFDAY;
break;
case 'i':
{
double optval;
optval = ping_strtod(optarg, "bad timing interval");
if (isgreater(optval, (double)(INT_MAX / 1000)))
error(2, 0, "bad timing interval: %s", optarg);
interval = (int)(optval * 1000);
options |= F_INTERVAL;
}
break;
case 'I':
/* IPv6 */
if (strchr(optarg, ':')) {
char *p, *addr = strdup(optarg);
if (!addr)
error(2, errno, "cannot copy: %s", optarg);
p = strchr(addr, SCOPE_DELIMITER);
if (p) {
*p = '\0';
device = optarg + (p - addr) + 1;
}
if (inet_pton(AF_INET6, addr, (char*)&source6.sin6_addr) <= 0)
error(2, 0, "invalid source address: %s", optarg);
options |= F_STRICTSOURCE;
free(addr);
} else if (inet_pton(AF_INET, optarg, &source.sin_addr) > 0) {
options |= F_STRICTSOURCE;
} else {
device = optarg;
}
break;
case 'l':
preload = atoi(optarg);
if (preload <= 0)
error(2, 0, "bad preload value: %s, should be 1..%d", optarg, MAX_DUP_CHK);
if (preload > MAX_DUP_CHK)
preload = MAX_DUP_CHK;
if (uid && preload > 3)
error(2, 0, "cannot set preload to value greater than 3: %d", preload);
break;
case 'L':
options |= F_NOLOOP;
break;
case 'm':
{
char *endp;
mark = (int)strtoul(optarg, &endp, 10);
if (mark < 0 || *endp != '\0')
error(2, 0, "mark cannot be negative: %s", optarg);
options |= F_MARK;
break;
}
case 'M':
if (strcmp(optarg, "do") == 0)
pmtudisc = IP_PMTUDISC_DO;
else if (strcmp(optarg, "dont") == 0)
pmtudisc = IP_PMTUDISC_DONT;
else if (strcmp(optarg, "want") == 0)
pmtudisc = IP_PMTUDISC_WANT;
else
error(2, 0, "invalid -M argument: %s", optarg);
break;
case 'n':
options |= F_NUMERIC;
break;
case 'O':
options |= F_OUTSTANDING;
break;
case 'f':
/* avoid `getaddrinfo()` during flood */
options |= F_FLOOD | F_NUMERIC;
setbuf(stdout, (char *)NULL);
break;
case 'p':
options |= F_PINGFILLED;
fill(optarg, outpack, sizeof(outpack));
break;
case 'q':
options |= F_QUIET;
break;
case 'Q':
settos = parsetos(optarg); /* IPv4 */
tclass = settos; /* IPv6 */
break;
case 'r':
options |= F_SO_DONTROUTE;
break;
case 's':
datalen = atoi(optarg);
if (datalen < 0)
error(2, 0, "illegal packet size: %d", datalen);
if (datalen > MAXPACKET - 8)
error(2, 0, "packet size too large: %d", datalen);
break;
case 'S':
sndbuf = atoi(optarg);
if (sndbuf <= 0)
error(2, 0, "bad sndbuf value: %s", optarg);
break;
case 't':
options |= F_TTL;
ttl = atoi(optarg);
if (ttl < 0 || ttl > 255)
error(2, 0, "ttl out of range: %s", optarg);
break;
case 'E':
exec_cmd(optarg);
return 0;
case 'U':
options |= F_LATENCY;
break;
case 'v':
options |= F_VERBOSE;
break;
case 'V':
printf(IPUTILS_VERSION("ping"));
exit(0);
case 'w':
deadline = atoi(optarg);
if (deadline < 0)
error(2, 0, "bad wait time: %s", optarg);
break;
case 'W':
{
double optval;
optval = ping_strtod(optarg, "bad linger time");
if (isless(optval, 0.001) || isgreater(optval, (double)(INT_MAX / 1000)))
error(2, 0, "bad linger time: %s", optarg);
/* lingertime will be converted to usec later */
lingertime = (int)(optval * 1000);
}
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (!argc)
error(1, EDESTADDRREQ, "usage error");
target = argv[argc-1];
/* Create sockets */
enable_capability_raw();
if (hints.ai_family != AF_INET6)
create_socket(&sock4, AF_INET, hints.ai_socktype, IPPROTO_ICMP, hints.ai_family == AF_INET);
if (hints.ai_family != AF_INET) {
create_socket(&sock6, AF_INET6, hints.ai_socktype, IPPROTO_ICMPV6, sock4.fd == -1);
/* This may not be needed if both protocol versions always had the same value, but
* since I don't know that, it's better to be safe than sorry. */
pmtudisc = pmtudisc == IP_PMTUDISC_DO ? IPV6_PMTUDISC_DO :
pmtudisc == IP_PMTUDISC_DONT ? IPV6_PMTUDISC_DONT :
pmtudisc == IP_PMTUDISC_WANT ? IPV6_PMTUDISC_WANT : pmtudisc;
}
disable_capability_raw();
/* Limit address family on single-protocol systems */
if (hints.ai_family == AF_UNSPEC) {
if (sock4.fd == -1)
hints.ai_family = AF_INET6;
else if (sock6.fd == -1)
hints.ai_family = AF_INET;
}
/* Set socket options */
if (settos)
set_socket_option(&sock4, IPPROTO_IP, IP_TOS, &settos, sizeof settos);
if (tclass)
set_socket_option(&sock6, IPPROTO_IPV6, IPV6_TCLASS, &tclass, sizeof tclass);
status = getaddrinfo(target, NULL, &hints, &result);
if (status)
error(2, 0, "%s: %s", target, gai_strerror(status));
for (ai = result; ai; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET:
status = ping4_run(argc, argv, ai, &sock4);
break;
case AF_INET6:
status = ping6_run(argc, argv, ai, &sock6);
break;
default:
error(2, 0, "unknown protocol family: %d", ai->ai_family);
}
if (status == 0)
break;
}
freeaddrinfo(result);
return status;
}
int ping4_run(int argc, char **argv, struct addrinfo *ai, socket_st *sock)
{
static const struct addrinfo hints = { .ai_family = AF_INET, .ai_protocol = IPPROTO_UDP, .ai_flags = getaddrinfo_flags };
int hold, packlen;
unsigned char *packet;
char *target;
char hnamebuf[NI_MAXHOST];
unsigned char rspace[3 + 4 * NROUTES + 1]; /* record route space */
uint32_t *tmp_rspace;
if (argc > 1) {
if (options & F_RROUTE)
usage();
else if (options & F_TIMESTAMP) {
if (ts_type != IPOPT_TS_PRESPEC)
usage();
if (argc > 5)
usage();
} else {
if (argc > 10)
usage();
options |= F_SOURCEROUTE;
}
}
while (argc > 0) {
target = *argv;
memset((char *)&whereto, 0, sizeof(whereto));
whereto.sin_family = AF_INET;
if (inet_aton(target, &whereto.sin_addr) == 1) {
hostname = target;
if (argc == 1)
options |= F_NUMERIC;
} else {
struct addrinfo *result = NULL;
int status;
if (argc > 1 || !ai) {
status = getaddrinfo(target, NULL, &hints, &result);
if (status)
error(2, 0, "%s: %s", target, gai_strerror(status));
ai = result;
}
memcpy(&whereto, ai->ai_addr, sizeof whereto);
memset(hnamebuf, 0, sizeof hnamebuf);
if (ai->ai_canonname)
strncpy(hnamebuf, ai->ai_canonname, sizeof hnamebuf - 1);
hostname = hnamebuf;
if (result)
freeaddrinfo(result);
}
if (argc > 1)
route[nroute++] = whereto.sin_addr.s_addr;
argc--;
argv++;
}
if (source.sin_addr.s_addr == 0) {
socklen_t alen;
struct sockaddr_in dst = whereto;
int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (probe_fd < 0)
error(2, errno, "socket");
if (device) {
struct ifreq ifr;
int i;
int fds[2] = {probe_fd, sock->fd};
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
for (i = 0; i < 2; i++) {
int fd = fds[i];
int rc;
int errno_save;
enable_capability_raw();
rc = setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1);
errno_save = errno;
disable_capability_raw();
if (rc == -1) {
if (IN_MULTICAST(ntohl(dst.sin_addr.s_addr))) {
struct ip_mreqn imr;
if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0)
error(2, 0, "unknown iface: %s", device);
memset(&imr, 0, sizeof(imr));
imr.imr_ifindex = ifr.ifr_ifindex;
if (setsockopt(fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1)
error(2, errno, "IP_MULTICAST_IF");
} else
error(2, errno_save, "SO_BINDTODEVICE %s", device);
}
}
}
if (settos &&
setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *)&settos, sizeof(int)) < 0)
error(0, errno, "warning: QOS sockopts");
dst.sin_port = htons(1025);
if (nroute)
dst.sin_addr.s_addr = route[0];
if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
if (errno == EACCES) {
if (broadcast_pings == 0)
error(2, 0,
"Do you want to ping broadcast? Then -b. If not, check your local firewall rules");
fprintf(stderr, "WARNING: pinging broadcast address\n");
if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
&broadcast_pings, sizeof(broadcast_pings)) < 0)
error(2, errno, "cannot set broadcasting");
if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1)
error(2, errno, "connect");
} else
error(2, errno, "connect");
}
alen = sizeof(source);
if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1)
error(2, errno, "getsockname");
source.sin_port = 0;
if (device) {
struct ifaddrs *ifa0, *ifa;
int ret;
ret = getifaddrs(&ifa0);
if (ret)
error(2, errno, "gatifaddrs failed");
for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
if (!ifa->ifa_name || !ifa->ifa_addr ||
ifa->ifa_addr->sa_family != AF_INET)
continue;
if (!strcmp(ifa->ifa_name, device) &&
!memcmp(&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
&source.sin_addr, sizeof(source.sin_addr)))
break;
}
freeifaddrs(ifa0);
if (!ifa)
error(0, 0, "Warning: source address might be selected on device other than: %s", device);
}
close(probe_fd);
} while (0);
if (whereto.sin_addr.s_addr == 0)
whereto.sin_addr.s_addr = source.sin_addr.s_addr;
if (device) {
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
if (ioctl(sock->fd, SIOCGIFINDEX, &ifr) < 0)
error(2, 0, "unknown iface: %s", device);
}
if (broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
if (uid) {
if (interval < 1000)
error(2, 0, "broadcast ping with too short interval: %d", interval);
if (pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO)
error(2, 0, "broadcast ping does not fragment");
}
if (pmtudisc < 0)
pmtudisc = IP_PMTUDISC_DO;
}
if (pmtudisc >= 0) {
if (setsockopt(sock->fd, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof pmtudisc) == -1)
error(2, errno, "IP_MTU_DISCOVER");
}
if ((options&F_STRICTSOURCE) &&
bind(sock->fd, (struct sockaddr *) &source, sizeof source) == -1)
error(2, errno, "bind");
if (sock->socktype == SOCK_RAW) {
struct icmp_filter filt;
filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
(1<<ICMP_DEST_UNREACH)|
(1<<ICMP_TIME_EXCEEDED)|
(1<<ICMP_PARAMETERPROB)|
(1<<ICMP_REDIRECT)|
(1<<ICMP_ECHOREPLY));
if (setsockopt(sock->fd, SOL_RAW, ICMP_FILTER, &filt, sizeof filt) == -1)
error(0, errno, "WARNING: setsockopt(ICMP_FILTER)");
}
hold = 1;
if (setsockopt(sock->fd, SOL_IP, IP_RECVERR, &hold, sizeof hold))
error(0, 0, "WARNING: your kernel is veeery old. No problems.");
if (sock->socktype == SOCK_DGRAM) {
if (setsockopt(sock->fd, SOL_IP, IP_RECVTTL, &hold, sizeof hold))
error(0, errno, "WARNING: setsockopt(IP_RECVTTL)");
if (setsockopt(sock->fd, SOL_IP, IP_RETOPTS, &hold, sizeof hold))
error(0, errno, "WARNING: setsockopt(IP_RETOPTS)");
}
/* record route option */
if (options & F_RROUTE) {
memset(rspace, 0, sizeof(rspace));
rspace[0] = IPOPT_NOP;
rspace[1+IPOPT_OPTVAL] = IPOPT_RR;
rspace[1+IPOPT_OLEN] = sizeof(rspace)-1;
rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
optlen = 40;
if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, sizeof rspace) < 0)
error(2, errno, "record route");
}
if (options & F_TIMESTAMP) {
memset(rspace, 0, sizeof(rspace));
rspace[0] = IPOPT_TIMESTAMP;
rspace[1] = (ts_type==IPOPT_TS_TSONLY ? 40 : 36);
rspace[2] = 5;
rspace[3] = ts_type;
if (ts_type == IPOPT_TS_PRESPEC) {
int i;
rspace[1] = 4+nroute*8;
for (i = 0; i < nroute; i++) {
tmp_rspace = (uint32_t*)&rspace[4+i*8];
*tmp_rspace = route[i];
}
}
if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
rspace[3] = 2;
if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0)
error(2, errno, "ts option");
}
optlen = 40;
}
if (options & F_SOURCEROUTE) {
int i;
memset(rspace, 0, sizeof(rspace));
rspace[0] = IPOPT_NOOP;
rspace[1+IPOPT_OPTVAL] = (options & F_SO_DONTROUTE) ? IPOPT_SSRR
: IPOPT_LSRR;
rspace[1+IPOPT_OLEN] = 3 + nroute*4;
rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
for (i = 0; i < nroute; i++) {
tmp_rspace = (uint32_t*)&rspace[4+i*4];
*tmp_rspace = route[i];
}
if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute*4) < 0)
error(2, errno, "record route");
optlen = 40;
}
/* Estimate memory eaten by single packet. It is rough estimate.
* Actually, for small datalen's it depends on kernel side a lot. */
hold = datalen + 8;
hold += ((hold+511)/512)*(optlen + 20 + 16 + 64 + 160);
sock_setbufs(sock, hold);
if (broadcast_pings) {
if (setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, &broadcast_pings, sizeof broadcast_pings) < 0)
error(2, errno, "cannot set broadcasting");
}
if (options & F_NOLOOP) {
int loop = 0;
if (setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof loop) == -1)
error(2, errno, "cannot disable multicast loopback");
}
if (options & F_TTL) {
int ittl = ttl;
if (setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof ttl) == -1)
error(2, errno, "cannot set multicast time-to-live");
if (setsockopt(sock->fd, IPPROTO_IP, IP_TTL, &ittl, sizeof ittl) == -1)
error(2, errno, "cannot set unicast time-to-live");
}
if (datalen > 0xFFFF - 8 - optlen - 20)
error(2, 0, "packet size %d is too large. Maximum is %d",
datalen, 0xFFFF - 8 - 20 - optlen);
if (datalen >= (int) sizeof(struct timeval)) /* can we time transfer */
timing = 1;
packlen = datalen + MAXIPLEN + MAXICMPLEN;
if (!(packet = (unsigned char *)malloc((unsigned int)packlen)))
error(2, errno, "memory allocation failed");
printf("PING %s (%s) ", hostname, inet_ntoa(whereto.sin_addr));
if (device || (options&F_STRICTSOURCE))
printf("from %s %s: ", inet_ntoa(source.sin_addr), device ? device : "");
printf("%d(%d) bytes of data.\n", datalen, datalen+8+optlen+20);
setup(sock);
main_loop(&ping4_func_set, sock, packet, packlen);
}
int ping4_receive_error_msg(socket_st *sock)
{
ssize_t res;
char cbuf[512];
struct iovec iov;
struct msghdr msg;
struct cmsghdr *cmsgh;
struct sock_extended_err *e;
struct icmphdr icmph;
struct sockaddr_in target;
int net_errors = 0;
int local_errors = 0;
int saved_errno = errno;
iov.iov_base = &icmph;
iov.iov_len = sizeof(icmph);
msg.msg_name = (void*)⌖
msg.msg_namelen = sizeof(target);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_flags = 0;
msg.msg_control = cbuf;
msg.msg_controllen = sizeof(cbuf);
res = recvmsg(sock->fd, &msg, MSG_ERRQUEUE|MSG_DONTWAIT);
if (res < 0)
goto out;
e = NULL;
for (cmsgh = CMSG_FIRSTHDR(&msg); cmsgh; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
if (cmsgh->cmsg_level == SOL_IP) {
if (cmsgh->cmsg_type == IP_RECVERR)
e = (struct sock_extended_err *)CMSG_DATA(cmsgh);
}
}
if (e == NULL)
abort();
if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
local_errors++;
if (options & F_QUIET)
goto out;
if (options & F_FLOOD)
write_stdout("E", 1);
else if (e->ee_errno != EMSGSIZE)
error(0, 0, "local error: %s", strerror(e->ee_errno));
else
error(0, 0, "local error: message too long, mtu=%u", e->ee_info);
nerrors++;
} else if (e->ee_origin == SO_EE_ORIGIN_ICMP) {
struct sockaddr_in *sin = (struct sockaddr_in*)(e+1);
if (res < (ssize_t) sizeof(icmph) ||
target.sin_addr.s_addr != whereto.sin_addr.s_addr ||
icmph.type != ICMP_ECHO ||
!is_ours(sock, icmph.un.echo.id)) {
/* Not our error, not an error at all. Clear. */
saved_errno = 0;
goto out;
}
acknowledge(ntohs(icmph.un.echo.sequence));
net_errors++;
nerrors++;
if (options & F_QUIET)
goto out;
if (options & F_FLOOD) {
write_stdout("\bE", 2);
} else {
print_timestamp();
printf("From %s icmp_seq=%u ", pr_addr(sin, sizeof *sin), ntohs(icmph.un.echo.sequence));
pr_icmph(e->ee_type, e->ee_code, e->ee_info, NULL);
fflush(stdout);
}
}
out:
errno = saved_errno;
return net_errors ? net_errors : -local_errors;
}
/*
* pinger --
* Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
* will be added on by the kernel. The ID field is our UNIX process ID,
* and the sequence number is an ascending integer. The first several bytes
* of the data portion are used to hold a UNIX "timeval" struct in VAX
* byte-order, to compute the round-trip time.
*/
int ping4_send_probe(socket_st *sock, void *packet, unsigned packet_size __attribute__((__unused__)))
{
struct icmphdr *icp;
int cc;
int i;
icp = (struct icmphdr *)packet;
icp->type = ICMP_ECHO;
icp->code = 0;
icp->checksum = 0;
icp->un.echo.sequence = htons(ntransmitted+1);
icp->un.echo.id = ident; /* ID */
rcvd_clear(ntransmitted+1);
if (timing) {
if (options&F_LATENCY) {
struct timeval tmp_tv;
gettimeofday(&tmp_tv, NULL);
memcpy(icp+1, &tmp_tv, sizeof(tmp_tv));
} else {
memset(icp+1, 0, sizeof(struct timeval));
}
}
cc = datalen + 8; /* skips ICMP portion */
/* compute ICMP checksum here */
icp->checksum = in_cksum((unsigned short *)icp, cc, 0);
if (timing && !(options&F_LATENCY)) {
struct timeval tmp_tv;
gettimeofday(&tmp_tv, NULL);
memcpy(icp+1, &tmp_tv, sizeof(tmp_tv));
icp->checksum = in_cksum((unsigned short *)&tmp_tv, sizeof(tmp_tv), ~icp->checksum);
}
i = sendto(sock->fd, icp, cc, 0, (struct sockaddr*)&whereto, sizeof(whereto));
return (cc == i ? 0 : i);
}
/*
* parse_reply --
* Print out the packet, if it came from us. This logic is necessary
* because ALL readers of the ICMP socket get a copy of ALL ICMP packets
* which arrive ('tis only fair). This permits multiple copies of this
* program to be run without having intermingled output (or statistics!).
*/
static
void pr_echo_reply(uint8_t *_icp, int len __attribute__((__unused__)))
{
struct icmphdr *icp = (struct icmphdr *)_icp;
printf(" icmp_seq=%u", ntohs(icp->un.echo.sequence));
}
int
ping4_parse_reply(struct socket_st *sock, struct msghdr *msg, int cc, void *addr, struct timeval *tv)
{
struct sockaddr_in *from = addr;
uint8_t *buf = msg->msg_iov->iov_base;
struct icmphdr *icp;
struct iphdr *ip;
int hlen;