toybox/toys/net/ping.c
<<
>>
Prefs
   1/* ping.c - check network connectivity
   2 *
   3 * Copyright 2014 Rob Landley <rob@landley.net>
   4 *
   5 * Not in SUSv4.
   6 *
   7 * Note: ping_group_range should never have existed. To disable it, do:
   8 *   echo 0 $(((1<<31)-1)) > /proc/sys/net/ipv4/ping_group_range
   9 * (Android does this by default in its init script.)
  10 *
  11 * Yes, I wimped out and capped -s at sizeof(toybuf), waiting for a complaint...
  12
  13// -s > 4088 = sizeof(toybuf)-sizeof(struct icmphdr), then kernel adds 20 bytes
  14USE_PING(NEWTOY(ping, "<1>1m#t#<0>255=64c#<0=3s#<0>4088=56I:i%W#<0=3w#<0qf46[-46]", TOYFLAG_USR|TOYFLAG_BIN))
  15USE_PING(OLDTOY(ping6, ping, TOYFLAG_USR|TOYFLAG_BIN))
  16 
  17config PING
  18  bool "ping"
  19  default y
  20  help
  21    usage: ping [OPTIONS] HOST
  22
  23    Check network connectivity by sending packets to a host and reporting
  24    its response.
  25
  26    Send ICMP ECHO_REQUEST packets to ipv4 or ipv6 addresses and prints each
  27    echo it receives back, with round trip time. Returns true if host alive.
  28
  29    Options:
  30    -4, -6              Force IPv4 or IPv6
  31    -c CNT              Send CNT many packets (default 3, 0 = infinite)
  32    -f          Flood (print . and \b to show drops, default -c 15 -i 0.2)
  33    -i TIME             Interval between packets (default 1, need root for < .2)
  34    -I IFACE/IP Source interface or address
  35    -m MARK             Tag outgoing packets using SO_MARK
  36    -q          Quiet (stops after one returns true if host is alive)
  37    -s SIZE             Data SIZE in bytes (default 56)
  38    -t TTL              Set Time To Live (number of hops)
  39    -W SEC              Seconds to wait for response after last -c packet (default 3)
  40    -w SEC              Exit after this many seconds
  41*/
  42
  43#define FOR_ping 
  44#include "toys.h"
  45
  46#include <ifaddrs.h>
  47#include <netinet/ip_icmp.h>
  48
  49GLOBALS(
  50  long w, W, i;
  51  char *I;
  52  long s, c, t, m;
  53
  54  struct sockaddr *sa;
  55  int sock;
  56  unsigned long sent, recv, fugit, min, max;
  57)
  58
  59static void xsendto(int sockfd, void *buf, size_t len, struct sockaddr *dest)
  60{
  61  int rc = sendto(TT.sock, buf, len, 0, dest,
  62    dest->sa_family == AF_INET ? sizeof(struct sockaddr_in) :
  63      sizeof(struct sockaddr_in6));
  64
  65  if (rc != len) perror_exit("sendto");
  66}
  67
  68static void summary(int sig)
  69{
  70  if (!(toys.optflags&FLAG_q) && TT.sent && TT.sa) {
  71    printf("\n--- %s ping statistics ---\n", ntop(TT.sa));
  72    printf("%lu packets transmitted, %lu received, %ld%% packet loss\n",
  73      TT.sent, TT.recv, ((TT.sent-TT.recv)*100)/(TT.sent?TT.sent:1));
  74    printf("round-trip min/avg/max = %lu/%lu/%lu ms\n",
  75      TT.min, TT.max, TT.fugit/(TT.recv?TT.recv:1));
  76  }
  77  TT.sa = 0;
  78}
  79
  80// assumes aligned and can read even number of bytes
  81static unsigned short pingchksum(unsigned short *data, int len)
  82{
  83  unsigned short u = 0, d;
  84
  85  // circular carry is endian independent: bits from high byte go to low byte
  86  while (len>0) {
  87    d = *data++;
  88    if (len == 1) d &= 255<<IS_BIG_ENDIAN;
  89    if (d >= (u += d)) u++;
  90    len -= 2;
  91  }
  92
  93  return u;
  94}
  95
  96void ping_main(void)
  97{
  98  struct addrinfo *ai, *ai2;
  99  struct ifaddrs *ifa, *ifa2 = 0;
 100  union {
 101    struct sockaddr_in in;
 102    struct sockaddr_in6 in6;
 103  } src_addr, src_addr2;
 104  struct sockaddr *sa = (void *)&src_addr, *sa2 = (void *)&src_addr2;
 105  struct pollfd pfd;
 106  int family = 0, len;
 107  long long tnext, tW, tnow, tw;
 108  unsigned short seq = 0, pkttime;
 109  struct icmphdr *ih = (void *)toybuf;
 110
 111  // Interval
 112  if (!(toys.optflags&FLAG_i)) TT.i = (toys.optflags&FLAG_f) ? 200 : 1000;
 113  else if (TT.i<200 && getuid()) error_exit("need root for -i <200");
 114  if (!(toys.optflags&FLAG_s)) TT.s = 56; // 64-PHDR_LEN
 115  if ((toys.optflags&(FLAG_f|FLAG_c)) == FLAG_f) TT.c = 15;
 116
 117  // ipv4 or ipv6? (0 = autodetect if -I or arg have only one address type.)
 118  if ((toys.optflags&FLAG_6) || toys.which->name[4] == '6') family = AF_INET6;
 119  else if (toys.optflags&FLAG_4) family = AF_INET;
 120  else family = 0;
 121
 122  sigatexit(summary);
 123
 124  // If -I src_addr look it up. Allow numeric address of correct type.
 125  memset(&src_addr, 0, sizeof(src_addr));
 126  if (TT.I) {
 127    if (!(toys.optflags&FLAG_6) && inet_pton(AF_INET, TT.I,
 128      (void *)&src_addr.in.sin_addr))
 129        family = AF_INET;
 130    else if (!(toys.optflags&FLAG_4) && inet_pton(AF_INET6, TT.I,
 131      (void *)&src_addr.in6.sin6_addr))
 132        family = AF_INET6;
 133    else if (getifaddrs(&ifa2)) perror_exit("getifaddrs");
 134  }
 135
 136  // Look up HOST address, filtering for correct type and interface.
 137  // If -I but no -46 then find compatible type between -I and HOST
 138  ai2 = xgetaddrinfo(*toys.optargs, 0, family, 0, 0, 0);
 139  for (ai = ai2; ai; ai = ai->ai_next) {
 140
 141    // correct type?
 142    if (family && family!=ai->ai_family) continue;
 143    if (ai->ai_family!=AF_INET && ai->ai_family!=AF_INET6) continue;
 144
 145    // correct interface?
 146    if (!TT.I || !ifa2) break;
 147    for (ifa = ifa2; ifa; ifa = ifa->ifa_next) {
 148      if (!ifa->ifa_addr || ifa->ifa_addr->sa_family!=ai->ai_family
 149          || strcmp(ifa->ifa_name, TT.I)) continue;
 150      sa = (void *)ifa->ifa_addr;
 151
 152      break;
 153    }
 154    if (ifa) break;
 155  }
 156
 157  if (!ai)
 158    error_exit("no v%d addr for -I %s", 4+2*(family==AF_INET6), TT.I);
 159  TT.sa = ai->ai_addr;
 160
 161  // Open DGRAM socket
 162  sa->sa_family = ai->ai_family;
 163  TT.sock = socket(ai->ai_family, SOCK_DGRAM,
 164    len = (ai->ai_family == AF_INET) ? IPPROTO_ICMP : IPPROTO_ICMPV6);
 165  if (TT.sock == -1) {
 166    perror_msg("socket SOCK_DGRAM %x", len);
 167    if (errno == EACCES) {
 168      fprintf(stderr, "Kernel bug workaround (as root):\n");
 169      fprintf(stderr, "echo 0 9999999 > /proc/sys/net/ipv4/ping_group_range\n");
 170    }
 171    xexit();
 172  }
 173  if (TT.I && bind(TT.sock, sa, sizeof(src_addr))) perror_exit("bind");
 174
 175  if (toys.optflags&FLAG_m) {
 176      int mark = TT.m;
 177
 178      xsetsockopt(TT.sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
 179  }
 180
 181  if (TT.t) {
 182    len = TT.t;
 183
 184    if (ai->ai_family == AF_INET)
 185      xsetsockopt(TT.sock, IPPROTO_IP, IP_TTL, &len, 4);
 186    else xsetsockopt(TT.sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &len, 4);
 187  }
 188
 189  if (!(toys.optflags&FLAG_q)) {
 190    printf("Ping %s (%s)", *toys.optargs, ntop(TT.sa));
 191    if (TT.I) {
 192      *toybuf = 0;
 193      printf(" from %s (%s)", TT.I, ntop(sa));
 194    }
 195    // 20 byte TCP header, 8 byte ICMP header, plus data payload
 196    printf(": %ld(%ld) bytes.\n", TT.s, TT.s+28);
 197  }
 198  toys.exitval = 1;
 199
 200  tW = tw = 0;
 201  tnext = millitime();
 202  if (TT.w) tw = TT.w*1000+tnext;
 203
 204  // Send/receive packets
 205  for (;;) {
 206    int waitms = INT_MAX;
 207
 208    // Exit due to timeout? (TODO: timeout is after last packet, waiting if
 209    // any packets ever dropped. Not timeout since packet was dropped.)
 210    tnow = millitime();
 211    if (tW) {
 212      if (0>=(waitms = tW-tnow) || !(TT.sent-TT.recv)) break;
 213      waitms = tW-tnow;
 214    }
 215    if (tw) {
 216      if (tnow>tw) break;
 217      else if (waitms>tw-tnow) waitms = tw-tnow;
 218    }
 219
 220    // Time to send the next packet?
 221    if (!tW && tnext-tnow <= 0) {
 222      tnext += TT.i;
 223
 224      memset(ih, 0, sizeof(*ih));
 225      ih->type = (ai->ai_family == AF_INET) ? 8 : 128;
 226      ih->un.echo.id = getpid();
 227      ih->un.echo.sequence = ++seq;
 228      if (TT.s >= 4) *(unsigned *)(ih+1) = tnow;
 229
 230      ih->checksum = 0;
 231      ih->checksum = pingchksum((void *)toybuf, TT.s+sizeof(*ih));
 232      xsendto(TT.sock, toybuf, TT.s+sizeof(*ih), TT.sa);
 233      TT.sent++;
 234      if ((toys.optflags&(FLAG_f|FLAG_q)) == FLAG_f) xputc('.');
 235
 236      // last packet?
 237      if (TT.c) if (!--TT.c) {
 238        tW = tnow + TT.W*1000;
 239        waitms = 1; // check for immediate return even when W=0
 240      }
 241    }
 242
 243    // This is down here so it's against new period if we just sent a packet
 244    if (!tW && waitms>tnext-tnow) waitms = tnext-tnow;
 245
 246    // wait for next packet or timeout
 247
 248    if (waitms<0) waitms = 0;
 249    pfd.fd = TT.sock;
 250    pfd.events = POLLIN;
 251    if (0>(len = poll(&pfd, 1, waitms))) break;
 252    if (!len) continue;
 253
 254    len = sizeof(src_addr2);
 255    len = recvfrom(TT.sock, toybuf, sizeof(toybuf), 0, sa2, (void *)&len);
 256    TT.recv++;
 257    TT.fugit += (pkttime = millitime()-*(unsigned *)(ih+1));
 258
 259    // reply id == 0 for ipv4, 129 for ipv6
 260
 261    if (!(toys.optflags&FLAG_q)) {
 262      if (toys.optflags&FLAG_f) xputc('\b');
 263      else {
 264        printf("%d bytes from %s: icmp_seq=%d ttl=%d", len, ntop(sa2),
 265               ih->un.echo.sequence, 0);
 266        if (len >= sizeof(*ih)+4)
 267          printf(" time=%u ms", pkttime);
 268        xputc('\n');
 269      }
 270    }
 271
 272    toys.exitval = 0;
 273  }
 274
 275  sigatexit(0);
 276  summary(0);
 277
 278  if (CFG_TOYBOX_FREE) {
 279    freeaddrinfo(ai2);
 280    if (ifa2) freeifaddrs(ifa2);
 281  }
 282}
 283