summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNick Kralevich <nnk@google.com>2013-02-21 15:54:51 -0800
committerNick Kralevich <nnk@google.com>2013-02-21 17:02:28 -0800
commitef37d714c2d9bbc7ee483bd1e1092c65c74ab92a (patch)
tree4ba6e8191b2b2201ea374c1a076ef6e2ecbd4b07
parent351fb705d76aa9b12ea69b1ffe456c23029f1064 (diff)
downloadping-ef37d714c2d9bbc7ee483bd1e1092c65c74ab92a.tar.gz
Update ping to one that understands IPPROTO_ICMP
See http://lwn.net/Articles/443051/ for more details. Change-Id: Ib7f597723b98a77032ced633f35b32a6f44c8747
-rw-r--r--Android.mk2
-rw-r--r--SNAPSHOT.h1
-rw-r--r--ping.c1769
-rw-r--r--ping_common.c857
-rw-r--r--ping_common.h10
5 files changed, 1358 insertions, 1281 deletions
diff --git a/Android.mk b/Android.mk
index b977022..5eaa892 100644
--- a/Android.mk
+++ b/Android.mk
@@ -1,6 +1,6 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= ping.c
+LOCAL_SRC_FILES:= ping.c ping_common.c
LOCAL_MODULE := ping
include $(BUILD_EXECUTABLE)
diff --git a/SNAPSHOT.h b/SNAPSHOT.h
new file mode 100644
index 0000000..6fc6b9c
--- /dev/null
+++ b/SNAPSHOT.h
@@ -0,0 +1 @@
+static char SNAPSHOT[] = "020927";
diff --git a/ping.c b/ping.c
index daefc41..a322a24 100644
--- a/ping.c
+++ b/ping.c
@@ -61,908 +61,525 @@ char copyright[] =
#include "ping_common.h"
#include <netinet/ip.h>
-#include <linux/icmp.h>
-#include <sched.h>
+#include <netinet/ip_icmp.h>
+
+#ifdef ANDROID
#include <sys/types.h>
#include <private/android_filesystem_config.h>
+#define bcmp(a, b, c) memcmp(a, b, c)
+#endif
-#define bzero(b,sz) memset(b, 0, sz)
-
-/* PING COMMON */
-
-int options;
-
-int sndbuf;
-int ttl;
-int rtt;
-int rtt_addend;
-__u16 acked;
-
-int mx_dup_ck = MAX_DUP_CHK;
-char rcvd_tbl[MAX_DUP_CHK / 8];
-
-
-/* counters */
-long npackets; /* max packets to transmit */
-long nreceived; /* # of packets we got back */
-long nrepeats; /* number of duplicates */
-long ntransmitted; /* sequence # for outbound packets = #sent */
-long nchecksum; /* replies with bad checksum */
-long nerrors; /* icmp errors */
-int interval = 1000; /* interval between packets (msec) */
-int preload;
-int deadline = 0; /* time to die */
-int lingertime = MAXWAIT*1000;
-struct timeval start_time, cur_time;
-volatile int exiting;
-volatile int status_snapshot;
-int confirm = 0;
-
-/* Stupid workarounds for bugs/missing functionality in older linuces.
- * confirm_flag fixes refusing service of kernels without MSG_CONFIRM.
- * i.e. for linux-2.2 */
-int confirm_flag = MSG_CONFIRM;
-/* And this is workaround for bug in IP_RECVERR on raw sockets which is present
- * in linux-2.2.[0-19], linux-2.4.[0-7] */
-int working_recverr;
-
-/* timing */
-int timing; /* flag to do timing */
-long tmin = LONG_MAX; /* minimum round trip time */
-long tmax; /* maximum round trip time */
-/* Message for rpm maintainers: have _shame_. If you want
- * to fix something send the patch to me for sanity checking.
- * "sparcfix" patch is a complete non-sense, apparenly the person
- * prepared it was stoned.
- */
-long long tsum; /* sum of all times, for doing average */
-long long tsum2;
-int pipesize = -1;
-
-int datalen = DEFDATALEN;
-
-char *hostname;
-int uid;
-int ident; /* process id to identify our packets */
-
-static int screen_width = INT_MAX;
-
-/* Fills all the outpack, excluding ICMP header, but _including_
- * timestamp area with supplied pattern.
- */
-static void fill(char *patp)
-{
- int ii, jj, kk;
- int pat[16];
- char *cp;
- char *bp = outpack+8;
-
- for (cp = patp; *cp; cp++) {
- if (!isxdigit(*cp)) {
- fprintf(stderr,
- "ping: patterns must be specified as hex digits.\n");
- exit(2);
- }
- }
- ii = sscanf(patp,
- "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
- &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
- &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
- &pat[13], &pat[14], &pat[15]);
-
- if (ii > 0) {
- for (kk = 0; kk <= maxpacket - (8 + ii); kk += ii)
- for (jj = 0; jj < ii; ++jj)
- bp[jj + kk] = pat[jj];
- }
- if (!(options & F_QUIET)) {
- printf("PATTERN: 0x");
- for (jj = 0; jj < ii; ++jj)
- printf("%02x", bp[jj] & 0xFF);
- printf("\n");
- }
-}
+#define MAXIPLEN 60
+#define MAXICMPLEN 76
+#define NROUTES 9 /* number of record route slots */
+#define TOS_MAX 255 /* 8-bit TOS field */
-void common_options(int ch)
-{
- switch(ch) {
- case 'a':
- options |= F_AUDIBLE;
- break;
- case 'A':
- options |= F_ADAPTIVE;
- break;
- case 'c':
- npackets = atoi(optarg);
- if (npackets <= 0) {
- fprintf(stderr, "ping: bad number of packets to transmit.\n");
- exit(2);
- }
- break;
- case 'd':
- options |= F_SO_DEBUG;
- break;
- case 'f':
- options |= F_FLOOD;
- //setbuf(stdout, (char *)NULL);
- break;
- case 'i': /* wait between sending packets */
- {
- if (strchr(optarg, '.')) {
- float t;
- if (sscanf(optarg, "%f", &t) != 1) {
- fprintf(stderr, "ping: bad timing interval.\n");
- exit(2);
- }
- interval = (int)(t*1000);
- } else if (sscanf(optarg, "%d", &interval) == 1) {
- interval *= 1000;
- } else {
- fprintf(stderr, "ping: bad timing interval.\n");
- exit(2);
- }
- if (interval < 0) {
- fprintf(stderr, "ping: bad timing interval.\n");
- exit(2);
- }
- options |= F_INTERVAL;
- break;
- }
- case 'w':
- deadline = atoi(optarg);
- if (deadline < 0) {
- fprintf(stderr, "ping: bad wait time.\n");
- exit(2);
- }
- break;
- case 'l':
- preload = atoi(optarg);
- if (preload <= 0) {
- fprintf(stderr, "ping: bad preload value, should be 1..%d\n", mx_dup_ck);
- exit(2);
- }
- if (preload > mx_dup_ck)
- preload = mx_dup_ck;
- if (uid && preload > 3) {
- fprintf(stderr, "ping: cannot set preload to value > 3\n");
- exit(2);
- }
- break;
- case 'S':
- sndbuf = atoi(optarg);
- if (sndbuf <= 0) {
- fprintf(stderr, "ping: bad sndbuf value.\n");
- exit(2);
- }
- break;
- case 'n':
- options |= F_NUMERIC;
- break;
- case 'p': /* fill buffer with user pattern */
- options |= F_PINGFILLED;
- fill(optarg);
- break;
- case 'q':
- options |= F_QUIET;
- break;
- case 'r':
- options |= F_SO_DONTROUTE;
- break;
- case 's': /* size of packet to send */
- datalen = atoi(optarg);
- if (datalen < 0) {
- fprintf(stderr, "ping: illegal negative packet size %d.\n", datalen);
- exit(2);
- }
- break;
- case 'v':
- options |= F_VERBOSE;
- break;
- case 'L':
- options |= F_NOLOOP;
- break;
- case 't':
- options |= F_TTL;
- ttl = atoi(optarg);
- if (ttl < 0 || ttl > 255) {
- fprintf(stderr, "ping: ttl %u out of range\n", ttl);
- exit(2);
- }
- break;
- case 'U':
- options |= F_LATENCY;
- break;
- case 'B':
- options |= F_STRICTSOURCE;
- break;
- case 'W':
- lingertime = atoi(optarg);
- if (lingertime < 0 || lingertime > INT_MAX/1000000) {
- fprintf(stderr, "ping: bad linger time.\n");
- exit(2);
- }
- lingertime *= 1000;
- break;
- case 'V':
- printf("ping utility, iputils-ss\n");
- exit(0);
- default:
- abort();
- }
-}
+static int ts_type;
+static int nroute = 0;
+static __u32 route[10];
-static void sigexit(int signo)
-{
- exiting = 1;
-}
-static void sigstatus(int signo)
-{
- status_snapshot = 1;
-}
+struct sockaddr_in whereto; /* who to ping */
+int optlen = 0;
+int settos = 0; /* Set TOS, Precendence or other QOS options */
+int icmp_sock; /* socket file descriptor */
+int using_ping_socket = 0;
+u_char outpack[0x10000];
+int maxpacket = sizeof(outpack);
+static int broadcast_pings = 0;
-int __schedule_exit(int next)
-{
- static unsigned long waittime;
- struct itimerval it;
-
- if (waittime)
- return next;
-
- if (nreceived) {
- waittime = 2 * tmax;
- if (waittime < 1000*interval)
- waittime = 1000*interval;
- } else
- waittime = lingertime*1000;
-
- if (next < 0 || next < waittime/1000)
- next = waittime/1000;
-
- it.it_interval.tv_sec = 0;
- it.it_interval.tv_usec = 0;
- it.it_value.tv_sec = waittime/1000000;
- it.it_value.tv_usec = waittime%1000000;
- setitimer(ITIMER_REAL, &it, NULL);
- return next;
-}
+static char *pr_addr(__u32);
+static void pr_options(unsigned char * cp, int hlen);
+static void pr_iph(struct iphdr *ip);
+static void usage(void) __attribute__((noreturn));
+static u_short in_cksum(const u_short *addr, int len, u_short salt);
+static void pr_icmph(__u8 type, __u8 code, __u32 info, struct icmphdr *icp);
+static int parsetos(char *str);
-static inline void update_interval(void)
-{
- int est = rtt ? rtt/8 : interval*1000;
+static struct {
+ struct cmsghdr cm;
+ struct in_pktinfo ipi;
+} cmsg = { {sizeof(struct cmsghdr) + sizeof(struct in_pktinfo), SOL_IP, IP_PKTINFO},
+ {0, }};
+int cmsg_len;
- interval = (est+rtt_addend+500)/1000;
- if (uid && interval < MINUSERINTERVAL)
- interval = MINUSERINTERVAL;
-}
+struct sockaddr_in source;
+char *device;
+int pmtudisc = -1;
-/*
- * 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 8 bytes
- * of the data portion are used to hold a UNIX "timeval" struct in VAX
- * byte-order, to compute the round-trip time.
- */
-int pinger(void)
-{
- static int oom_count;
- static int tokens;
+#ifdef ANDROID
+int isInSupplementaryGroup(gid_t group) {
+ long ngroups_max;
+ gid_t empty[0];
+ gid_t *groups;
+ int ngroups;
int i;
- /* Have we already sent enough? If we have, return an arbitrary positive value. */
- if (exiting || (npackets && ntransmitted >= npackets && !deadline))
- return 1000;
-
- /* Check that packets < rate*time + preload */
- if (cur_time.tv_sec == 0) {
- gettimeofday(&cur_time, NULL);
- tokens = interval*(preload-1);
- } else {
- long ntokens;
- struct timeval tv;
-
- gettimeofday(&tv, NULL);
- ntokens = (tv.tv_sec - cur_time.tv_sec)*1000 +
- (tv.tv_usec-cur_time.tv_usec)/1000;
- if (!interval) {
- /* Case of unlimited flood is special;
- * if we see no reply, they are limited to 100pps */
- if (ntokens < MININTERVAL && in_flight() >= preload)
- return MININTERVAL-ntokens;
- }
- ntokens += tokens;
- if (ntokens > interval*preload)
- ntokens = interval*preload;
- if (ntokens < interval)
- return interval - ntokens;
-
- cur_time = tv;
- tokens = ntokens - interval;
+ if (getuid() == 0) {
+ // root is presumed to be in every group
+ return 1;
}
-resend:
- i = send_probe();
-
- if (i == 0) {
- oom_count = 0;
- advance_ntransmitted();
- if (!(options & F_QUIET) && (options & F_FLOOD)) {
- /* Very silly, but without this output with
- * high preload or pipe size is very confusing. */
- if ((preload < screen_width && pipesize < screen_width) ||
- in_flight() < screen_width)
- write(STDOUT_FILENO, ".", 1);
- }
- return interval - tokens;
+ ngroups = getgroups(0, empty);
+ if (ngroups < 0) {
+ perror("ping: call to getgroups for sizing failed");
+ exit(2);
}
-
- /* And handle various errors... */
- if (i > 0) {
- /* Apparently, it is some fatal bug. */
- abort();
- } else if (errno == ENOBUFS || errno == ENOMEM) {
- int nores_interval;
-
- /* Device queue overflow or OOM. Packet is not sent. */
- tokens = 0;
- /* Slowdown. This works only in adaptive mode (option -A) */
- rtt_addend += (rtt < 8*50000 ? rtt/8 : 50000);
- if (options&F_ADAPTIVE)
- update_interval();
- nores_interval = SCHINT(interval/2);
- if (nores_interval > 500)
- nores_interval = 500;
- oom_count++;
- if (oom_count*nores_interval < lingertime)
- return nores_interval;
- i = 0;
- /* Fall to hard error. It is to avoid complete deadlock
- * on stuck output device even when dealine was not requested.
- * Expected timings are screwed up in any case, but we will
- * exit some day. :-) */
- } else if (errno == EAGAIN) {
- /* Socket buffer is full. */
- tokens += interval;
- return MININTERVAL;
- } else {
- if ((i=receive_error_msg()) > 0) {
- /* An ICMP error arrived. */
- tokens += interval;
- return MININTERVAL;
- }
- /* Compatibility with old linuces. */
- if (i == 0 && confirm_flag && errno == EINVAL) {
- confirm_flag = 0;
- errno = 0;
- }
- if (!errno)
- goto resend;
+ groups = (gid_t *) malloc((ngroups * sizeof(gid_t)));
+ if (groups == NULL) {
+ fprintf(stderr, "ping: unable to allocate memory for %d groups. Aborting\n", ngroups);
+ exit(2);
}
-
- /* Hard local error. Pretend we sent packet. */
- advance_ntransmitted();
-
- if (i == 0 && !(options & F_QUIET)) {
- if (options & F_FLOOD)
- write(STDOUT_FILENO, "E", 1);
- else
- perror("ping: sendmsg");
+ ngroups = getgroups(ngroups, groups);
+ if (ngroups < 0) {
+ perror("ping: getgroups failed");
+ exit(2);
}
- tokens = 0;
- return SCHINT(interval);
-}
-/* Set socket buffers, "alloc" is an estimate of memory taken by single packet. */
-
-void sock_setbufs(int icmp_sock, int alloc)
-{
- int rcvbuf, hold;
- int tmplen = sizeof(hold);
-
- if (!sndbuf)
- sndbuf = alloc;
- setsockopt(icmp_sock, SOL_SOCKET, SO_SNDBUF, (char *)&sndbuf, sizeof(sndbuf));
-
- rcvbuf = hold = alloc * preload;
- if (hold < 65536)
- hold = 65536;
- setsockopt(icmp_sock, SOL_SOCKET, SO_RCVBUF, (char *)&hold, sizeof(hold));
- if (getsockopt(icmp_sock, SOL_SOCKET, SO_RCVBUF, (char *)&hold, &tmplen) == 0) {
- if (hold < rcvbuf)
- fprintf(stderr, "WARNING: probably, rcvbuf is not enough to hold preload.\n");
+ for (i = 0; i < ngroups; i++) {
+ if (group == groups[i]) {
+ free(groups);
+ return 1;
+ }
}
-}
-/* Protocol independent setup and parameter checks. */
+ free(groups);
+ return 0;
+}
+#endif
-void setup(int icmp_sock)
+int
+main(int argc, char **argv)
{
- int hold;
- struct timeval tv;
-
- if ((options & F_FLOOD) && !(options & F_INTERVAL))
- interval = 0;
+ struct hostent *hp;
+ int ch, hold, packlen;
+ int socket_errno;
+ u_char *packet;
+ char *target, hnamebuf[MAXHOSTNAMELEN];
+ char rspace[3 + 4 * NROUTES + 1]; /* record route space */
- if (uid && interval < MINUSERINTERVAL) {
- fprintf(stderr, "ping: cannot flood; minimal interval, allowed for user, is %dms\n", MINUSERINTERVAL);
- exit(2);
- }
+ icmp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
+ if (icmp_sock != -1)
+ using_ping_socket = 1;
+ else
+ icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
+ socket_errno = errno;
- if (interval >= INT_MAX/preload) {
- fprintf(stderr, "ping: illegal preload and/or interval\n");
+#ifdef ANDROID
+ if (!isInSupplementaryGroup(AID_INET)) {
+ fprintf(stderr, "You must have internet permissions to use ping. Aborting.\n");
exit(2);
}
-
- hold = 1;
- if (options & F_SO_DEBUG)
- setsockopt(icmp_sock, SOL_SOCKET, SO_DEBUG, (char *)&hold, sizeof(hold));
- if (options & F_SO_DONTROUTE)
- setsockopt(icmp_sock, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, sizeof(hold));
-
-#ifdef SO_TIMESTAMP
- if (!(options&F_LATENCY)) {
- int on = 1;
- if (setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)))
- fprintf(stderr, "Warning: no SO_TIMESTAMP support, falling back to SIOCGSTAMP\n");
- }
#endif
+ uid = getuid();
+ setuid(uid);
- /* Set some SNDTIMEO to prevent blocking forever
- * on sends, when device is too slow or stalls. Just put limit
- * of one second, or "interval", if it is less.
- */
- tv.tv_sec = 1;
- tv.tv_usec = 0;
- if (interval < 1000) {
- tv.tv_sec = 0;
- tv.tv_usec = 1000 * SCHINT(interval);
- }
- setsockopt(icmp_sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv));
-
- /* Set RCVTIMEO to "interval". Note, it is just an optimization
- * allowing to avoid redundant poll(). */
- tv.tv_sec = SCHINT(interval)/1000;
- tv.tv_usec = 1000*(SCHINT(interval)%1000);
- if (setsockopt(icmp_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)))
- options |= F_FLOOD_POLL;
-
- if (!(options & F_PINGFILLED)) {
- int i;
- char *p = outpack+8;
-
- /* Do not forget about case of small datalen,
- * fill timestamp area too!
- */
- for (i = 0; i < datalen; ++i)
- *p++ = i;
- }
-
- ident = getpid() & 0xFFFF;
-
- set_signal(SIGINT, sigexit);
- set_signal(SIGALRM, sigexit);
- set_signal(SIGQUIT, sigstatus);
-
- gettimeofday(&start_time, NULL);
+ source.sin_family = AF_INET;
- if (deadline) {
- struct itimerval it;
+ preload = 1;
+ while ((ch = getopt(argc, argv, COMMON_OPTSTR "bRT:")) != EOF) {
+ switch(ch) {
+ case 'b':
+ broadcast_pings = 1;
+ break;
+ case 'Q':
+ settos = parsetos(optarg);
+ if (settos &&
+ (setsockopt(icmp_sock, IPPROTO_IP, IP_TOS,
+ (char *)&settos, sizeof(int)) < 0)) {
+ perror("ping: error setting QOS sockopts");
+ exit(2);
+ }
+ break;
+ case 'R':
+ if (options & F_TIMESTAMP) {
+ fprintf(stderr, "Only one of -T or -R may be used\n");
+ exit(2);
+ }
+ options |= F_RROUTE;
+ break;
+ case 'T':
+ if (options & F_RROUTE) {
+ fprintf(stderr, "Only one of -T or -R may be used\n");
+ exit(2);
+ }
+ 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 {
+ fprintf(stderr, "Invalid timestamp type\n");
+ exit(2);
+ }
+ break;
+ case 'I':
+ {
+ char dummy;
+ int i1, i2, i3, i4;
- it.it_interval.tv_sec = 0;
- it.it_interval.tv_usec = 0;
- it.it_value.tv_sec = deadline;
- it.it_value.tv_usec = 0;
- setitimer(ITIMER_REAL, &it, NULL);
+ if (sscanf(optarg, "%u.%u.%u.%u%c",
+ &i1, &i2, &i3, &i4, &dummy) == 4) {
+ __u8 *ptr;
+ ptr = (__u8*)&source.sin_addr;
+ ptr[0] = i1;
+ ptr[1] = i2;
+ ptr[2] = i3;
+ ptr[3] = i4;
+ options |= F_STRICTSOURCE;
+ } else {
+ device = optarg;
+ }
+ 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 {
+ fprintf(stderr, "ping: wrong value for -M: do, dont, want are valid ones.\n");
+ exit(2);
+ }
+ break;
+ case 'V':
+ printf("ping utility, iputils-ss%s\n", SNAPSHOT);
+ exit(0);
+ COMMON_OPTIONS
+ common_options(ch);
+ break;
+ default:
+ usage();
+ }
}
+ argc -= optind;
+ argv += optind;
-#if 0
- if (isatty(STDOUT_FILENO)) {
- struct winsize w;
-
- if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
- if (w.ws_col > 0)
- screen_width = w.ws_col;
+ if (argc == 0)
+ usage();
+ 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;
}
}
-#endif
-}
+ while (argc > 0) {
+ target = *argv;
-void main_loop(int icmp_sock, __u8 *packet, int packlen)
-{
- char addrbuf[128];
- char ans_data[4096];
- struct iovec iov;
- struct msghdr msg;
- struct cmsghdr *c;
- int cc;
- int next;
- int polling;
+ bzero((char *)&whereto, sizeof(whereto));
+ whereto.sin_family = AF_INET;
+ if (inet_aton(target, &whereto.sin_addr) == 1) {
+ hostname = target;
+ if (argc == 1)
+ options |= F_NUMERIC;
+ } else {
+ hp = gethostbyname(target);
+ if (!hp) {
+ fprintf(stderr, "ping: unknown host %s\n", target);
+ exit(2);
+ }
+ memcpy(&whereto.sin_addr, hp->h_addr, 4);
+ strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
+ hnamebuf[sizeof(hnamebuf) - 1] = 0;
+ hostname = hnamebuf;
+ }
+ if (argc > 1)
+ route[nroute++] = whereto.sin_addr.s_addr;
+ argc--;
+ argv++;
+ }
- iov.iov_base = (char *)packet;
+ if (source.sin_addr.s_addr == 0) {
+ int alen;
+ struct sockaddr_in dst = whereto;
+ int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
- for (;;) {
- /* Check exit conditions. */
- if (exiting)
- break;
- if (npackets && nreceived + nerrors >= npackets)
- break;
- if (deadline && nerrors)
- break;
- /* Check for and do special actions. */
- if (status_snapshot)
- status();
-
- /* Send probes scheduled to this time. */
- do {
- next = pinger();
- next = schedule_exit(next);
- } while (next <= 0);
-
- /* "next" is time to send next probe, if positive.
- * If next<=0 send now or as soon as possible. */
-
- /* Technical part. Looks wicked. Could be dropped,
- * if everyone used the newest kernel. :-)
- * Its purpose is:
- * 1. Provide intervals less than resolution of scheduler.
- * Solution: spinning.
- * 2. Avoid use of poll(), when recvmsg() can provide
- * timed waiting (SO_RCVTIMEO). */
- polling = 0;
- if ((options & (F_ADAPTIVE|F_FLOOD_POLL)) || next<SCHINT(interval)) {
- int recv_expected = in_flight();
-
- /* If we are here, recvmsg() is unable to wait for
- * required timeout. */
- if (1000*next <= 1000000/(int)HZ) {
- /* Very short timeout... So, if we wait for
- * something, we sleep for MININTERVAL.
- * Otherwise, spin! */
- if (recv_expected) {
- next = MININTERVAL;
- } else {
- next = 0;
- /* When spinning, no reasons to poll.
- * Use nonblocking recvmsg() instead. */
- polling = MSG_DONTWAIT;
- /* But yield yet. */
- sched_yield();
+ if (probe_fd < 0) {
+ perror("socket");
+ exit(2);
+ }
+ if (device) {
+ struct ifreq ifr;
+ memset(&ifr, 0, sizeof(ifr));
+ strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
+ if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1) {
+ if (IN_MULTICAST(ntohl(dst.sin_addr.s_addr))) {
+ struct ip_mreqn imr;
+ if (ioctl(probe_fd, SIOCGIFINDEX, &ifr) < 0) {
+ fprintf(stderr, "ping: unknown iface %s\n", device);
+ exit(2);
+ }
+ memset(&imr, 0, sizeof(imr));
+ imr.imr_ifindex = ifr.ifr_ifindex;
+ if (setsockopt(probe_fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1) {
+ perror("ping: IP_MULTICAST_IF");
+ exit(2);
+ }
}
}
-
- if (!polling &&
- ((options & (F_ADAPTIVE|F_FLOOD_POLL)) || interval)) {
- struct pollfd pset;
- pset.fd = icmp_sock;
- pset.events = POLLIN|POLLERR;
- pset.revents = 0;
- if (poll(&pset, 1, next) < 1 ||
- !(pset.revents&(POLLIN|POLLERR)))
- continue;
- polling = MSG_DONTWAIT;
- }
}
- for (;;) {
- struct timeval *recv_timep = NULL;
- struct timeval recv_time;
- int not_ours = 0; /* Raw socket can receive messages
- * destined to other running pings. */
-
- iov.iov_len = packlen;
- msg.msg_name = addrbuf;
- msg.msg_namelen = sizeof(addrbuf);
- msg.msg_iov = &iov;
- msg.msg_iovlen = 1;
- msg.msg_control = ans_data;
- msg.msg_controllen = sizeof(ans_data);
-
- cc = recvmsg(icmp_sock, &msg, polling);
- polling = MSG_DONTWAIT;
-
- if (cc < 0) {
- if (errno == EAGAIN || errno == EINTR)
- break;
- if (!receive_error_msg()) {
- if (errno) {
- perror("ping: recvmsg");
- break;
- }
- not_ours = 1;
- }
- } else {
+ if (settos &&
+ setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *)&settos, sizeof(int)) < 0)
+ perror("Warning: error setting QOS sockopts");
-#ifdef SO_TIMESTAMP
- for (c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
- if (c->cmsg_level != SOL_SOCKET ||
- c->cmsg_type != SO_TIMESTAMP)
- continue;
- if (c->cmsg_len < CMSG_LEN(sizeof(struct timeval)))
- continue;
- recv_timep = (struct timeval*)CMSG_DATA(c);
+ 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) {
+ fprintf(stderr, "Do you want to ping broadcast? Then -b\n");
+ exit(2);
}
-#endif
-
- if ((options&F_LATENCY) || recv_timep == NULL) {
- if ((options&F_LATENCY) ||
- ioctl(icmp_sock, SIOCGSTAMP, &recv_time))
- gettimeofday(&recv_time, NULL);
- recv_timep = &recv_time;
+ fprintf(stderr, "WARNING: pinging broadcast address\n");
+ if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
+ &broadcast_pings, sizeof(broadcast_pings)) < 0) {
+ perror ("can't set broadcasting");
+ exit(2);
}
-
- not_ours = parse_reply(&msg, cc, addrbuf, recv_timep);
+ if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
+ perror("connect");
+ exit(2);
+ }
+ } else {
+ perror("connect");
+ exit(2);
}
+ }
+ alen = sizeof(source);
+ if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1) {
+ perror("getsockname");
+ exit(2);
+ }
+ source.sin_port = 0;
+ close(probe_fd);
+ } while (0);
- /* See? ... someone runs another ping on this host. */
- if (not_ours)
- install_filter();
+ if (whereto.sin_addr.s_addr == 0)
+ whereto.sin_addr.s_addr = source.sin_addr.s_addr;
- /* If nothing is in flight, "break" returns us to pinger. */
- if (in_flight() == 0)
- break;
+ if (icmp_sock < 0) {
+ errno = socket_errno;
+ perror("ping: icmp open socket");
+ exit(2);
+ }
+
+ if (device) {
+ struct ifreq ifr;
- /* Otherwise, try to recvmsg() again. recvmsg()
- * is nonblocking after the first iteration, so that
- * if nothing is queued, it will receive EAGAIN
- * and return to pinger. */
+ memset(&ifr, 0, sizeof(ifr));
+ strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
+ if (ioctl(icmp_sock, SIOCGIFINDEX, &ifr) < 0) {
+ fprintf(stderr, "ping: unknown iface %s\n", device);
+ exit(2);
}
+ cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
+ cmsg_len = sizeof(cmsg);
}
- finish();
-}
-int gather_statistics(__u8 *ptr, int cc, __u16 seq, int hops,
- int csfailed, struct timeval *tv, char *from)
-{
- int dupflag = 0;
- long triptime = 0;
-
- ++nreceived;
- if (!csfailed)
- acknowledge(seq);
-
- if (timing && cc >= 8+sizeof(struct timeval)) {
- struct timeval tmp_tv;
- memcpy(&tmp_tv, ptr, sizeof(tmp_tv));
-
-restamp:
- tvsub(tv, &tmp_tv);
- triptime = tv->tv_sec * 1000000 + tv->tv_usec;
- if (triptime < 0) {
- fprintf(stderr, "Warning: time of day goes back (%ldus), taking countermeasures.\n", triptime);
- triptime = 0;
- if (!(options & F_LATENCY)) {
- gettimeofday(tv, NULL);
- options |= F_LATENCY;
- goto restamp;
+ if (broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
+ if (uid) {
+ if (interval < 1000) {
+ fprintf(stderr, "ping: broadcast ping with too short interval.\n");
+ exit(2);
+ }
+ if (pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO) {
+ fprintf(stderr, "ping: broadcast ping does not fragment.\n");
+ exit(2);
}
}
- if (!csfailed) {
- tsum += triptime;
- tsum2 += (long long)triptime * (long long)triptime;
- if (triptime < tmin)
- tmin = triptime;
- if (triptime > tmax)
- tmax = triptime;
- if (!rtt)
- rtt = triptime*8;
- else
- rtt += triptime-rtt/8;
- if (options&F_ADAPTIVE)
- update_interval();
- }
+ if (pmtudisc < 0)
+ pmtudisc = IP_PMTUDISC_DO;
}
- if (csfailed) {
- ++nchecksum;
- --nreceived;
- } else if (TST(seq % mx_dup_ck)) {
- ++nrepeats;
- --nreceived;
- dupflag = 1;
- } else {
- SET(seq % mx_dup_ck);
- dupflag = 0;
+ if (pmtudisc >= 0) {
+ if (setsockopt(icmp_sock, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof(pmtudisc)) == -1) {
+ perror("ping: IP_MTU_DISCOVER");
+ exit(2);
+ }
}
- confirm = confirm_flag;
- if (options & F_QUIET)
- return 1;
-
- if (options & F_FLOOD) {
- if (!csfailed)
- write(STDOUT_FILENO, "\b \b", 3);
- else
- write(STDOUT_FILENO, "\bC", 1);
+ if (!using_ping_socket) {
+ if ((options&F_STRICTSOURCE) &&
+ bind(icmp_sock, (struct sockaddr*)&source, sizeof(source)) == -1) {
+ perror("bind");
+ exit(2);
+ }
} else {
- int i;
- __u8 *cp, *dp;
- printf("%d bytes from %s: icmp_seq=%u", cc, from, seq);
+ struct sockaddr_in sa;
+ socklen_t sl;
- if (hops >= 0)
- printf(" ttl=%d", hops);
+ sa.sin_family = AF_INET;
+ sa.sin_port = 0;
+ sa.sin_addr.s_addr = (options&F_STRICTSOURCE) ?
+ source.sin_addr.s_addr : 0;
+ sl = sizeof(sa);
- if (cc < datalen+8) {
- printf(" (truncated)\n");
- return 1;
- }
- if (timing) {
- if (triptime >= 100000)
- printf(" time=%ld ms", triptime/1000);
- else if (triptime >= 10000)
- printf(" time=%ld.%01ld ms", triptime/1000,
- (triptime%1000)/100);
- else if (triptime >= 1000)
- printf(" time=%ld.%02ld ms", triptime/1000,
- (triptime%1000)/10);
- else
- printf(" time=%ld.%03ld ms", triptime/1000,
- triptime%1000);
- }
- if (dupflag)
- printf(" (DUP!)");
- if (csfailed)
- printf(" (BAD CHECKSUM!)");
-
- /* check the data */
- cp = ((u_char*)ptr) + sizeof(struct timeval);
- dp = &outpack[8 + sizeof(struct timeval)];
- for (i = sizeof(struct timeval); i < datalen; ++i, ++cp, ++dp) {
- if (*cp != *dp) {
- printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
- i, *dp, *cp);
- cp = (u_char*)ptr + sizeof(struct timeval);
- for (i = sizeof(struct timeval); i < datalen; ++i, ++cp) {
- if ((i % 32) == sizeof(struct timeval))
- printf("\n#%d\t", i);
- printf("%x ", *cp);
- }
- break;
- }
+ if (bind(icmp_sock, (struct sockaddr *) &sa, sl) == -1) {
+ perror("bind");
+ exit(2);
}
- }
- return 0;
-}
-static long llsqrt(long long a)
-{
- long long prev = ~((long long)1 << 63);
- long long x = a;
-
- if (x > 0) {
- while (x < prev) {
- prev = x;
- x = (x+(a/x))/2;
+ if (getsockname(icmp_sock, (struct sockaddr *) &sa, &sl) == -1) {
+ perror("getsockname");
+ exit(2);
}
+ ident = sa.sin_port;
}
- return (long)x;
-}
-
-/*
- * finish --
- * Print out statistics, and give up.
- */
-void finish(void)
-{
- struct timeval tv = cur_time;
-
- tvsub(&tv, &start_time);
-
- putchar('\n');
- fflush(stdout);
- printf("--- %s ping statistics ---\n", hostname);
- printf("%ld packets transmitted, ", ntransmitted);
- printf("%ld received", nreceived);
- if (nrepeats)
- printf(", +%ld duplicates", nrepeats);
- if (nchecksum)
- printf(", +%ld corrupted", nchecksum);
- if (nerrors)
- printf(", +%ld errors", nerrors);
- if (ntransmitted) {
- printf(", %d%% packet loss",
- (int) ((((long long)(ntransmitted - nreceived)) * 100) /
- ntransmitted));
- printf(", time %ldms", 1000*tv.tv_sec+tv.tv_usec/1000);
+ if (!using_ping_socket) {
+ 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(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
+ perror("WARNING: setsockopt(ICMP_FILTER)");
}
- putchar('\n');
- if (nreceived && timing) {
- long tmdev;
-
- tsum /= nreceived + nrepeats;
- tsum2 /= nreceived + nrepeats;
- tmdev = llsqrt(tsum2 - tsum * tsum);
+ hold = 1;
+ if (setsockopt(icmp_sock, SOL_IP, IP_RECVERR, (char *)&hold, sizeof(hold)))
+ fprintf(stderr, "WARNING: your kernel is veeery old. No problems.\n");
+ if (using_ping_socket) {
+ if (setsockopt(icmp_sock, SOL_IP, IP_RECVTTL, (char *)&hold, sizeof(hold)))
+ perror("WARNING: setsockopt(IP_RECVTTL)");
+ if (setsockopt(icmp_sock, SOL_IP, IP_RETOPTS, (char *)&hold, sizeof(hold)))
+ perror("WARNING: setsockopt(IP_RETOPTS)");
+ }
- printf("rtt min/avg/max/mdev = %ld.%03ld/%lu.%03ld/%ld.%03ld/%ld.%03ld ms",
- tmin/1000, tmin%1000,
- (unsigned long)(tsum/1000), (long)(tsum%1000),
- tmax/1000, tmax%1000,
- tmdev/1000, tmdev%1000
- );
+ /* record route option */
+ if (options & F_RROUTE) {
+ bzero(rspace, 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(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, sizeof(rspace)) < 0) {
+ perror("ping: record route");
+ exit(2);
+ }
}
- if (pipesize > 1)
- printf(", pipe %d", pipesize);
- if (ntransmitted > 1 && (!interval || (options&(F_FLOOD|F_ADAPTIVE)))) {
- int ipg = (1000000*(long long)tv.tv_sec+tv.tv_usec)/(ntransmitted-1);
- printf(", ipg/ewma %d.%03d/%d.%03d ms",
- ipg/1000, ipg%1000, rtt/8000, (rtt/8)%1000);
+ if (options & F_TIMESTAMP) {
+ bzero(rspace, 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++)
+ *(__u32*)&rspace[4+i*8] = route[i];
+ }
+ if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
+ rspace[3] = 2;
+ if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
+ perror("ping: ts option");
+ exit(2);
+ }
+ }
+ optlen = 40;
}
- putchar('\n');
- exit(!nreceived || (deadline && nreceived < npackets));
-}
-
-
-void status(void)
-{
- int loss = 0;
- long tavg = 0;
-
- status_snapshot = 0;
-
- if (ntransmitted)
- loss = (((long long)(ntransmitted - nreceived)) * 100) / ntransmitted;
-
- fprintf(stderr, "\r%ld/%ld packets, %d%% loss", ntransmitted, nreceived, loss);
-
- if (nreceived && timing) {
- tavg = tsum / (nreceived + nrepeats);
-
- fprintf(stderr, ", min/avg/ewma/max = %ld.%03ld/%lu.%03ld/%d.%03d/%ld.%03ld ms",
- tmin/1000, tmin%1000,
- tavg/1000, tavg%1000,
- rtt/8000, (rtt/8)%1000,
- tmax/1000, tmax%1000
- );
+ if (options & F_SOURCEROUTE) {
+ int i;
+ bzero(rspace, 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++)
+ *(__u32*)&rspace[4+i*4] = route[i];
+
+ if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute*4) < 0) {
+ perror("ping: record route");
+ exit(2);
+ }
+ optlen = 40;
}
- fprintf(stderr, "\n");
-}
-
-/* PING COMMON */
-
-#define MAXIPLEN 60
-#define MAXICMPLEN 76
-#define NROUTES 9 /* number of record route slots */
-#define TOS_MAX 255 /* 8-bit TOS field */
+ /* 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(icmp_sock, hold);
-static int ts_type;
-static int nroute = 0;
-static __u32 route[10];
+ if (broadcast_pings) {
+ if (setsockopt(icmp_sock, SOL_SOCKET, SO_BROADCAST,
+ &broadcast_pings, sizeof(broadcast_pings)) < 0) {
+ perror ("ping: can't set broadcasting");
+ exit(2);
+ }
+ }
+ if (options & F_NOLOOP) {
+ int loop = 0;
+ if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_LOOP,
+ &loop, 1) == -1) {
+ perror ("ping: can't disable multicast loopback");
+ exit(2);
+ }
+ }
+ if (options & F_TTL) {
+ int ittl = ttl;
+ if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_TTL,
+ &ttl, 1) == -1) {
+ perror ("ping: can't set multicast time-to-live");
+ exit(2);
+ }
+ if (setsockopt(icmp_sock, IPPROTO_IP, IP_TTL,
+ &ittl, sizeof(ittl)) == -1) {
+ perror ("ping: can't set unicast time-to-live");
+ exit(2);
+ }
+ }
+ if (datalen > 0xFFFF - 8 - optlen - 20) {
+ if (uid || datalen > sizeof(outpack)-8) {
+ fprintf(stderr, "Error: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
+ exit(2);
+ }
+ /* Allow small oversize to root yet. It will cause EMSGSIZE. */
+ fprintf(stderr, "WARNING: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
+ }
-struct sockaddr_in whereto; /* who to ping */
-int optlen = 0;
-int settos = 0; /* Set TOS, Precendence or other QOS options */
-int icmp_sock; /* socket file descriptor */
-u_char outpack[0x10000];
-int maxpacket = sizeof(outpack);
+ if (datalen >= sizeof(struct timeval)) /* can we time transfer */
+ timing = 1;
+ packlen = datalen + MAXIPLEN + MAXICMPLEN;
+ if (!(packet = (u_char *)malloc((u_int)packlen))) {
+ fprintf(stderr, "ping: out of memory.\n");
+ exit(2);
+ }
-static int broadcast_pings = 0;
+ 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 ?: "");
+ printf("%d(%d) bytes of data.\n", datalen, datalen+8+optlen+20);
-static char *pr_addr(__u32);
-static void pr_options(unsigned char * cp, int hlen);
-static void pr_iph(struct iphdr *ip);
-static void usage(void) __attribute__((noreturn));
-static u_short in_cksum(const u_short *addr, int len, u_short salt);
-static void pr_icmph(__u8 type, __u8 code, __u32 info, struct icmphdr *icp);
-static int parsetos(char *str);
+ setup(icmp_sock);
-static struct {
- struct cmsghdr cm;
- struct in_pktinfo ipi;
-} cmsg = { {sizeof(struct cmsghdr) + sizeof(struct in_pktinfo), SOL_IP, IP_PKTINFO},
- {0, }};
-int cmsg_len;
+ main_loop(icmp_sock, packet, packlen);
+}
-struct sockaddr_in source;
-char *device;
-int pmtudisc = -1;
int receive_error_msg()
{
@@ -1015,6 +632,7 @@ int receive_error_msg()
nerrors++;
} else if (e->ee_origin == SO_EE_ORIGIN_ICMP) {
struct sockaddr_in *sin = (struct sockaddr_in*)(e+1);
+ int error_pkt;
if (res < sizeof(icmph) ||
target.sin_addr.s_addr != whereto.sin_addr.s_addr ||
@@ -1025,9 +643,18 @@ int receive_error_msg()
goto out;
}
- acknowledge(ntohs(icmph.un.echo.sequence));
+ error_pkt = (e->ee_type != ICMP_REDIRECT &&
+ e->ee_type != ICMP_SOURCE_QUENCH);
+ if (error_pkt) {
+ acknowledge(ntohs(icmph.un.echo.sequence));
+ net_errors++;
+ nerrors++;
+ }
+ else {
+ saved_errno = 0;
+ }
- if (!working_recverr) {
+ if (!using_ping_socket && !working_recverr) {
struct icmp_filter filt;
working_recverr = 1;
/* OK, it works. Add stronger filter. */
@@ -1038,14 +665,13 @@ int receive_error_msg()
perror("\rWARNING: setsockopt(ICMP_FILTER)");
}
- net_errors++;
- nerrors++;
if (options & F_QUIET)
goto out;
if (options & F_FLOOD) {
- write(STDOUT_FILENO, "\bE", 2);
+ if (error_pkt)
+ write(STDOUT_FILENO, "\bE", 2);
} else {
- printf("From %s icmp_seq=%u ", pr_addr(sin->sin_addr.s_addr), ntohs(icmph.un.echo.sequence));
+ printf("From %s: icmp_seq=%u ", pr_addr(sin->sin_addr.s_addr), ntohs(icmph.un.echo.sequence));
pr_icmph(e->ee_type, e->ee_code, e->ee_info, NULL);
fflush(stdout);
}
@@ -1137,15 +763,41 @@ parse_reply(struct msghdr *msg, int cc, void *addr, struct timeval *tv)
struct iphdr *ip;
int hlen;
int csfailed;
+ struct cmsghdr *cmsg;
+ int ttl;
+ __u8 *opts;
+ int optlen;
/* Check the IP header */
ip = (struct iphdr *)buf;
- hlen = ip->ihl*4;
- if (cc < hlen + 8 || ip->ihl < 5) {
- if (options & F_VERBOSE)
- fprintf(stderr, "ping: packet too short (%d bytes) from %s\n", cc,
- pr_addr(from->sin_addr.s_addr));
- return 1;
+ if (!using_ping_socket) {
+ hlen = ip->ihl*4;
+ if (cc < hlen + 8 || ip->ihl < 5) {
+ if (options & F_VERBOSE)
+ fprintf(stderr, "ping: packet too short (%d bytes) from %s\n", cc,
+ pr_addr(from->sin_addr.s_addr));
+ return 1;
+ }
+ ttl = ip->ttl;
+ opts = buf + sizeof(struct iphdr);
+ optlen = hlen - sizeof(struct iphdr);
+ } else {
+ hlen = 0;
+ ttl = 0;
+ opts = buf;
+ optlen = 0;
+ for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
+ if (cmsg->cmsg_level != SOL_IP)
+ continue;
+ if (cmsg->cmsg_type == IP_TTL) {
+ if (cmsg->cmsg_len < sizeof(int))
+ continue;
+ ttl = *(int *) CMSG_DATA(cmsg);
+ } else if (cmsg->cmsg_type == IP_RETOPTS) {
+ opts = (__u8 *) CMSG_DATA(cmsg);
+ optlen = cmsg->cmsg_len;
+ }
+ }
}
/* Now the ICMP part */
@@ -1158,7 +810,7 @@ parse_reply(struct msghdr *msg, int cc, void *addr, struct timeval *tv)
return 1; /* 'Twas not our ECHO */
if (gather_statistics((__u8*)(icp+1), cc,
ntohs(icp->un.echo.sequence),
- ip->ttl, 0, tv, pr_addr(from->sin_addr.s_addr)))
+ ttl, 0, tv, pr_addr(from->sin_addr.s_addr)))
return 0;
} else {
/* We fall here when a redirect or source quench arrived.
@@ -1242,7 +894,7 @@ parse_reply(struct msghdr *msg, int cc, void *addr, struct timeval *tv)
}
if (!(options & F_FLOOD)) {
- pr_options(buf + sizeof(struct iphdr), hlen);
+ pr_options(opts, optlen + sizeof(struct iphdr));
if (options & F_AUDIBLE)
putchar('\a');
@@ -1348,8 +1000,7 @@ void pr_icmph(__u8 type, __u8 code, __u32 info, struct icmphdr *icp)
printf("Redirect, Bad Code: %d", code);
break;
}
- if (icp)
- printf("(New nexthop: %s)\n", pr_addr(icp->un.gateway));
+ printf("(New nexthop: %s)\n", pr_addr(icp ? icp->un.gateway : info));
if (icp && (options & F_VERBOSE))
pr_iph((struct iphdr*)(icp + 1));
break;
@@ -1466,7 +1117,7 @@ void pr_options(unsigned char * cp, int hlen)
if (i <= 0)
continue;
if (i == old_rrlen
- && !memcmp((char *)cp, old_rr, i)
+ && !bcmp((char *)cp, old_rr, i)
&& !(options & F_FLOOD)) {
printf("\t(same route)");
i = ((i + 3) / 4) * 4;
@@ -1474,7 +1125,7 @@ void pr_options(unsigned char * cp, int hlen)
break;
}
old_rrlen = i;
- memcpy((char *)cp, old_rr, i);
+ bcopy((char *)cp, old_rr, i);
printf("\nRR: ");
cp++;
for (;;) {
@@ -1649,7 +1300,7 @@ void install_filter(void)
insns
};
- if (once)
+ if (once || using_ping_socket)
return;
once = 1;
@@ -1670,445 +1321,3 @@ void usage(void)
" [ -T timestamp option ] [ -Q tos ] [hop1 ...] destination\n");
exit(2);
}
-
-int isInSupplementaryGroup(gid_t group) {
- long ngroups_max;
- gid_t empty[0];
- gid_t *groups;
- int ngroups;
- int i;
-
- if (getuid() == 0) {
- // root is presumed to be in every group
- return 1;
- }
-
- ngroups = getgroups(0, empty);
- if (ngroups < 0) {
- perror("ping: call to getgroups for sizing failed");
- exit(2);
- }
- groups = (gid_t *) malloc((ngroups * sizeof(gid_t)));
- if (groups == NULL) {
- fprintf(stderr, "ping: unable to allocate memory for %d groups. Aborting\n", ngroups);
- exit(2);
- }
- ngroups = getgroups(ngroups, groups);
- if (ngroups < 0) {
- perror("ping: getgroups failed");
- exit(2);
- }
-
- for (i = 0; i < ngroups; i++) {
- if (group == groups[i]) {
- free(groups);
- return 1;
- }
- }
-
- free(groups);
- return 0;
-}
-
-int main(int argc, char *argv[])
-{
- struct hostent *hp;
- int ch, hold, packlen;
- int socket_errno;
- u_char *packet;
- char *target, hnamebuf[MAXHOSTNAMELEN];
- char rspace[3 + 4 * NROUTES + 1]; /* record route space */
-
- icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
- socket_errno = errno;
-
- /* if we were setuid root, undo that */
- if (setuid(getuid())) return -1;
-
- if (!isInSupplementaryGroup(AID_INET)) {
- fprintf(stderr, "You must have internet permissions to use ping. Aborting.\n");
- exit(2);
- }
-
- source.sin_family = AF_INET;
-
- preload = 1;
- while ((ch = getopt(argc, argv, COMMON_OPTSTR "bRT:")) != EOF) {
- switch(ch) {
- case 'b':
- broadcast_pings = 1;
- break;
- case 'Q':
- settos = parsetos(optarg);
- if (settos &&
- (setsockopt(icmp_sock, IPPROTO_IP, IP_TOS,
- (char *)&settos, sizeof(int)) < 0)) {
- perror("ping: error setting QOS sockopts");
- exit(2);
- }
- break;
- case 'R':
- if (options & F_TIMESTAMP) {
- fprintf(stderr, "Only one of -T or -R may be used\n");
- exit(2);
- }
- options |= F_RROUTE;
- break;
- case 'T':
- if (options & F_RROUTE) {
- fprintf(stderr, "Only one of -T or -R may be used\n");
- exit(2);
- }
- 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 {
- fprintf(stderr, "Invalid timestamp type\n");
- exit(2);
- }
- break;
- case 'I':
- {
- char dummy;
- int i1, i2, i3, i4;
-
- if (sscanf(optarg, "%u.%u.%u.%u%c",
- &i1, &i2, &i3, &i4, &dummy) == 4) {
- __u8 *ptr;
- ptr = (__u8*)&source.sin_addr;
- ptr[0] = i1;
- ptr[1] = i2;
- ptr[2] = i3;
- ptr[3] = i4;
- options |= F_STRICTSOURCE;
- } else {
- device = optarg;
- }
- 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 {
- fprintf(stderr, "ping: wrong value for -M: do, dont, want are valid ones.\n");
- exit(2);
- }
- break;
- case 'V':
- printf("ping utility, iputils-ss\n");
- exit(0);
- COMMON_OPTIONS
- common_options(ch);
- break;
- default:
- usage();
- }
- }
- argc -= optind;
- argv += optind;
-
- if (argc == 0)
- usage();
- 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;
-
- bzero((char *)&whereto, sizeof(whereto));
- whereto.sin_family = AF_INET;
- if (inet_aton(target, &whereto.sin_addr) == 1) {
- hostname = target;
- if (argc == 1)
- options |= F_NUMERIC;
- } else {
- hp = gethostbyname(target);
- hp = gethostbyname(target);
- hp = gethostbyname(target);
- if (!hp) {
- fprintf(stderr, "ping: unknown host %s\n", target);
- exit(2);
- }
- memcpy(&whereto.sin_addr, hp->h_addr, 4);
- strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
- hnamebuf[sizeof(hnamebuf) - 1] = 0;
- hostname = hnamebuf;
- }
- if (argc > 1)
- route[nroute++] = whereto.sin_addr.s_addr;
- argc--;
- argv++;
- }
-
- if (source.sin_addr.s_addr == 0) {
- int alen;
- struct sockaddr_in dst = whereto;
- int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
-
- if (probe_fd < 0) {
- perror("socket");
- exit(2);
- }
- if (device) {
- struct ifreq ifr;
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
- if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1) {
- if (IN_MULTICAST(ntohl(dst.sin_addr.s_addr))) {
- struct ip_mreqn imr;
- if (ioctl(probe_fd, SIOCGIFINDEX, &ifr) < 0) {
- fprintf(stderr, "ping: unknown iface %s\n", device);
- exit(2);
- }
- memset(&imr, 0, sizeof(imr));
- imr.imr_ifindex = ifr.ifr_ifindex;
- if (setsockopt(probe_fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1) {
- perror("ping: IP_MULTICAST_IF");
- exit(2);
- }
- }
- }
- }
-
- if (settos &&
- setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *)&settos, sizeof(int)) < 0)
- perror("Warning: error setting 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) {
- fprintf(stderr, "Do you want to ping broadcast? Then -b\n");
- exit(2);
- }
- fprintf(stderr, "WARNING: pinging broadcast address\n");
- if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
- &broadcast_pings, sizeof(broadcast_pings)) < 0) {
- perror ("can't set broadcasting");
- exit(2);
- }
- if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
- perror("connect");
- exit(2);
- }
- } else {
- perror("connect");
- exit(2);
- }
- }
- alen = sizeof(source);
- if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1) {
- perror("getsockname");
- exit(2);
- }
- source.sin_port = 0;
- close(probe_fd);
- } while (0);
-
- if (whereto.sin_addr.s_addr == 0)
- whereto.sin_addr.s_addr = source.sin_addr.s_addr;
-
- if (icmp_sock < 0) {
- errno = socket_errno;
- perror("ping: icmp open socket");
- exit(2);
- }
-
- if (device) {
- struct ifreq ifr;
-
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
- if (ioctl(icmp_sock, SIOCGIFINDEX, &ifr) < 0) {
- fprintf(stderr, "ping: unknown iface %s\n", device);
- exit(2);
- }
- cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
- cmsg_len = sizeof(cmsg);
- }
-
- if (broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
- if (uid) {
- if (interval < 1000) {
- fprintf(stderr, "ping: broadcast ping with too short interval.\n");
- exit(2);
- }
- if (pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO) {
- fprintf(stderr, "ping: broadcast ping does not fragment.\n");
- exit(2);
- }
- }
- if (pmtudisc < 0)
- pmtudisc = IP_PMTUDISC_DO;
- }
-
- if (pmtudisc >= 0) {
- if (setsockopt(icmp_sock, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof(pmtudisc)) == -1) {
- perror("ping: IP_MTU_DISCOVER");
- exit(2);
- }
- }
-
- if ((options&F_STRICTSOURCE) &&
- bind(icmp_sock, (struct sockaddr*)&source, sizeof(source)) == -1) {
- perror("bind");
- exit(2);
- }
-
- if (1) {
- 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(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
- perror("WARNING: setsockopt(ICMP_FILTER)");
- }
-
- hold = 1;
- if (setsockopt(icmp_sock, SOL_IP, IP_RECVERR, (char *)&hold, sizeof(hold)))
- fprintf(stderr, "WARNING: your kernel is veeery old. No problems.\n");
-
- /* record route option */
- if (options & F_RROUTE) {
- bzero(rspace, 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(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, sizeof(rspace)) < 0) {
- perror("ping: record route");
- exit(2);
- }
- }
- if (options & F_TIMESTAMP) {
- bzero(rspace, 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++)
- *(__u32*)&rspace[4+i*8] = route[i];
- }
- if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
- rspace[3] = 2;
- if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
- perror("ping: ts option");
- exit(2);
- }
- }
- optlen = 40;
- }
- if (options & F_SOURCEROUTE) {
- int i;
- bzero(rspace, 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++)
- *(__u32*)&rspace[4+i*4] = route[i];
-
- if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute*4) < 0) {
- perror("ping: record route");
- exit(2);
- }
- 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(icmp_sock, hold);
-
- if (broadcast_pings) {
- if (setsockopt(icmp_sock, SOL_SOCKET, SO_BROADCAST,
- &broadcast_pings, sizeof(broadcast_pings)) < 0) {
- perror ("ping: can't set broadcasting");
- exit(2);
- }
- }
-
- if (options & F_NOLOOP) {
- int loop = 0;
- if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_LOOP,
- &loop, 1) == -1) {
- perror ("ping: can't disable multicast loopback");
- exit(2);
- }
- }
- if (options & F_TTL) {
- int ittl = ttl;
- if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_TTL,
- &ttl, 1) == -1) {
- perror ("ping: can't set multicast time-to-live");
- exit(2);
- }
- if (setsockopt(icmp_sock, IPPROTO_IP, IP_TTL,
- &ittl, sizeof(ittl)) == -1) {
- perror ("ping: can't set unicast time-to-live");
- exit(2);
- }
- }
-
- if (datalen > 0xFFFF - 8 - optlen - 20) {
- if (uid || datalen > sizeof(outpack)-8) {
- fprintf(stderr, "Error: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
- exit(2);
- }
- /* Allow small oversize to root yet. It will cause EMSGSIZE. */
- fprintf(stderr, "WARNING: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
- }
-
- if (datalen >= sizeof(struct timeval)) /* can we time transfer */
- timing = 1;
- packlen = datalen + MAXIPLEN + MAXICMPLEN;
- if (!(packet = (u_char *)malloc((u_int)packlen))) {
- fprintf(stderr, "ping: out of memory.\n");
- exit(2);
- }
-
- 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 ?: "");
- printf("%d(%d) bytes of data.\n", datalen, datalen+8+optlen+20);
-
- setup(icmp_sock);
-
- main_loop(icmp_sock, packet, packlen);
- return 0;
-}
-
-void *dlopen(const char *filename, int flag) { return 0; }
-char *dlerror(void) { return 0; }
-void *dlsym(void *handle, const char *symbol) { return 0; }
-int dlclose(void *handle) { return 0; }
diff --git a/ping_common.c b/ping_common.c
new file mode 100644
index 0000000..e8ae6b8
--- /dev/null
+++ b/ping_common.c
@@ -0,0 +1,857 @@
+#include "ping_common.h"
+#include <ctype.h>
+#include <sched.h>
+
+int options;
+
+int sndbuf;
+int ttl;
+int rtt;
+int rtt_addend;
+__u16 acked;
+
+int mx_dup_ck = MAX_DUP_CHK;
+char rcvd_tbl[MAX_DUP_CHK / 8];
+
+
+/* counters */
+long npackets; /* max packets to transmit */
+long nreceived; /* # of packets we got back */
+long nrepeats; /* number of duplicates */
+long ntransmitted; /* sequence # for outbound packets = #sent */
+long nchecksum; /* replies with bad checksum */
+long nerrors; /* icmp errors */
+int interval = 1000; /* interval between packets (msec) */
+int preload;
+int deadline = 0; /* time to die */
+int lingertime = MAXWAIT*1000;
+struct timeval start_time, cur_time;
+volatile int exiting;
+volatile int status_snapshot;
+int confirm = 0;
+
+/* Stupid workarounds for bugs/missing functionality in older linuces.
+ * confirm_flag fixes refusing service of kernels without MSG_CONFIRM.
+ * i.e. for linux-2.2 */
+int confirm_flag = MSG_CONFIRM;
+/* And this is workaround for bug in IP_RECVERR on raw sockets which is present
+ * in linux-2.2.[0-19], linux-2.4.[0-7] */
+int working_recverr;
+
+/* timing */
+int timing; /* flag to do timing */
+long tmin = LONG_MAX; /* minimum round trip time */
+long tmax; /* maximum round trip time */
+/* Message for rpm maintainers: have _shame_. If you want
+ * to fix something send the patch to me for sanity checking.
+ * "sparcfix" patch is a complete non-sense, apparenly the person
+ * prepared it was stoned.
+ */
+long long tsum; /* sum of all times, for doing average */
+long long tsum2;
+int pipesize = -1;
+
+int datalen = DEFDATALEN;
+
+char *hostname;
+int uid;
+int ident; /* process id to identify our packets */
+
+static int screen_width = INT_MAX;
+
+/* Fills all the outpack, excluding ICMP header, but _including_
+ * timestamp area with supplied pattern.
+ */
+static void fill(char *patp)
+{
+ int ii, jj, kk;
+ int pat[16];
+ char *cp;
+ char *bp = outpack+8;
+
+ for (cp = patp; *cp; cp++) {
+ if (!isxdigit(*cp)) {
+ fprintf(stderr,
+ "ping: patterns must be specified as hex digits.\n");
+ exit(2);
+ }
+ }
+ ii = sscanf(patp,
+ "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
+ &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
+ &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
+ &pat[13], &pat[14], &pat[15]);
+
+ if (ii > 0) {
+ for (kk = 0; kk <= maxpacket - (8 + ii); kk += ii)
+ for (jj = 0; jj < ii; ++jj)
+ bp[jj + kk] = pat[jj];
+ }
+ if (!(options & F_QUIET)) {
+ printf("PATTERN: 0x");
+ for (jj = 0; jj < ii; ++jj)
+ printf("%02x", bp[jj] & 0xFF);
+ printf("\n");
+ }
+}
+
+void common_options(int ch)
+{
+ switch(ch) {
+ case 'a':
+ options |= F_AUDIBLE;
+ break;
+ case 'A':
+ options |= F_ADAPTIVE;
+ break;
+ case 'c':
+ npackets = atoi(optarg);
+ if (npackets <= 0) {
+ fprintf(stderr, "ping: bad number of packets to transmit.\n");
+ exit(2);
+ }
+ break;
+ case 'd':
+ options |= F_SO_DEBUG;
+ break;
+ case 'f':
+ options |= F_FLOOD;
+ setbuf(stdout, (char *)NULL);
+ break;
+ case 'i': /* wait between sending packets */
+ {
+ if (strchr(optarg, '.')) {
+ float t;
+ if (sscanf(optarg, "%f", &t) != 1) {
+ fprintf(stderr, "ping: bad timing interval.\n");
+ exit(2);
+ }
+ interval = (int)(t*1000);
+ } else if (sscanf(optarg, "%d", &interval) == 1) {
+ interval *= 1000;
+ } else {
+ fprintf(stderr, "ping: bad timing interval.\n");
+ exit(2);
+ }
+
+ if (interval < 0) {
+ fprintf(stderr, "ping: bad timing interval.\n");
+ exit(2);
+ }
+ options |= F_INTERVAL;
+ break;
+ }
+ case 'w':
+ deadline = atoi(optarg);
+ if (deadline < 0) {
+ fprintf(stderr, "ping: bad wait time.\n");
+ exit(2);
+ }
+ break;
+ case 'l':
+ preload = atoi(optarg);
+ if (preload <= 0) {
+ fprintf(stderr, "ping: bad preload value, should be 1..%d\n", mx_dup_ck);
+ exit(2);
+ }
+ if (preload > mx_dup_ck)
+ preload = mx_dup_ck;
+ if (uid && preload > 3) {
+ fprintf(stderr, "ping: cannot set preload to value > 3\n");
+ exit(2);
+ }
+ break;
+ case 'S':
+ sndbuf = atoi(optarg);
+ if (sndbuf <= 0) {
+ fprintf(stderr, "ping: bad sndbuf value.\n");
+ exit(2);
+ }
+ break;
+ case 'n':
+ options |= F_NUMERIC;
+ break;
+ case 'p': /* fill buffer with user pattern */
+ options |= F_PINGFILLED;
+ fill(optarg);
+ break;
+ case 'q':
+ options |= F_QUIET;
+ break;
+ case 'r':
+ options |= F_SO_DONTROUTE;
+ break;
+ case 's': /* size of packet to send */
+ datalen = atoi(optarg);
+ if (datalen < 0) {
+ fprintf(stderr, "ping: illegal negative packet size %d.\n", datalen);
+ exit(2);
+ }
+ break;
+ case 'v':
+ options |= F_VERBOSE;
+ break;
+ case 'L':
+ options |= F_NOLOOP;
+ break;
+ case 't':
+ options |= F_TTL;
+ ttl = atoi(optarg);
+ if (ttl < 0 || ttl > 255) {
+ fprintf(stderr, "ping: ttl %u out of range\n", ttl);
+ exit(2);
+ }
+ break;
+ case 'U':
+ options |= F_LATENCY;
+ break;
+ case 'B':
+ options |= F_STRICTSOURCE;
+ break;
+ case 'W':
+ lingertime = atoi(optarg);
+ if (lingertime < 0 || lingertime > INT_MAX/1000000) {
+ fprintf(stderr, "ping: bad linger time.\n");
+ exit(2);
+ }
+ lingertime *= 1000;
+ break;
+ case 'V':
+ printf("ping utility, iputils-ss%s\n", SNAPSHOT);
+ exit(0);
+ default:
+ abort();
+ }
+}
+
+
+static void sigexit(int signo)
+{
+ exiting = 1;
+}
+
+static void sigstatus(int signo)
+{
+ status_snapshot = 1;
+}
+
+
+int __schedule_exit(int next)
+{
+ static unsigned long waittime;
+ struct itimerval it;
+
+ if (waittime)
+ return next;
+
+ if (nreceived) {
+ waittime = 2 * tmax;
+ if (waittime < 1000*interval)
+ waittime = 1000*interval;
+ } else
+ waittime = lingertime*1000;
+
+ if (next < 0 || next < waittime/1000)
+ next = waittime/1000;
+
+ it.it_interval.tv_sec = 0;
+ it.it_interval.tv_usec = 0;
+ it.it_value.tv_sec = waittime/1000000;
+ it.it_value.tv_usec = waittime%1000000;
+ setitimer(ITIMER_REAL, &it, NULL);
+ return next;
+}
+
+static inline void update_interval(void)
+{
+ int est = rtt ? rtt/8 : interval*1000;
+
+ interval = (est+rtt_addend+500)/1000;
+ if (uid && interval < MINUSERINTERVAL)
+ interval = MINUSERINTERVAL;
+}
+
+/*
+ * 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 8 bytes
+ * of the data portion are used to hold a UNIX "timeval" struct in VAX
+ * byte-order, to compute the round-trip time.
+ */
+int pinger(void)
+{
+ static int oom_count;
+ static int tokens;
+ int i;
+
+ /* Have we already sent enough? If we have, return an arbitrary positive value. */
+ if (exiting || (npackets && ntransmitted >= npackets && !deadline))
+ return 1000;
+
+ /* Check that packets < rate*time + preload */
+ if (cur_time.tv_sec == 0) {
+ gettimeofday(&cur_time, NULL);
+ tokens = interval*(preload-1);
+ } else {
+ long ntokens;
+ struct timeval tv;
+
+ gettimeofday(&tv, NULL);
+ ntokens = (tv.tv_sec - cur_time.tv_sec)*1000 +
+ (tv.tv_usec-cur_time.tv_usec)/1000;
+ if (!interval) {
+ /* Case of unlimited flood is special;
+ * if we see no reply, they are limited to 100pps */
+ if (ntokens < MININTERVAL && in_flight() >= preload)
+ return MININTERVAL-ntokens;
+ }
+ ntokens += tokens;
+ if (ntokens > interval*preload)
+ ntokens = interval*preload;
+ if (ntokens < interval)
+ return interval - ntokens;
+
+ cur_time = tv;
+ tokens = ntokens - interval;
+ }
+
+resend:
+ i = send_probe();
+
+ if (i == 0) {
+ oom_count = 0;
+ advance_ntransmitted();
+ if (!(options & F_QUIET) && (options & F_FLOOD)) {
+ /* Very silly, but without this output with
+ * high preload or pipe size is very confusing. */
+ if ((preload < screen_width && pipesize < screen_width) ||
+ in_flight() < screen_width)
+ write(STDOUT_FILENO, ".", 1);
+ }
+ return interval - tokens;
+ }
+
+ /* And handle various errors... */
+ if (i > 0) {
+ /* Apparently, it is some fatal bug. */
+ abort();
+ } else if (errno == ENOBUFS || errno == ENOMEM) {
+ int nores_interval;
+
+ /* Device queue overflow or OOM. Packet is not sent. */
+ tokens = 0;
+ /* Slowdown. This works only in adaptive mode (option -A) */
+ rtt_addend += (rtt < 8*50000 ? rtt/8 : 50000);
+ if (options&F_ADAPTIVE)
+ update_interval();
+ nores_interval = SCHINT(interval/2);
+ if (nores_interval > 500)
+ nores_interval = 500;
+ oom_count++;
+ if (oom_count*nores_interval < lingertime)
+ return nores_interval;
+ i = 0;
+ /* Fall to hard error. It is to avoid complete deadlock
+ * on stuck output device even when dealine was not requested.
+ * Expected timings are screwed up in any case, but we will
+ * exit some day. :-) */
+ } else if (errno == EAGAIN) {
+ /* Socket buffer is full. */
+ tokens += interval;
+ return MININTERVAL;
+ } else {
+ if ((i=receive_error_msg()) > 0) {
+ /* An ICMP error arrived. */
+ tokens += interval;
+ return MININTERVAL;
+ }
+ /* Compatibility with old linuces. */
+ if (i == 0 && confirm_flag && errno == EINVAL) {
+ confirm_flag = 0;
+ errno = 0;
+ }
+ if (!errno)
+ goto resend;
+ }
+
+ /* Hard local error. Pretend we sent packet. */
+ advance_ntransmitted();
+
+ if (i == 0 && !(options & F_QUIET)) {
+ if (options & F_FLOOD)
+ write(STDOUT_FILENO, "E", 1);
+ else
+ perror("ping: sendmsg");
+ }
+ tokens = 0;
+ return SCHINT(interval);
+}
+
+/* Set socket buffers, "alloc" is an estimate of memory taken by single packet. */
+
+void sock_setbufs(int icmp_sock, int alloc)
+{
+ int rcvbuf, hold;
+ int tmplen = sizeof(hold);
+
+ if (!sndbuf)
+ sndbuf = alloc;
+ setsockopt(icmp_sock, SOL_SOCKET, SO_SNDBUF, (char *)&sndbuf, sizeof(sndbuf));
+
+ rcvbuf = hold = alloc * preload;
+ if (hold < 65536)
+ hold = 65536;
+ setsockopt(icmp_sock, SOL_SOCKET, SO_RCVBUF, (char *)&hold, sizeof(hold));
+ if (getsockopt(icmp_sock, SOL_SOCKET, SO_RCVBUF, (char *)&hold, &tmplen) == 0) {
+ if (hold < rcvbuf)
+ fprintf(stderr, "WARNING: probably, rcvbuf is not enough to hold preload.\n");
+ }
+}
+
+/* Protocol independent setup and parameter checks. */
+
+void setup(int icmp_sock)
+{
+ int hold;
+ struct timeval tv;
+
+ if ((options & F_FLOOD) && !(options & F_INTERVAL))
+ interval = 0;
+
+ if (uid && interval < MINUSERINTERVAL) {
+ fprintf(stderr, "ping: cannot flood; minimal interval, allowed for user, is %dms\n", MINUSERINTERVAL);
+ exit(2);
+ }
+
+ if (interval >= INT_MAX/preload) {
+ fprintf(stderr, "ping: illegal preload and/or interval\n");
+ exit(2);
+ }
+
+ hold = 1;
+ if (options & F_SO_DEBUG)
+ setsockopt(icmp_sock, SOL_SOCKET, SO_DEBUG, (char *)&hold, sizeof(hold));
+ if (options & F_SO_DONTROUTE)
+ setsockopt(icmp_sock, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, sizeof(hold));
+
+#ifdef SO_TIMESTAMP
+ if (!(options&F_LATENCY)) {
+ int on = 1;
+ if (setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)))
+ fprintf(stderr, "Warning: no SO_TIMESTAMP support, falling back to SIOCGSTAMP\n");
+ }
+#endif
+
+ /* Set some SNDTIMEO to prevent blocking forever
+ * on sends, when device is too slow or stalls. Just put limit
+ * of one second, or "interval", if it is less.
+ */
+ tv.tv_sec = 1;
+ tv.tv_usec = 0;
+ if (interval < 1000) {
+ tv.tv_sec = 0;
+ tv.tv_usec = 1000 * SCHINT(interval);
+ }
+ setsockopt(icmp_sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv));
+
+ /* Set RCVTIMEO to "interval". Note, it is just an optimization
+ * allowing to avoid redundant poll(). */
+ tv.tv_sec = SCHINT(interval)/1000;
+ tv.tv_usec = 1000*(SCHINT(interval)%1000);
+ if (setsockopt(icmp_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)))
+ options |= F_FLOOD_POLL;
+
+ if (!(options & F_PINGFILLED)) {
+ int i;
+ char *p = outpack+8;
+
+ /* Do not forget about case of small datalen,
+ * fill timestamp area too!
+ */
+ for (i = 0; i < datalen; ++i)
+ *p++ = i;
+ }
+
+ if (!ident)
+ ident = getpid() & 0xFFFF;
+
+ set_signal(SIGINT, sigexit);
+ set_signal(SIGALRM, sigexit);
+ set_signal(SIGQUIT, sigstatus);
+
+ gettimeofday(&start_time, NULL);
+
+ if (deadline) {
+ struct itimerval it;
+
+ it.it_interval.tv_sec = 0;
+ it.it_interval.tv_usec = 0;
+ it.it_value.tv_sec = deadline;
+ it.it_value.tv_usec = 0;
+ setitimer(ITIMER_REAL, &it, NULL);
+ }
+
+#ifndef ANDROID
+ if (isatty(STDOUT_FILENO)) {
+ struct winsize w;
+
+ if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
+ if (w.ws_col > 0)
+ screen_width = w.ws_col;
+ }
+ }
+#endif
+}
+
+void main_loop(int icmp_sock, __u8 *packet, int packlen)
+{
+ char addrbuf[128];
+ char ans_data[4096];
+ struct iovec iov;
+ struct msghdr msg;
+ struct cmsghdr *c;
+ int cc;
+ int next;
+ int polling;
+
+ iov.iov_base = (char *)packet;
+
+ for (;;) {
+ /* Check exit conditions. */
+ if (exiting)
+ break;
+ if (npackets && nreceived + nerrors >= npackets)
+ break;
+ if (deadline && nerrors)
+ break;
+ /* Check for and do special actions. */
+ if (status_snapshot)
+ status();
+
+ /* Send probes scheduled to this time. */
+ do {
+ next = pinger();
+ next = schedule_exit(next);
+ } while (next <= 0);
+
+ /* "next" is time to send next probe, if positive.
+ * If next<=0 send now or as soon as possible. */
+
+ /* Technical part. Looks wicked. Could be dropped,
+ * if everyone used the newest kernel. :-)
+ * Its purpose is:
+ * 1. Provide intervals less than resolution of scheduler.
+ * Solution: spinning.
+ * 2. Avoid use of poll(), when recvmsg() can provide
+ * timed waiting (SO_RCVTIMEO). */
+ polling = 0;
+ if ((options & (F_ADAPTIVE|F_FLOOD_POLL)) || next<SCHINT(interval)) {
+ int recv_expected = in_flight();
+
+ /* If we are here, recvmsg() is unable to wait for
+ * required timeout. */
+ if (1000*next <= 1000000/(int)HZ) {
+ /* Very short timeout... So, if we wait for
+ * something, we sleep for MININTERVAL.
+ * Otherwise, spin! */
+ if (recv_expected) {
+ next = MININTERVAL;
+ } else {
+ next = 0;
+ /* When spinning, no reasons to poll.
+ * Use nonblocking recvmsg() instead. */
+ polling = MSG_DONTWAIT;
+ /* But yield yet. */
+ sched_yield();
+ }
+ }
+
+ if (!polling &&
+ ((options & (F_ADAPTIVE|F_FLOOD_POLL)) || interval)) {
+ struct pollfd pset;
+ pset.fd = icmp_sock;
+ pset.events = POLLIN|POLLERR;
+ pset.revents = 0;
+ if (poll(&pset, 1, next) < 1 ||
+ !(pset.revents&(POLLIN|POLLERR)))
+ continue;
+ polling = MSG_DONTWAIT;
+ }
+ }
+
+ for (;;) {
+ struct timeval *recv_timep = NULL;
+ struct timeval recv_time;
+ int not_ours = 0; /* Raw socket can receive messages
+ * destined to other running pings. */
+
+ iov.iov_len = packlen;
+ msg.msg_name = addrbuf;
+ msg.msg_namelen = sizeof(addrbuf);
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+ msg.msg_control = ans_data;
+ msg.msg_controllen = sizeof(ans_data);
+
+ cc = recvmsg(icmp_sock, &msg, polling);
+ polling = MSG_DONTWAIT;
+
+ if (cc < 0) {
+ if (errno == EAGAIN || errno == EINTR)
+ break;
+ if (!receive_error_msg()) {
+ if (errno) {
+ perror("ping: recvmsg");
+ break;
+ }
+ not_ours = 1;
+ }
+ } else {
+
+#ifdef SO_TIMESTAMP
+ for (c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
+ if (c->cmsg_level != SOL_SOCKET ||
+ c->cmsg_type != SO_TIMESTAMP)
+ continue;
+ if (c->cmsg_len < CMSG_LEN(sizeof(struct timeval)))
+ continue;
+ recv_timep = (struct timeval*)CMSG_DATA(c);
+ }
+#endif
+
+ if ((options&F_LATENCY) || recv_timep == NULL) {
+ if ((options&F_LATENCY) ||
+ ioctl(icmp_sock, SIOCGSTAMP, &recv_time))
+ gettimeofday(&recv_time, NULL);
+ recv_timep = &recv_time;
+ }
+
+ not_ours = parse_reply(&msg, cc, addrbuf, recv_timep);
+ }
+
+ /* See? ... someone runs another ping on this host. */
+ if (not_ours)
+ install_filter();
+
+ /* If nothing is in flight, "break" returns us to pinger. */
+ if (in_flight() == 0)
+ break;
+
+ /* Otherwise, try to recvmsg() again. recvmsg()
+ * is nonblocking after the first iteration, so that
+ * if nothing is queued, it will receive EAGAIN
+ * and return to pinger. */
+ }
+ }
+ finish();
+}
+
+int gather_statistics(__u8 *ptr, int cc, __u16 seq, int hops,
+ int csfailed, struct timeval *tv, char *from)
+{
+ int dupflag = 0;
+ long triptime = 0;
+
+ ++nreceived;
+ if (!csfailed)
+ acknowledge(seq);
+
+ if (timing && cc >= 8+sizeof(struct timeval)) {
+ struct timeval tmp_tv;
+ memcpy(&tmp_tv, ptr, sizeof(tmp_tv));
+
+restamp:
+ tvsub(tv, &tmp_tv);
+ triptime = tv->tv_sec * 1000000 + tv->tv_usec;
+ if (triptime < 0) {
+ fprintf(stderr, "Warning: time of day goes back (%ldus), taking countermeasures.\n", triptime);
+ triptime = 0;
+ if (!(options & F_LATENCY)) {
+ gettimeofday(tv, NULL);
+ options |= F_LATENCY;
+ goto restamp;
+ }
+ }
+ if (!csfailed) {
+ tsum += triptime;
+ tsum2 += (long long)triptime * (long long)triptime;
+ if (triptime < tmin)
+ tmin = triptime;
+ if (triptime > tmax)
+ tmax = triptime;
+ if (!rtt)
+ rtt = triptime*8;
+ else
+ rtt += triptime-rtt/8;
+ if (options&F_ADAPTIVE)
+ update_interval();
+ }
+ }
+
+ if (csfailed) {
+ ++nchecksum;
+ --nreceived;
+ } else if (TST(seq % mx_dup_ck)) {
+ ++nrepeats;
+ --nreceived;
+ dupflag = 1;
+ } else {
+ SET(seq % mx_dup_ck);
+ dupflag = 0;
+ }
+ confirm = confirm_flag;
+
+ if (options & F_QUIET)
+ return 1;
+
+ if (options & F_FLOOD) {
+ if (!csfailed)
+ write(STDOUT_FILENO, "\b \b", 3);
+ else
+ write(STDOUT_FILENO, "\bC", 1);
+ } else {
+ int i;
+ __u8 *cp, *dp;
+ printf("%d bytes from %s: icmp_seq=%u", cc, from, seq);
+
+ if (hops >= 0)
+ printf(" ttl=%d", hops);
+
+ if (cc < datalen+8) {
+ printf(" (truncated)\n");
+ return 1;
+ }
+ if (timing) {
+ if (triptime >= 100000)
+ printf(" time=%ld ms", triptime/1000);
+ else if (triptime >= 10000)
+ printf(" time=%ld.%01ld ms", triptime/1000,
+ (triptime%1000)/100);
+ else if (triptime >= 1000)
+ printf(" time=%ld.%02ld ms", triptime/1000,
+ (triptime%1000)/10);
+ else
+ printf(" time=%ld.%03ld ms", triptime/1000,
+ triptime%1000);
+ }
+ if (dupflag)
+ printf(" (DUP!)");
+ if (csfailed)
+ printf(" (BAD CHECKSUM!)");
+
+ /* check the data */
+ cp = ((u_char*)ptr) + sizeof(struct timeval);
+ dp = &outpack[8 + sizeof(struct timeval)];
+ for (i = sizeof(struct timeval); i < datalen; ++i, ++cp, ++dp) {
+ if (*cp != *dp) {
+ printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
+ i, *dp, *cp);
+ cp = (u_char*)ptr + sizeof(struct timeval);
+ for (i = sizeof(struct timeval); i < datalen; ++i, ++cp) {
+ if ((i % 32) == sizeof(struct timeval))
+ printf("\n#%d\t", i);
+ printf("%x ", *cp);
+ }
+ break;
+ }
+ }
+ }
+ return 0;
+}
+
+static long llsqrt(long long a)
+{
+ long long prev = ~((long long)1 << 63);
+ long long x = a;
+
+ if (x > 0) {
+ while (x < prev) {
+ prev = x;
+ x = (x+(a/x))/2;
+ }
+ }
+
+ return (long)x;
+}
+
+/*
+ * finish --
+ * Print out statistics, and give up.
+ */
+void finish(void)
+{
+ struct timeval tv = cur_time;
+
+ tvsub(&tv, &start_time);
+
+ putchar('\n');
+ fflush(stdout);
+ printf("--- %s ping statistics ---\n", hostname);
+ printf("%ld packets transmitted, ", ntransmitted);
+ printf("%ld received", nreceived);
+ if (nrepeats)
+ printf(", +%ld duplicates", nrepeats);
+ if (nchecksum)
+ printf(", +%ld corrupted", nchecksum);
+ if (nerrors)
+ printf(", +%ld errors", nerrors);
+ if (ntransmitted) {
+ printf(", %d%% packet loss",
+ (int) ((((long long)(ntransmitted - nreceived)) * 100) /
+ ntransmitted));
+ printf(", time %ldms", 1000*tv.tv_sec+tv.tv_usec/1000);
+ }
+ putchar('\n');
+
+ if (nreceived && timing) {
+ long tmdev;
+
+ tsum /= nreceived + nrepeats;
+ tsum2 /= nreceived + nrepeats;
+ tmdev = llsqrt(tsum2 - tsum * tsum);
+
+ printf("rtt min/avg/max/mdev = %ld.%03ld/%lu.%03ld/%ld.%03ld/%ld.%03ld ms",
+ tmin/1000, tmin%1000,
+ (unsigned long)(tsum/1000), (long)(tsum%1000),
+ tmax/1000, tmax%1000,
+ tmdev/1000, tmdev%1000
+ );
+ }
+ if (pipesize > 1)
+ printf(", pipe %d", pipesize);
+ if (ntransmitted > 1 && (!interval || (options&(F_FLOOD|F_ADAPTIVE)))) {
+ int ipg = (1000000*(long long)tv.tv_sec+tv.tv_usec)/(ntransmitted-1);
+ printf(", ipg/ewma %d.%03d/%d.%03d ms",
+ ipg/1000, ipg%1000, rtt/8000, (rtt/8)%1000);
+ }
+ putchar('\n');
+ exit(!nreceived || (deadline && nreceived < npackets));
+}
+
+
+void status(void)
+{
+ int loss = 0;
+ long tavg = 0;
+
+ status_snapshot = 0;
+
+ if (ntransmitted)
+ loss = (((long long)(ntransmitted - nreceived)) * 100) / ntransmitted;
+
+ fprintf(stderr, "\r%ld/%ld packets, %d%% loss", ntransmitted, nreceived, loss);
+
+ if (nreceived && timing) {
+ tavg = tsum / (nreceived + nrepeats);
+
+ fprintf(stderr, ", min/avg/ewma/max = %ld.%03ld/%lu.%03ld/%d.%03d/%ld.%03ld ms",
+ tmin/1000, tmin%1000,
+ tavg/1000, tavg%1000,
+ rtt/8000, (rtt/8)%1000,
+ tmax/1000, tmax%1000
+ );
+ }
+ fprintf(stderr, "\n");
+}
+
diff --git a/ping_common.h b/ping_common.h
index a7c494d..8663b4c 100644
--- a/ping_common.h
+++ b/ping_common.h
@@ -7,7 +7,11 @@
#include <linux/sockios.h>
#include <sys/file.h>
#include <sys/time.h>
+#ifdef ANDROID
#include <signal.h>
+#else
+#include <sys/signal.h>
+#endif
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/uio.h>
@@ -21,6 +25,12 @@
#include <arpa/inet.h>
#include <linux/errqueue.h>
+#ifdef ANDROID
+#include <linux/icmp.h>
+#endif
+
+#include "SNAPSHOT.h"
+
#define DEFDATALEN (64 - 8) /* default data length */
#define MAXWAIT 10 /* max seconds to wait for response */