forked from NetBSD/src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathping.c
1991 lines (1773 loc) · 48.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
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
/* $NetBSD: ping.c,v 1.122 2022/12/01 14:42:12 christos Exp $ */
/*
* Copyright (c) 1989, 1993
* 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
* Modified at Uc Berkeley
* Record Route and verbose headers - Phil Dykstra, BRL, March 1988.
* Multicast options (ttl, if, loop) - Steve Deering, Stanford, August 1988.
* ttl, duplicate detection - Cliff Frost, UCB, April 1989
* Pad pattern - Cliff Frost (from Tom Ferrin, UCSF), April 1989
*
* Status -
* Public Domain. Distribution Unlimited.
*
* Bugs -
* More statistics could always be gathered.
* This program has to run SUID to ROOT to access the ICMP socket.
*/
#include <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: ping.c,v 1.122 2022/12/01 14:42:12 christos Exp $");
#endif
#include <stdio.h>
#include <stddef.h>
#include <errno.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <termios.h>
#include <stdlib.h>
#include <unistd.h>
#include <poll.h>
#include <limits.h>
#include <math.h>
#include <string.h>
#include <err.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/ip_var.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <netdb.h>
#ifdef IPSEC
#include <netipsec/ipsec.h>
#endif /*IPSEC*/
#include "prog_ops.h"
#define FLOOD_INTVL 0.01 /* default flood output interval */
#define MAXPACKET (IP_MAXPACKET-60-8) /* max packet size */
#define F_VERBOSE 0x0001
#define F_QUIET 0x0002 /* minimize all output */
#define F_SEMI_QUIET 0x0004 /* ignore our ICMP errors */
#define F_FLOOD 0x0008 /* flood-ping */
#define F_RECORD_ROUTE 0x0010 /* record route */
#define F_SOURCE_ROUTE 0x0020 /* loose source route */
#define F_PING_FILLED 0x0040 /* is buffer filled with user data? */
#define F_PING_RANDOM 0x0080 /* use random data */
#define F_NUMERIC 0x0100 /* do not do gethostbyaddr() calls */
#define F_TIMING 0x0200 /* room for a timestamp */
#define F_DF 0x0400 /* set IP DF bit */
#define F_SOURCE_ADDR 0x0800 /* set source IP address/interface */
#define F_ONCE 0x1000 /* exit(0) after receiving 1 reply */
#define F_MCAST 0x2000 /* multicast target */
#define F_MCAST_NOLOOP 0x4000 /* no multicast loopback */
#define F_AUDIBLE 0x8000 /* audible output */
#define F_TIMING64 0x10000 /* 64 bit time, nanoseconds */
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
#define F_POLICY 0x20000
#else
#define F_AUTHHDR 0x20000
#define F_ENCRYPT 0x40000
#endif /*IPSEC_POLICY_IPSEC*/
#endif /*IPSEC*/
/* MAX_DUP_CHK is the number of bits in received table, the
* maximum number of received sequence numbers we can track to check
* for duplicates.
*/
#define MAX_DUP_CHK (8 * 2048)
static u_char rcvd_tbl[MAX_DUP_CHK/8];
static int nrepeats = 0;
#define A(seq) rcvd_tbl[(seq/8)%sizeof(rcvd_tbl)] /* byte in array */
#define B(seq) (1 << (seq & 0x07)) /* bit in byte */
#define SET(seq) (A(seq) |= B(seq))
#define CLR(seq) (A(seq) &= (~B(seq)))
#define TST(seq) (A(seq) & B(seq))
struct tv32 {
int32_t tv32_sec;
int32_t tv32_usec;
};
static u_char *packet;
static int packlen;
static int pingflags = 0, options;
static int pongflags = 0;
static char *fill_pat;
static int s; /* Socket file descriptor */
static int sloop; /* Socket file descriptor/loopback */
#define PHDR_LEN sizeof(struct tv32) /* size of timestamp header */
#define PHDR64_LEN sizeof(struct timespec) /* size of timestamp header */
static struct sockaddr_in whereto, send_addr; /* Who to ping */
static struct sockaddr_in src_addr; /* from where */
static struct sockaddr_in loc_addr; /* 127.1 */
static int datalen; /* How much data */
static int phdrlen;
static sigset_t blockmask, enablemask; /* signal masks */
#ifndef __NetBSD__
static char *progname;
#define getprogname() (progname)
#define setprogname(name) ((void)(progname = (name)))
#endif
static char hostname[MAXHOSTNAMELEN];
static struct {
struct ip o_ip;
char o_opt[MAX_IPOPTLEN];
union {
u_char u_buf[MAXPACKET+offsetof(struct icmp, icmp_data)];
struct icmp u_icmp;
} o_u;
} out_pack;
#define opack_icmp out_pack.o_u.u_icmp
static struct ip *opack_ip;
static uint8_t optspace[MAX_IPOPTLEN]; /* record route space */
static int optlen;
static int npackets; /* total packets to send */
static int preload; /* number of packets to "preload" */
static int ntransmitted; /* output sequence # = #sent */
static int ident; /* 16 random bits to identify our packets */
static int nreceived; /* # of packets we got back */
static double interval; /* interval between packets */
static struct timespec interval_tv;
static double tmin = 999999999.0;
static double tmax = 0.0;
static double tsum = 0.0; /* sum of all times */
static double tsumsq = 0.0;
static double maxwait = 0.0;
static int bufspace = IP_MAXPACKET;
static struct timespec now, clear_cache, last_tx, next_tx, first_tx;
static struct timespec last_rx, first_rx;
static int lastrcvd = 1; /* last ping sent has been received */
static struct timespec jiggle_time;
static int jiggle_cnt, total_jiggled, jiggle_direction = -1;
__dead static void doit(void);
static void prefinish(int);
static void prtsig(int);
__dead static void finish(int);
static void blocksignals(void);
static void enablesignals(void);
static void summary(int);
static void pinger(void);
static void fill(void);
static void rnd_fill(void);
static double diffsec(struct timespec *, struct timespec *);
#if 0
static void timespecadd(struct timespec *, struct timespec *);
#endif
static void sec_to_timespec(const double, struct timespec *);
static double timespec_to_sec(const struct timespec *);
static void pr_pack(u_char *, int, struct sockaddr_in *);
static u_int16_t in_cksum(u_int16_t *, u_int);
static void pr_saddr(u_char *);
static char *pr_addr(struct in_addr *);
static void pr_iph(struct icmp *, int);
static void pr_retip(struct icmp *, int);
static int pr_icmph(struct icmp *, struct sockaddr_in *, int);
static void jiggle(int), jiggle_flush(int);
static void gethost(const char *, const char *,
struct sockaddr_in *, char *, int);
__dead static void usage(void);
int
main(int argc, char *argv[])
{
int c, i, on = 1, hostind = 0;
long l;
int len = -1, compat = 0;
u_char ttl = 0;
u_long tos = 0;
char *p;
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
char *policy_in = NULL;
char *policy_out = NULL;
#endif
#endif
#ifdef SIGINFO
struct sigaction sa;
#endif
if (prog_init && prog_init() == -1)
err(EXIT_FAILURE, "init failed");
if ((s = prog_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
err(EXIT_FAILURE, "Cannot create socket");
if ((sloop = prog_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
err(EXIT_FAILURE, "Cannot create socket");
/*
* sloop is never read on. This prevents packets from
* queueing in its recv buffer.
*/
if (prog_shutdown(sloop, SHUT_RD) == -1)
warn("Cannot shutdown for read");
if (prog_setuid(prog_getuid()) == -1)
err(EXIT_FAILURE, "setuid");
setprogname(argv[0]);
#ifndef IPSEC
#define IPSECOPT
#else
#ifdef IPSEC_POLICY_IPSEC
#define IPSECOPT "E:"
#else
#define IPSECOPT "AE"
#endif /*IPSEC_POLICY_IPSEC*/
#endif
while ((c = getopt(argc, argv,
"ac:CdDfg:h:i:I:l:Lnop:PqQrRs:t:T:vw:" IPSECOPT)) != -1) {
#undef IPSECOPT
switch (c) {
case 'a':
pingflags |= F_AUDIBLE;
break;
case 'C':
compat = 1;
break;
case 'c':
l = strtol(optarg, &p, 0);
if (*p != '\0' || l <= 0)
errx(EXIT_FAILURE,
"Bad/invalid number of packets: %s",
optarg);
#if INT_MAX < LONG_MAX
if (l > INT_MAX)
errx(EXIT_FAILURE,
"Too many packets to count: %ld", l);
#endif
npackets = l;
break;
case 'D':
pingflags |= F_DF;
break;
case 'd':
options |= SO_DEBUG;
break;
case 'f':
pingflags |= F_FLOOD;
break;
case 'h':
hostind = optind-1;
break;
case 'i': /* wait between sending packets */
interval = strtod(optarg, &p);
if (*p != '\0' || interval <= 0)
errx(EXIT_FAILURE, "Bad/invalid interval: %s",
optarg);
/*
* In order to avoid overflowing the microseconds
* argument of poll() the interval must be less than
* INT_MAX/1000. Limit it to one second less than
* that to be safe.
*/
if (interval >= INT_MAX/1000.0 - 1.0)
errx(EXIT_FAILURE,
"Timing interval %g too large", interval);
break;
case 'l':
l = strtol(optarg, &p, 0);
if (*p != '\0' || l < 0)
errx(EXIT_FAILURE, "Bad/invalid preload value: "
"%s", optarg);
#if INT_MAX < LONG_MAX
if (l > INT_MAX)
errx(EXIT_FAILURE,
"Too many preload packets: %ld", l);
#endif
preload = l;
break;
case 'n':
pingflags |= F_NUMERIC;
break;
case 'o':
pingflags |= F_ONCE;
break;
case 'p': /* fill buffer with user pattern */
if (pingflags & F_PING_RANDOM)
errx(EXIT_FAILURE,
"Only one of -P and -p allowed");
pingflags |= F_PING_FILLED;
fill_pat = optarg;
break;
case 'P':
if (pingflags & F_PING_FILLED)
errx(EXIT_FAILURE,
"Only one of -P and -p allowed");
pingflags |= F_PING_RANDOM;
break;
case 'q':
pingflags |= F_QUIET;
break;
case 'Q':
pingflags |= F_SEMI_QUIET;
break;
case 'r':
options |= SO_DONTROUTE;
break;
case 's': /* size of packet to send */
l = strtol(optarg, &p, 0);
if (*p != '\0' || l < 0)
errx(EXIT_FAILURE,
"Bad/invalid packet size: %s", optarg);
if (l > MAXPACKET)
errx(EXIT_FAILURE, "packet size is too large");
len = (int)l;
break;
case 'v':
pingflags |= F_VERBOSE;
break;
case 'R':
pingflags |= F_RECORD_ROUTE;
break;
case 'L':
pingflags |= F_MCAST_NOLOOP;
break;
case 't':
tos = strtoul(optarg, &p, 0);
if (*p != '\0' || tos > 0xFF)
errx(EXIT_FAILURE, "bad tos value: %s", optarg);
break;
case 'T':
l = strtol(optarg, &p, 0);
if (*p != '\0' || l > 255 || l <= 0)
errx(EXIT_FAILURE, "ttl out of range: %s",
optarg);
ttl = (u_char)l; /* cannot check >255 otherwise */
break;
case 'I':
pingflags |= F_SOURCE_ADDR;
gethost("-I", optarg, &src_addr, 0, 0);
break;
case 'g':
pingflags |= F_SOURCE_ROUTE;
gethost("-g", optarg, &send_addr, 0, 0);
break;
case 'w':
maxwait = strtod(optarg, &p);
if (*p != '\0' || maxwait <= 0)
errx(EXIT_FAILURE, "Bad/invalid maxwait time: "
"%s", optarg);
break;
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
case 'E':
pingflags |= F_POLICY;
if (!strncmp("in", optarg, 2)) {
policy_in = strdup(optarg);
if (!policy_in)
err(EXIT_FAILURE, "strdup");
} else if (!strncmp("out", optarg, 3)) {
policy_out = strdup(optarg);
if (!policy_out)
err(EXIT_FAILURE, "strdup");
} else
errx(EXIT_FAILURE, "invalid security policy: "
"%s", optarg);
break;
#else
case 'A':
pingflags |= F_AUTHHDR;
break;
case 'E':
pingflags |= F_ENCRYPT;
break;
#endif /*IPSEC_POLICY_IPSEC*/
#endif /*IPSEC*/
default:
usage();
break;
}
}
if (interval == 0)
interval = (pingflags & F_FLOOD) ? FLOOD_INTVL : 1.0;
if (pingflags & F_FLOOD && prog_getuid())
errx(EXIT_FAILURE, "Must be superuser to use -f");
if (interval < 1.0 && prog_getuid())
errx(EXIT_FAILURE, "Must be superuser to use < 1 sec "
"ping interval");
if (preload > 0 && prog_getuid())
errx(EXIT_FAILURE, "Must be superuser to use -l");
sec_to_timespec(interval, &interval_tv);
if (interval_tv.tv_sec == 0 && interval_tv.tv_nsec == 0) {
errx(EXIT_FAILURE, "Packet interval must be at least 1 ns");
}
if ((pingflags & (F_AUDIBLE|F_FLOOD)) == (F_AUDIBLE|F_FLOOD))
warnx("Sorry, no audible output for flood pings");
if (npackets != 0) {
npackets += preload;
} else {
npackets = INT_MAX;
}
if (hostind == 0) {
if (optind != argc-1)
usage();
else
hostind = optind;
}
else if (hostind >= argc - 1)
usage();
gethost("", argv[hostind], &whereto, hostname, sizeof(hostname));
if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr)))
pingflags |= F_MCAST;
if (!(pingflags & F_SOURCE_ROUTE))
(void) memcpy(&send_addr, &whereto, sizeof(send_addr));
loc_addr.sin_family = AF_INET;
loc_addr.sin_len = sizeof(struct sockaddr_in);
loc_addr.sin_addr.s_addr = htonl((127 << 24) + 1);
if (len != -1)
datalen = len;
else
datalen = 64 - PHDR_LEN;
if (!compat && datalen >= (int)PHDR64_LEN) { /* can we time them? */
pingflags |= F_TIMING64;
phdrlen = PHDR64_LEN;
} else if (datalen >= (int)PHDR_LEN) { /* can we time them? */
pingflags |= F_TIMING;
phdrlen = PHDR_LEN;
} else
phdrlen = 0;
packlen = datalen + 60 + 76; /* MAXIP + MAXICMP */
if ((packet = malloc(packlen)) == NULL)
err(EXIT_FAILURE, "Can't allocate %d bytes", packlen);
if (pingflags & F_PING_FILLED) {
fill();
} else if (pingflags & F_PING_RANDOM) {
rnd_fill();
} else {
for (i = phdrlen; i < datalen; i++)
opack_icmp.icmp_data[i] = i;
}
ident = arc4random() & 0xFFFF;
if (options & SO_DEBUG) {
if (prog_setsockopt(s, SOL_SOCKET, SO_DEBUG,
(char *)&on, sizeof(on)) == -1)
warn("Can't turn on socket debugging");
}
if (options & SO_DONTROUTE) {
if (prog_setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
(char *)&on, sizeof(on)) == -1)
warn("SO_DONTROUTE");
}
if (options & SO_DEBUG) {
if (prog_setsockopt(sloop, SOL_SOCKET, SO_DEBUG,
(char *)&on, sizeof(on)) == -1)
warn("Can't turn on socket debugging");
}
if (options & SO_DONTROUTE) {
if (prog_setsockopt(sloop, SOL_SOCKET, SO_DONTROUTE,
(char *)&on, sizeof(on)) == -1)
warn("SO_DONTROUTE");
}
if (pingflags & F_SOURCE_ROUTE) {
optspace[IPOPT_OPTVAL] = IPOPT_LSRR;
optspace[IPOPT_OLEN] = optlen = 7;
optspace[IPOPT_OFFSET] = IPOPT_MINOFF;
(void)memcpy(&optspace[IPOPT_MINOFF-1], &whereto.sin_addr,
sizeof(whereto.sin_addr));
optspace[optlen++] = IPOPT_NOP;
}
if (pingflags & F_RECORD_ROUTE) {
optspace[optlen+IPOPT_OPTVAL] = IPOPT_RR;
optspace[optlen+IPOPT_OLEN] = (MAX_IPOPTLEN -1-optlen);
optspace[optlen+IPOPT_OFFSET] = IPOPT_MINOFF;
optlen = MAX_IPOPTLEN;
}
/* this leaves opack_ip 0(mod 4) aligned */
opack_ip = (struct ip *)((char *)&out_pack.o_ip
+ sizeof(out_pack.o_opt)
- optlen);
(void) memcpy(opack_ip + 1, optspace, optlen);
if (prog_setsockopt(s, IPPROTO_IP, IP_HDRINCL,
(char *) &on, sizeof(on)) < 0)
err(EXIT_FAILURE, "Can't set special IP header");
opack_ip->ip_v = IPVERSION;
opack_ip->ip_hl = (sizeof(struct ip)+optlen) >> 2;
opack_ip->ip_tos = tos;
opack_ip->ip_off = (pingflags & F_DF) ? IP_DF : 0;
opack_ip->ip_ttl = ttl ? ttl : MAXTTL;
opack_ip->ip_p = IPPROTO_ICMP;
opack_ip->ip_src = src_addr.sin_addr;
opack_ip->ip_dst = send_addr.sin_addr;
if (pingflags & F_MCAST) {
if (pingflags & F_MCAST_NOLOOP) {
u_char loop = 0;
if (prog_setsockopt(s, IPPROTO_IP,
IP_MULTICAST_LOOP,
(char *) &loop, 1) < 0)
err(EXIT_FAILURE, "Can't disable multicast loopback");
}
if (ttl != 0
&& prog_setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
(char *) &ttl, 1) < 0)
err(EXIT_FAILURE, "Can't set multicast time-to-live");
if ((pingflags & F_SOURCE_ADDR)
&& prog_setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
(char *) &src_addr.sin_addr,
sizeof(src_addr.sin_addr)) < 0)
err(EXIT_FAILURE, "Can't set multicast source interface");
} else if (pingflags & F_SOURCE_ADDR) {
if (prog_setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
(char *) &src_addr.sin_addr,
sizeof(src_addr.sin_addr)) < 0)
err(EXIT_FAILURE, "Can't set source interface/address");
}
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
{
char *buf;
if (pingflags & F_POLICY) {
if (policy_in != NULL) {
buf = ipsec_set_policy(policy_in, strlen(policy_in));
if (buf == NULL)
errx(EXIT_FAILURE, "%s", ipsec_strerror());
if (prog_setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
buf, ipsec_get_policylen(buf)) < 0) {
err(EXIT_FAILURE, "ipsec policy cannot be "
"configured");
}
free(buf);
}
if (policy_out != NULL) {
buf = ipsec_set_policy(policy_out, strlen(policy_out));
if (buf == NULL)
errx(EXIT_FAILURE, "%s", ipsec_strerror());
if (prog_setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
buf, ipsec_get_policylen(buf)) < 0) {
err(EXIT_FAILURE, "ipsec policy cannot be "
"configured");
}
free(buf);
}
}
buf = ipsec_set_policy("out bypass", strlen("out bypass"));
if (buf == NULL)
errx(EXIT_FAILURE, "%s", ipsec_strerror());
if (prog_setsockopt(sloop, IPPROTO_IP, IP_IPSEC_POLICY,
buf, ipsec_get_policylen(buf)) < 0) {
#if 0
warnx("ipsec is not configured");
#else
/* ignore it, should be okay */
#endif
}
free(buf);
}
#else
{
int optval;
if (pingflags & F_AUTHHDR) {
optval = IPSEC_LEVEL_REQUIRE;
#ifdef IP_AUTH_TRANS_LEVEL
(void)prog_setsockopt(s, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
(char *)&optval, sizeof(optval));
#else
(void)prog_setsockopt(s, IPPROTO_IP, IP_AUTH_LEVEL,
(char *)&optval, sizeof(optval));
#endif
}
if (pingflags & F_ENCRYPT) {
optval = IPSEC_LEVEL_REQUIRE;
(void)prog_setsockopt(s, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
(char *)&optval, sizeof(optval));
}
optval = IPSEC_LEVEL_BYPASS;
#ifdef IP_AUTH_TRANS_LEVEL
(void)prog_setsockopt(sloop, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
(char *)&optval, sizeof(optval));
#else
(void)prog_setsockopt(sloop, IPPROTO_IP, IP_AUTH_LEVEL,
(char *)&optval, sizeof(optval));
#endif
(void)prog_setsockopt(sloop, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
(char *)&optval, sizeof(optval));
}
#endif /*IPSEC_POLICY_IPSEC*/
#endif /*IPSEC*/
(void)printf("PING %s (%s): %d data bytes\n", hostname,
inet_ntoa(whereto.sin_addr), datalen);
/* When pinging the broadcast address, you can get a lot
* of answers. Doing something so evil is useful if you
* are trying to stress the ethernet, or just want to
* fill the arp cache to get some stuff for /etc/ethers.
*/
while (0 > prog_setsockopt(s, SOL_SOCKET, SO_RCVBUF,
(char*)&bufspace, sizeof(bufspace))) {
if ((bufspace -= 4096) <= 0)
err(EXIT_FAILURE, "Cannot set the receive buffer size");
}
/* make it possible to send giant probes, but do not worry now
* if it fails, since we probably won't send giant probes.
*/
(void)prog_setsockopt(s, SOL_SOCKET, SO_SNDBUF,
(char*)&bufspace, sizeof(bufspace));
(void)signal(SIGINT, prefinish);
/*
* Set up two signal masks:
* - blockmask blocks the signals we catch
* - enablemask does not
*/
sigemptyset(&enablemask);
sigemptyset(&blockmask);
sigaddset(&blockmask, SIGINT);
#ifdef SIGINFO
sigaddset(&blockmask, SIGINFO);
#else
sigaddset(&blockmask, SIGQUIT);
#endif
#ifdef SIGINFO
sa.sa_handler = prtsig;
sa.sa_flags = SA_NOKERNINFO;
sigemptyset(&sa.sa_mask);
(void)sigaction(SIGINFO, &sa, NULL);
#else
(void)signal(SIGQUIT, prtsig);
#endif
(void)signal(SIGCONT, prtsig);
blocksignals();
/* fire off them quickies */
for (i = 0; i < preload; i++) {
clock_gettime(CLOCK_MONOTONIC, &now);
pinger();
}
doit();
return 0;
}
static void
doit(void)
{
int cc;
struct sockaddr_in from;
socklen_t fromlen;
double sec, last, d_last;
struct pollfd fdmaskp[1];
(void)clock_gettime(CLOCK_MONOTONIC, &clear_cache);
if (maxwait != 0) {
last = timespec_to_sec(&clear_cache) + maxwait;
d_last = 0;
} else {
last = 0;
d_last = 365*24*60*60;
}
do {
clock_gettime(CLOCK_MONOTONIC, &now);
if (last != 0)
d_last = last - timespec_to_sec(&now);
if (ntransmitted < npackets && d_last > 0) {
/* send if within 100 usec or late for next packet */
sec = diffsec(&next_tx, &now);
if (sec <= 0.0001 ||
(lastrcvd && (pingflags & F_FLOOD))) {
pinger();
sec = diffsec(&next_tx, &now);
}
if (sec < 0.0)
sec = 0.0;
if (d_last < sec)
sec = d_last;
} else {
/* For the last response, wait twice as long as the
* worst case seen, or 10 times as long as the
* maximum interpacket interval, whichever is longer.
*/
sec = MAX(2 * tmax, 10 * interval) -
diffsec(&now, &last_tx);
if (d_last < sec)
sec = d_last;
if (sec <= 0)
break;
}
fdmaskp[0].fd = s;
fdmaskp[0].events = POLLIN;
enablesignals();
cc = prog_poll(fdmaskp, 1, (int)(sec * 1000));
blocksignals();
if (cc <= 0) {
if (cc < 0) {
if (errno == EINTR)
continue;
jiggle_flush(1);
err(EXIT_FAILURE, "poll");
}
continue;
}
fromlen = sizeof(from);
cc = prog_recvfrom(s, (char *) packet, packlen,
0, (struct sockaddr *)&from,
&fromlen);
if (cc < 0) {
if (errno != EINTR) {
jiggle_flush(1);
warn("recvfrom");
(void)fflush(stderr);
}
continue;
}
clock_gettime(CLOCK_MONOTONIC, &now);
pr_pack(packet, cc, &from);
} while (nreceived < npackets
&& (nreceived == 0 || !(pingflags & F_ONCE)));
finish(0);
}
static void
jiggle_flush(int nl) /* new line if there are dots */
{
int serrno = errno;
if (jiggle_cnt > 0) {
total_jiggled += jiggle_cnt;
jiggle_direction = 1;
do {
(void)putchar('.');
} while (--jiggle_cnt > 0);
} else if (jiggle_cnt < 0) {
total_jiggled -= jiggle_cnt;
jiggle_direction = -1;
do {
(void)putchar('\b');
} while (++jiggle_cnt < 0);
}
if (nl) {
if (total_jiggled != 0)
(void)putchar('\n');
total_jiggled = 0;
jiggle_direction = -1;
}
(void)fflush(stdout);
(void)fflush(stderr);
jiggle_time = now;
errno = serrno;
}
/* jiggle the cursor for flood-ping
*/
static void
jiggle(int delta)
{
double dt;
if (pingflags & F_QUIET)
return;
/* do not back up into messages */
if (total_jiggled+jiggle_cnt+delta < 0)
return;
jiggle_cnt += delta;
/* flush the FLOOD dots when things are quiet
* or occasionally to make the cursor jiggle.
*/
dt = diffsec(&last_tx, &jiggle_time);
if (dt > 0.2 || (dt >= 0.15 && delta*jiggle_direction < 0))
jiggle_flush(0);
}
/*
* Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
* will be added on by the kernel. The ID field is random,
* and the sequence number is an ascending integer. The first phdrlen bytes
* of the data portion are used to hold a UNIX "timeval" struct in VAX
* byte-order, to compute the round-trip time, or a UNIX "timespec" in native
* format.
*/
static void
pinger(void)
{
struct tv32 tv32;
int i, cc, sw;
double waittime;
long numskip;
opack_icmp.icmp_code = 0;
opack_icmp.icmp_seq = htons((u_int16_t)(ntransmitted));
/* clear the cached route in the kernel after an ICMP
* response such as a Redirect is seen to stop causing
* more such packets. Also clear the cached route
* periodically in case of routing changes that make
* black holes come and go.
*/
if (clear_cache.tv_sec != now.tv_sec) {
opack_icmp.icmp_type = ICMP_ECHOREPLY;
opack_icmp.icmp_id = ~ident;
opack_icmp.icmp_cksum = 0;
opack_icmp.icmp_cksum = in_cksum((u_int16_t *)&opack_icmp,
ICMP_MINLEN);
sw = 0;
if (prog_setsockopt(sloop, IPPROTO_IP, IP_HDRINCL,
(char *)&sw, sizeof(sw)) < 0)
err(EXIT_FAILURE, "Can't turn off special IP header");
if (prog_sendto(sloop, (char *) &opack_icmp,
ICMP_MINLEN, MSG_DONTROUTE,
(struct sockaddr *)&loc_addr,
sizeof(struct sockaddr_in)) < 0) {
/*
* XXX: we only report this as a warning in verbose
* mode because people get confused when they see
* this error when they are running in single user
* mode and they have not configured lo0
*/
if (pingflags & F_VERBOSE)
warn("failed to clear cached route");
}
sw = 1;
if (prog_setsockopt(sloop, IPPROTO_IP, IP_HDRINCL,
(char *)&sw, sizeof(sw)) < 0)
err(EXIT_FAILURE, "Can't set special IP header");
(void)clock_gettime(CLOCK_MONOTONIC, &clear_cache);
}
opack_icmp.icmp_type = ICMP_ECHO;
opack_icmp.icmp_id = ident;
if (pingflags & F_TIMING) {
tv32.tv32_sec = (uint32_t)htonl(now.tv_sec);
tv32.tv32_usec = htonl(now.tv_nsec / 1000);
(void) memcpy(&opack_icmp.icmp_data[0], &tv32, sizeof(tv32));
} else if (pingflags & F_TIMING64)
(void) memcpy(&opack_icmp.icmp_data[0], &now, sizeof(now));
cc = MAX(datalen, ICMP_MINLEN) + PHDR_LEN;
opack_icmp.icmp_cksum = 0;
opack_icmp.icmp_cksum = in_cksum((u_int16_t *)&opack_icmp, cc);
cc += opack_ip->ip_hl<<2;
opack_ip->ip_len = cc;
i = prog_sendto(s, (char *) opack_ip, cc, 0,
(struct sockaddr *)&send_addr, sizeof(struct sockaddr_in));
if (i != cc) {
jiggle_flush(1);
if (i < 0)
warn("sendto");
else
warnx("wrote %s %d chars, ret=%d", hostname, cc, i);
(void)fflush(stderr);
}
lastrcvd = 0;
CLR(ntransmitted);
ntransmitted++;
last_tx = now;
if (next_tx.tv_sec == 0) {
first_tx = now;
next_tx = now;
}
/* Transmit regularly, at always the same microsecond in the
* second when going at one packet per second.
* If we are at most 100 ms behind, send extras to get caught up.
* Otherwise, skip packets we were too slow to send.
*/
waittime = diffsec(&next_tx, &now);
if (waittime < -1.0) {
/* very behind - forget about being precise */
next_tx.tv_sec += (int)(-waittime);
} else if (waittime < -0.1) {
/* behind - skip a few */
if (interval_tv.tv_sec == 0) {
numskip = (long)(-waittime / interval_tv.tv_nsec);
next_tx.tv_nsec += numskip * interval_tv.tv_nsec;
/*
* We can add at most one second's worth, but allow
* for tv_nsec reaching 2 billion just in case FP
* issues strike.
*/
while (next_tx.tv_nsec >= 1000000000) {
next_tx.tv_sec++;
next_tx.tv_nsec -= 1000000000;
}