busybox/networking/arping.c
<<
>>
Prefs
   1/* vi: set sw=4 ts=4: */
   2/*
   3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
   4 *
   5 * Author: Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
   6 * Busybox port: Nick Fedchik <nick@fedchik.org.ua>
   7 */
   8//config:config ARPING
   9//config:       bool "arping (9 kb)"
  10//config:       default y
  11//config:       help
  12//config:       Ping hosts by ARP packets.
  13
  14//applet:IF_ARPING(APPLET(arping, BB_DIR_USR_SBIN, BB_SUID_DROP))
  15
  16//kbuild:lib-$(CONFIG_ARPING) += arping.o
  17
  18//usage:#define arping_trivial_usage
  19//usage:       "[-fqbDUA] [-c CNT] [-w TIMEOUT] [-I IFACE] [-s SRC_IP] DST_IP"
  20//usage:#define arping_full_usage "\n\n"
  21//usage:       "Send ARP requests/replies\n"
  22//usage:     "\n        -f              Quit on first ARP reply"
  23//usage:     "\n        -q              Quiet"
  24//usage:     "\n        -b              Keep broadcasting, don't go unicast"
  25//usage:     "\n        -D              Exit with 1 if DST_IP replies"
  26//usage:     "\n        -U              Unsolicited ARP mode, update your neighbors"
  27//usage:     "\n        -A              ARP answer mode, update your neighbors"
  28//usage:     "\n        -c N            Stop after sending N ARP requests"
  29//usage:     "\n        -w TIMEOUT      Seconds to wait for ARP reply"
  30//NB: in iputils-s20160308, iface is mandatory, no default
  31//usage:     "\n        -I IFACE        Interface to use (default eth0)"
  32//usage:     "\n        -s SRC_IP       Sender IP address"
  33//usage:     "\n        DST_IP          Target IP address"
  34
  35#include <arpa/inet.h>
  36#include <net/if.h>
  37#include <netinet/ether.h>
  38#include <netpacket/packet.h>
  39
  40#include "libbb.h"
  41#include "common_bufsiz.h"
  42
  43/* We don't expect to see 1000+ seconds delay, unsigned is enough */
  44#define MONOTONIC_US() ((unsigned)monotonic_us())
  45
  46enum {
  47        UNSOLICITED   = 1 << 0,
  48        DAD           = 1 << 1,
  49        ADVERT        = 1 << 2,
  50        QUIET         = 1 << 3,
  51        QUIT_ON_REPLY = 1 << 4,
  52        BCAST_ONLY    = 1 << 5,
  53        UNICASTING    = 1 << 6,
  54        TIMEOUT       = 1 << 7,
  55};
  56#define GETOPT32(str_timeout, device, source) \
  57        getopt32(argv, "^" \
  58                "UDAqfbc:+w:I:s:" \
  59                /* DAD also sets quit_on_reply, */ \
  60                /* advert also sets unsolicited: */ \
  61                "\0" "=1:Df:AU", \
  62                &count, &str_timeout, &device, &source \
  63        );
  64
  65struct globals {
  66        struct in_addr src;
  67        struct in_addr dst;
  68        struct sockaddr_ll me;
  69        struct sockaddr_ll he;
  70
  71        int count; // = -1;
  72        unsigned last;
  73        unsigned timeout_us;
  74        unsigned start;
  75
  76        unsigned sent;
  77        unsigned brd_sent;
  78        unsigned received;
  79        unsigned brd_recv;
  80        unsigned req_recv;
  81
  82        /* should be in main(), but are here to reduce stack use: */
  83        struct ifreq ifr;
  84        struct sockaddr_in probe_saddr;
  85        sigset_t sset;
  86        unsigned char packet[4096];
  87} FIX_ALIASING;
  88#define src        (G.src       )
  89#define dst        (G.dst       )
  90#define me         (G.me        )
  91#define he         (G.he        )
  92#define count      (G.count     )
  93#define last       (G.last      )
  94#define timeout_us (G.timeout_us)
  95#define start      (G.start     )
  96#define sent       (G.sent      )
  97#define brd_sent   (G.brd_sent  )
  98#define received   (G.received  )
  99#define brd_recv   (G.brd_recv  )
 100#define req_recv   (G.req_recv  )
 101//#define G (*(struct globals*)bb_common_bufsiz1)
 102#define G (*ptr_to_globals)
 103#define INIT_G() do { \
 104        /*setup_common_bufsiz();*/ \
 105        SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
 106        count = -1; \
 107} while (0)
 108
 109#define sock_fd 3
 110
 111static int send_pack(struct in_addr *src_addr,
 112                        struct in_addr *dst_addr,
 113                        struct sockaddr_ll *ME,
 114                        struct sockaddr_ll *HE)
 115{
 116        int err;
 117        unsigned char buf[256];
 118        struct arphdr *ah = (struct arphdr *) buf;
 119        unsigned char *p;
 120
 121        ah->ar_hrd = htons(ARPHRD_ETHER);
 122        ah->ar_pro = htons(ETH_P_IP);
 123        ah->ar_hln = ME->sll_halen;
 124        ah->ar_pln = 4;
 125        ah->ar_op = option_mask32 & ADVERT ? htons(ARPOP_REPLY) : htons(ARPOP_REQUEST);
 126
 127        p = (unsigned char *) (ah + 1);
 128        p = mempcpy(p, &ME->sll_addr, ah->ar_hln);
 129        p = mempcpy(p, src_addr, 4);
 130
 131        if (option_mask32 & ADVERT)
 132                p = mempcpy(p, &ME->sll_addr, ah->ar_hln);
 133        else
 134                p = mempcpy(p, &HE->sll_addr, ah->ar_hln);
 135
 136        p = mempcpy(p, dst_addr, 4);
 137
 138        err = sendto(sock_fd, buf, p - buf, 0, (struct sockaddr *) HE, sizeof(*HE));
 139        if (err == p - buf) {
 140                last = MONOTONIC_US();
 141                sent++;
 142                if (!(option_mask32 & UNICASTING))
 143                        brd_sent++;
 144        }
 145        return err;
 146}
 147
 148static void finish(void) NORETURN;
 149static void finish(void)
 150{
 151        if (!(option_mask32 & QUIET)) {
 152                printf("Sent %u probe(s) (%u broadcast(s))\n"
 153                        "Received %u response(s)"
 154                        " (%u request(s), %u broadcast(s))\n",
 155                        sent, brd_sent,
 156                        received,
 157                        req_recv, brd_recv);
 158        }
 159        if (option_mask32 & DAD)
 160                exit(!!received);
 161        if (option_mask32 & UNSOLICITED)
 162                exit(EXIT_SUCCESS);
 163        exit(!received);
 164}
 165
 166static void catcher(void)
 167{
 168        unsigned now;
 169
 170        now = MONOTONIC_US();
 171        if (start == 0)
 172                start = now;
 173
 174        if (count == 0 || (timeout_us && (now - start) > timeout_us))
 175                finish();
 176
 177        /* count < 0 means "infinite count" */
 178        if (count > 0)
 179                count--;
 180
 181        if (last == 0 || (now - last) > 500000) {
 182                send_pack(&src, &dst, &me, &he);
 183                if (count == 0 && (option_mask32 & UNSOLICITED))
 184                        finish();
 185        }
 186        alarm(1);
 187}
 188
 189static void recv_pack(unsigned char *buf, int len, struct sockaddr_ll *FROM)
 190{
 191        struct arphdr *ah = (struct arphdr *) buf;
 192        unsigned char *p = (unsigned char *) (ah + 1);
 193        struct in_addr src_ip, dst_ip;
 194
 195        /* moves below assume in_addr is 4 bytes big, ensure that */
 196        BUILD_BUG_ON(sizeof(struct in_addr) != 4);
 197        BUILD_BUG_ON(sizeof(src_ip.s_addr) != 4);
 198
 199        /* Filter out wild packets */
 200        if (FROM->sll_pkttype != PACKET_HOST
 201         && FROM->sll_pkttype != PACKET_BROADCAST
 202         && FROM->sll_pkttype != PACKET_MULTICAST)
 203                return;
 204
 205        /* Only these types are recognized */
 206        if (ah->ar_op != htons(ARPOP_REQUEST) && ah->ar_op != htons(ARPOP_REPLY))
 207                return;
 208
 209        /* ARPHRD check and this darned FDDI hack here :-( */
 210        if (ah->ar_hrd != htons(FROM->sll_hatype)
 211         && (FROM->sll_hatype != ARPHRD_FDDI || ah->ar_hrd != htons(ARPHRD_ETHER)))
 212                return;
 213
 214        /* Protocol must be IP. */
 215        if (ah->ar_pro != htons(ETH_P_IP)
 216         || (ah->ar_pln != 4)
 217         || (ah->ar_hln != me.sll_halen)
 218         || (len < (int)(sizeof(*ah) + 2 * (4 + ah->ar_hln)))
 219        ) {
 220                return;
 221        }
 222
 223        move_from_unaligned32(src_ip.s_addr, p + ah->ar_hln);
 224        move_from_unaligned32(dst_ip.s_addr, p + ah->ar_hln + 4 + ah->ar_hln);
 225
 226        if (dst.s_addr != src_ip.s_addr)
 227                return;
 228        if (!(option_mask32 & DAD)) {
 229                if ((src.s_addr != dst_ip.s_addr)
 230                 || (memcmp(p + ah->ar_hln + 4, &me.sll_addr, ah->ar_hln)))
 231                        return;
 232        } else {
 233                /* DAD packet was:
 234                   src_ip = 0 (or some src)
 235                   src_hw = ME
 236                   dst_ip = tested address
 237                   dst_hw = <unspec>
 238
 239                   We fail, if receive request/reply with:
 240                   src_ip = tested_address
 241                   src_hw != ME
 242                   if src_ip in request was not zero, check
 243                   also that it matches to dst_ip, otherwise
 244                   dst_ip/dst_hw do not matter.
 245                 */
 246                if ((memcmp(p, &me.sll_addr, me.sll_halen) == 0)
 247                 || (src.s_addr && src.s_addr != dst_ip.s_addr))
 248                        return;
 249        }
 250        if (!(option_mask32 & QUIET)) {
 251                int s_printed = 0;
 252
 253//TODO: arping from iputils-s20160308 print upprcase hex in MAC, follow them?
 254                printf("%scast re%s from %s [%02x:%02x:%02x:%02x:%02x:%02x]",
 255                        FROM->sll_pkttype == PACKET_HOST ? "Uni" : "Broad",
 256                        ah->ar_op == htons(ARPOP_REPLY) ? "ply" : "quest",
 257                        inet_ntoa(src_ip),
 258                        p[0], p[1], p[2], p[3], p[4], p[5]
 259                );
 260                if (dst_ip.s_addr != src.s_addr) {
 261                        printf("for %s", inet_ntoa(dst_ip));
 262                        s_printed = 1;
 263                }
 264                if (memcmp(p + ah->ar_hln + 4, me.sll_addr, ah->ar_hln)) {
 265                        unsigned char *pp = p + ah->ar_hln + 4;
 266                        if (!s_printed)
 267                                printf(" for");
 268                        printf(" [%02x:%02x:%02x:%02x:%02x:%02x]",
 269                                pp[0], pp[1], pp[2], pp[3], pp[4], pp[5]
 270                        );
 271                }
 272
 273                if (last) {
 274                        unsigned diff = MONOTONIC_US() - last;
 275                        printf(" %u.%03ums\n", diff / 1000, diff % 1000);
 276                } else {
 277                        puts(" UNSOLICITED?");
 278                }
 279                fflush_all();
 280        }
 281        received++;
 282        if (FROM->sll_pkttype != PACKET_HOST)
 283                brd_recv++;
 284        if (ah->ar_op == htons(ARPOP_REQUEST))
 285                req_recv++;
 286        if (option_mask32 & QUIT_ON_REPLY)
 287                finish();
 288        if (!(option_mask32 & BCAST_ONLY)) {
 289                memcpy(he.sll_addr, p, me.sll_halen);
 290                option_mask32 |= UNICASTING;
 291        }
 292}
 293
 294int arping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
 295int arping_main(int argc UNUSED_PARAM, char **argv)
 296{
 297        const char *device = "eth0";
 298        char *source = NULL;
 299        char *target;
 300        char *err_str;
 301
 302        INIT_G();
 303
 304        xmove_fd(xsocket(AF_PACKET, SOCK_DGRAM, 0), sock_fd);
 305
 306        // If you ever change BB_SUID_DROP to BB_SUID_REQUIRE,
 307        // drop suid root privileges here:
 308        //xsetuid(getuid());
 309
 310        {
 311                unsigned opt;
 312                char *str_timeout;
 313
 314                opt = GETOPT32(str_timeout, device, source);
 315                if (opt & TIMEOUT)
 316                        timeout_us = xatou_range(str_timeout, 0, INT_MAX/2000000) * 1000000 + 500000;
 317        }
 318
 319        target = argv[optind];
 320        err_str = xasprintf("interface %s %%s", device);
 321        xfunc_error_retval = 2;
 322
 323        /*memset(&G.ifr, 0, sizeof(G.ifr)); - zeroed by INIT_G */
 324        strncpy_IFNAMSIZ(G.ifr.ifr_name, device);
 325        ioctl_or_perror_and_die(sock_fd, SIOCGIFINDEX, &G.ifr, err_str, "not found");
 326        me.sll_ifindex = G.ifr.ifr_ifindex;
 327
 328        xioctl(sock_fd, SIOCGIFFLAGS, (char *) &G.ifr);
 329
 330        if (!(G.ifr.ifr_flags & IFF_UP)) {
 331                bb_error_msg_and_die(err_str, "is down");
 332        }
 333        if (G.ifr.ifr_flags & (IFF_NOARP | IFF_LOOPBACK)) {
 334                bb_error_msg(err_str, "is not ARPable");
 335                BUILD_BUG_ON(DAD != 2);
 336                /* exit 0 if DAD, else exit 2 */
 337                return (~option_mask32 & DAD);
 338        }
 339
 340        /* if (!inet_aton(target, &dst)) - not needed */ {
 341                len_and_sockaddr *lsa;
 342                lsa = xhost_and_af2sockaddr(target, 0, AF_INET);
 343                dst = lsa->u.sin.sin_addr;
 344                if (ENABLE_FEATURE_CLEAN_UP)
 345                        free(lsa);
 346        }
 347
 348        if (source && !inet_aton(source, &src)) {
 349                bb_error_msg_and_die("invalid source address %s", source);
 350        }
 351
 352        if ((option_mask32 & (DAD|UNSOLICITED)) == UNSOLICITED && src.s_addr == 0)
 353                src = dst;
 354
 355        if (!(option_mask32 & DAD) || src.s_addr) {
 356                /*struct sockaddr_in probe_saddr;*/
 357                int probe_fd = xsocket(AF_INET, SOCK_DGRAM, 0);
 358
 359                setsockopt_bindtodevice(probe_fd, device);
 360
 361                /*memset(&G.probe_saddr, 0, sizeof(G.probe_saddr)); - zeroed by INIT_G */
 362                G.probe_saddr.sin_family = AF_INET;
 363                if (src.s_addr) {
 364                        /* Check that this is indeed our IP */
 365                        G.probe_saddr.sin_addr = src;
 366                        xbind(probe_fd, (struct sockaddr *) &G.probe_saddr, sizeof(G.probe_saddr));
 367                } else { /* !(option_mask32 & DAD) case */
 368                        /* Find IP address on this iface */
 369                        G.probe_saddr.sin_port = htons(1025);
 370                        G.probe_saddr.sin_addr = dst;
 371
 372                        if (setsockopt_SOL_SOCKET_1(probe_fd, SO_DONTROUTE) != 0)
 373                                bb_perror_msg("setsockopt(%s)", "SO_DONTROUTE");
 374                        xconnect(probe_fd, (struct sockaddr *) &G.probe_saddr, sizeof(G.probe_saddr));
 375                        bb_getsockname(probe_fd, (struct sockaddr *) &G.probe_saddr, sizeof(G.probe_saddr));
 376                        if (G.probe_saddr.sin_family != AF_INET)
 377                                bb_simple_error_msg_and_die("no IP address configured");
 378                        src = G.probe_saddr.sin_addr;
 379                }
 380                close(probe_fd);
 381        }
 382
 383        me.sll_family = AF_PACKET;
 384        //me.sll_ifindex = ifindex; - done before
 385        me.sll_protocol = htons(ETH_P_ARP);
 386        xbind(sock_fd, (struct sockaddr *) &me, sizeof(me));
 387
 388        bb_getsockname(sock_fd, (struct sockaddr *) &me, sizeof(me));
 389        //never happens:
 390        //if (getsockname(sock_fd, (struct sockaddr *) &me, &alen) == -1)
 391        //      bb_perror_msg_and_die("getsockname");
 392        if (me.sll_halen == 0) {
 393                bb_error_msg(err_str, "is not ARPable (no ll address)");
 394                BUILD_BUG_ON(DAD != 2);
 395                /* exit 0 if DAD, else exit 2 */
 396                return (~option_mask32 & DAD);
 397        }
 398        he = me;
 399        memset(he.sll_addr, -1, he.sll_halen);
 400
 401        if (!(option_mask32 & QUIET)) {
 402                /* inet_ntoa uses static storage, can't use in same printf */
 403                printf("ARPING %s", inet_ntoa(dst));
 404                printf(" from %s %s\n", inet_ntoa(src), device);
 405        }
 406
 407        /*sigemptyset(&G.sset); - zeroed by INIT_G */
 408        sigaddset(&G.sset, SIGALRM);
 409        sigaddset(&G.sset, SIGINT);
 410        signal_SA_RESTART_empty_mask(SIGINT,  (void (*)(int))finish);
 411        signal_SA_RESTART_empty_mask(SIGALRM, (void (*)(int))catcher);
 412
 413        /* Send the first packet, arm ALRM */
 414        catcher();
 415
 416        while (1) {
 417                struct sockaddr_ll from;
 418                socklen_t alen = sizeof(from);
 419                int cc;
 420
 421                /* Unblock SIGALRM so that the previously called alarm()
 422                 * can prevent recvfrom from blocking forever in case the
 423                 * inherited procmask is blocking SIGALRM.
 424                 */
 425                sigprocmask(SIG_UNBLOCK, &G.sset, NULL);
 426
 427                cc = recvfrom(sock_fd, G.packet, sizeof(G.packet), 0, (struct sockaddr *) &from, &alen);
 428
 429                /* Don't allow SIGALRMs while we process the reply */
 430                sigprocmask(SIG_BLOCK, &G.sset, NULL);
 431                if (cc < 0) {
 432                        bb_simple_perror_msg("recvfrom");
 433                        continue;
 434                }
 435                recv_pack(G.packet, cc, &from);
 436        }
 437}
 438