Debian Codegraph @

src/arping.c

raw symbols SCIP
1 /** arping/src/arping.c
2 *
3 * arping
4 *
5 * By Thomas Habets <[email protected]>
6 *
7 * ARP 'ping' utility
8 *
9 * Broadcasts a who-has ARP packet on the network and prints answers.
10 * *VERY* useful when you are trying to pick an unused IP for a net that
11 * you don't yet have routing to. Then again, if you have no idea what I'm
12 * talking about then you prolly don't need it.
13 *
14 * Also finds out IP of specified MAC.
15 *
16 */
17 /*
18 * Copyright (C) 2000-2024 Thomas Habets <[email protected]>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License along
31 * with this program; if not, write to the Free Software Foundation, Inc.,
32 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
33 */
34 #define _GNU_SOURCE
35 #if HAVE_CONFIG_H
36 #include "config.h"
37 #endif
38
39 #include <assert.h>
40 #include <errno.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <limits.h>
45 #include <math.h>
46 #include <poll.h>
47
48 #if HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51
52 #if HAVE_GETOPT_H
53 #include <getopt.h>
54 #endif
55
56 #if HAVE_STDINT_H
57 #include <stdint.h>
58 #endif
59
60 #if HAVE_INTTYPES_H
61 #include <inttypes.h>
62 #endif
63
64 #if HAVE_TIME_H
65 #include <time.h>
66 #endif
67
68 #if HAVE_SYS_TIME_H
69 #include <sys/time.h>
70 #endif
71
72 #if HAVE_SYS_TYPES_H
73 #include <sys/types.h>
74 #endif
75
76 #if HAVE_SYS_PARAM_H
77 #include <sys/param.h>
78 #endif
79
80 #if HAVE_SYS_RANDOM_H
81 #include <sys/random.h>
82 #endif
83
84 #if HAVE_GRP_H
85 #include <grp.h>
86 #endif
87
88 #if HAVE_SYS_SOCKET_H
89 #include <sys/socket.h>
90 #endif
91
92 #if HAVE_NETINET_IN_H
93 #include <netinet/in.h>
94 #endif
95
96 #if HAVE_ARPA_INET_H
97 #include <arpa/inet.h>
98 #endif
99
100 #if HAVE_LIBNET_H
101 #include <libnet.h>
102 #endif
103
104 #if HAVE_WIN32_LIBNET_H
105 #include <win32/libnet.h>
106 #endif
107
108 #if HAVE_PWD_H
109 #include <pwd.h>
110 #endif
111
112 #if HAVE_SYS_CAPABILITY_H
113 #include <sys/capability.h>
114 #else
115 // It seems that some environments have a libc with cap_init, but do not have
116 // the header files. Without the header files we won't have the cap_t struct, so
117 // it won't actually work.
118 //
119 // TODO: Probably this logic should be in configure.ac instead.
120 #undef HAVE_CAP_INIT
121 #endif
122
123 #if HAVE_NET_BPF_H
124 #include <net/bpf.h>
125 #endif
126 #include <pcap.h>
127
128 #include "arping.h"
129 #include "cast.h"
130
131 #ifndef ETH_ALEN
132 #define ETH_ALEN 6
133 #endif
134
135 #ifndef IP_ALEN
136 #define IP_ALEN 4
137 #endif
138
139 #ifndef WIN32
140 #define WIN32 0
141 #endif
142
143 #ifndef CLOCK_MONOTONIC
144 #define CLOCK_MONOTONIC CLOCK_REALTIME
145 #endif
146
147 #define UNUSED(x) (void)(x)
148
149 #ifndef PCAP_NETMASK_UNKNOWN
150 #define PCAP_NETMASK_UNKNOWN 0xffffffff
151 #endif
152
153 /**
154 * OS-specific interface finding using routing table. See findif_*.c
155 * ebuf must be called with a size of at least
156 * max(LIBNET_ERRBUF_SIZE, PCAP_ERRBUF_SIZE).
157 */
158 const char *
159 arping_lookupdev(uint32_t srcip, uint32_t dstip, char *ebuf);
160
161 const char *
162 arping_lookupdev_default(uint32_t srcip, uint32_t dstip, char *ebuf);
163
164 static const char *version = VERSION; /* from autoconf */
165
166 libnet_t *libnet = 0;
167
168 /*
169 * Exit if dropping privs fails. Intentionally disabled for now.
170 */
171 static const int exit_on_drop_fail = 0;
172
173 /* Timestamp of last packet sent.
174 * Used for timing, and assumes that reply is due to most recent sent query.
175 */
176 static struct timespec lastpacketsent;
177
178 /* target string */
179 static const char *target = "huh? bug in arping?";
180
181 /*
182 * Ping IP mode: cmdline target
183 * Ping MAC mode: 255.255.255.255, override with -T
184 */
185 uint32_t dstip;
186
187 /*
188 * Ping IP mode: ethxmas, override with -t
189 * Ping MAC mode: cmdline target
190 */
191 static uint8_t dstmac[ETH_ALEN];
192
193 /* For ping MAC mode, use some extra ICMP echo payload data to confirm it's our
194 * ping.
195 */
196 char* payload_suffix = NULL;
197 const size_t payload_suffix_size = 4;
198
199 // Must be at least big enough to capture an entire packet.
200 // Longest possible:
201 // MAC: 802.1q(16) + IPv4(20) + ICMPv4(4) + timespec(18?) + 4 = 62.
202 // IP: 802.1q(16) + ARP(8) + 2xaddr_pair = 44.
203 // 100 is enough.
204 static const int pcap_snaplen = 100;
205 static const int pcap_timeout_ms = 10;
206
207 /* If there were any libnet write failures, we return error. */
208 static size_t libnet_write_failures = 0;
209
210 uint32_t srcip; /* autodetected, override with -S/-b/-0 */
211 uint8_t srcmac[ETH_ALEN]; /* autodetected, override with -s */
212
213 static int16_t vlan_tag = -1; /* 802.1Q tag to add to packets. -V */
214 static int16_t vlan_prio = -1; /* 802.1p prio to use with 802.1Q. -Q */
215
216 static int beep = 0; /* beep when reply is received. -a */
217 static int reverse_beep = 0; /* beep when expected reply absent. -e */
218 static int alsototal = 0; /* print sent as well as received. -u */
219 static int addr_must_be_same = 0; /* -A */
220 static int unsolicited = 0; /* -U */
221 static int send_reply = 0; /* Send reply instead of request. -P */
222 static int promisc = 0; /* Use promisc mode. -p */
223
224 static int finddup = 0; /* finddup mode. -d */
225 static int dupfound = 0; /* set to 1 if dup found */
226 static char lastreplymac[ETH_ALEN]; /* if last different from this then dup */
227
228 /* -z to turn on, -Z to turn off. Default is compile time option */
229 static int use_seccomp = DEFAULT_SECCOMP;
230
231 unsigned int numsent = 0; /* packets sent */
232 unsigned int numrecvd = 0; /* packets received */
233 static unsigned int max_replies = UINT_MAX; /* exit after -C replies */
234 static const char* timestamp_type = NULL; /* Incoming packet measurement ts type (-m) */
235
236 static double stats_min_time = -1;
237 static double stats_max_time = -1;
238 static double stats_total_time = 0;
239 static double stats_total_sq_time = 0;
240
241 /* RAWRAW is RAW|RRAW */
242 static enum { NORMAL, /* normal output */
243 QUIET, /* No output. -q */
244 RAW, /* Print MAC when pinging IP. -r */
245 RRAW, /* Print IP when pinging IP. -R */
246 RAWRAW, /* Print both. -r and -R */
247 DOT /* Print '.' and '!', Cisco-style. -D */
248 } display = NORMAL;
249
250 static const uint8_t ethnull[ETH_ALEN] = {0, 0, 0, 0, 0, 0};
251 static const uint8_t ethxmas[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
252 static const char* ip_broadcast = "255.255.255.255";
253 static const uint32_t ip_broadcast_num = (uint32_t)-1;
254
255 int verbose = 0; /* Increase with -v */
256
257 /* Doesn't really need to be volatile, but doesn't hurt. */
258 static volatile sig_atomic_t time_to_die = 0;
259
260 void drop_landlock();
261 void drop_no_new_privs();
262
263 void
264 xsnprintf(char *buf, size_t size, const char* fmt, ...)
265 {
266 va_list ap;
267 va_start(ap, fmt);
268
269 const int ret = vsnprintf(buf, size, fmt, ap);
270 if (ret < 0) {
271 fprintf(stderr, "arping: snprintf() returned negative: %d\n", ret);
272 exit(1);
273 }
274 if (cast_int_size(ret, "snprintf return %d not castable to size_t", ret) >= size) {
275 fprintf(stderr, "arping: snprintf() overflow: %d >= %zu\n", ret, size);
276 exit(1);
277 }
278
279 va_end(ap);
280 }
281
282 static float
283 must_parse_float(const char* in, const char* what)
284 {
285 if (!*in) {
286 fprintf(stderr, "arping: %s: value was empty\n", what);
287 exit(1);
288 }
289 char *endp = NULL;
290 errno = 0;
291 // Maybe need to use strtod() instead? It's in C89, whereas
292 // looks like strtof() is in POSIX.1-2001, POSIX.1-2008, C99.
293 const float ret = strtof(in, &endp);
294 if (errno) {
295 fprintf(stderr, "arping: %s: parsing <%s> as float: %s\n",
296 what, in, strerror(errno));
297 exit(1);
298 }
299 if (*endp) {
300 fprintf(stderr,
301 "arping: %s: failed parsing <%s> as float\n",
302 what, in);
303 exit(1);
304 }
305 return ret;
306 }
307
308 static int
309 must_parse_int(const char* in, const char* what)
310 {
311 if (!*in) {
312 fprintf(stderr, "arping: %s: value was empty\n", what);
313 exit(1);
314 }
315 char *endp = NULL;
316 errno = 0;
317 const long ret = strtol(in, &endp, 0);
318 if (errno) {
319 fprintf(stderr, "arping: %s: parsing <%s> as integer: %s\n",
320 what, in, strerror(errno));
321 exit(1);
322 }
323 if (*endp) {
324 fprintf(stderr,
325 "arping: %s: failed parsing <%s> as integer\n",
326 what, in);
327 exit(1);
328 }
329 return cast_long_int(ret, "%s %s", what, in);
330 }
331
332 static int16_t
333 must_parse_int16(const char* in, const char* what)
334 {
335 const int out = must_parse_int(in, what);
336 return cast_int_int16(out, "%s %s", what, in);
337 }
338
339 /*
340 * It's not actually possible to parse unsigned numbers in C.
341 * The best this function can do is parse as a long, then reject
342 * negative numbers. If sizeof(int) == sizeof(long) then that cuts
343 * off half of all possible values.
344 *
345 * More ranting here:
346 * https://blog.habets.se/2022/10/No-way-to-parse-integers-in-C.html
347 */
348 static unsigned int
349 must_parse_uint(const char* in, const char* what)
350 {
351 if (!*in) {
352 fprintf(stderr, "arping: %s: value was empty\n", what);
353 exit(1);
354 }
355 char *endp = NULL;
356 errno = 0;
357 #if HAVE_STRTOLL
358 #define CASTER cast_longlong_uint
359 const long long ret = strtoll(in, &endp, 0);
360 #else
361 #define CASTER cast_long_uint
362 const long ret = strtol(in, &endp, 0);
363 #endif
364 if (errno) {
365 fprintf(stderr, "arping: %s: parsing <%s> as integer: %s\n",
366 what, in, strerror(errno));
367 exit(1);
368 }
369 if (*endp) {
370 fprintf(stderr,
371 "arping: %s: failed parsing <%s> as integer\n",
372 what, in);
373 exit(1);
374 }
375 if (ret < 0) {
376 fprintf(stderr,
377 "arping: %s: <%s> is negative\n", what, in);
378 exit(1);
379 }
380 return CASTER(ret, "%s %s", what, in);
381 #undef CASTER
382 }
383
384 static unsigned long
385 parse_ulong(const char* in, const char* what, char* ebuf, size_t ebuflen)
386 {
387 if (!*in) {
388 xsnprintf(ebuf, ebuflen, "arping: %s: value was empty\n", what);
389 return 0;
390 }
391 char *endp = NULL;
392 errno = 0;
393 #if HAVE_STRTOLL
394 #define CASTER cast_longlong_ulonglong
395 const long long ret = strtoll(in, &endp, 0);
396 #else
397 #define CASTER cast_long_ulong
398 const long ret = strtol(in, &endp, 0);
399 #endif
400 if (errno) {
401 xsnprintf(ebuf, ebuflen, "arping: %s: parsing <%s> as integer: %s\n",
402 what, in, strerror(errno));
403 return 0;
404 }
405 if (*endp) {
406 xsnprintf(ebuf, ebuflen,
407 "arping: %s: failed parsing <%s> as integer\n",
408 what, in);
409 return 0;
410 }
411 if (ret < 0) {
412 xsnprintf(ebuf, ebuflen,
413 "arping: %s: <%s> is negative\n", what, in);
414 return 0;
415 }
416 return CASTER(ret, "%s %s", what, in);
417 #undef CASTER
418 }
419
420 static ssize_t
421 xgetrandom(void *buf, const size_t buflen, const unsigned int flags)
422 {
423 #ifdef ACTUALLY_HAS_GETRANDOM
424 return getrandom(buf, buflen, flags);
425 #else
426 UNUSED(flags);
427 uint8_t* p = buf;
428 for (size_t n = 0; n < buflen; n++) {
429 p[n] = cast_long_uint8(random() & 0xff, NULL);
430 }
431 return cast_size_ssize(buflen, NULL);
432 #endif
433 }
434
435 static uint16_t
436 xrandom16() {
437 const int maxtry = 10;
438 for (int c = 0; c < maxtry; c++) {
439 uint16_t ret;
440 const ssize_t rc = xgetrandom(&ret, sizeof(ret), 0);
441 if (rc == -1) {
442 fprintf(stderr, "arping: failed to get random bytes: %s\n", strerror(errno));
443 continue;
444 }
445 if (sizeof(ret) != rc) {
446 fprintf(stderr, "arping: got too few random bytes %zd, want %zu\n", rc, sizeof(ret));
447 continue;
448 }
449 return ret;
450 }
451 fprintf(stderr, "arping: failed to get random bytes after %d tries\n", maxtry);
452 exit(1);
453 }
454
455 /**
456 * If possible, chroot.
457 *
458 * The sshd user is used for privilege separation in OpenSSH.
459 * Let's assume it's installed and chroot() to there.
460 */
461 static void
462 drop_fs_root()
463 {
464 const char* chroot_user = "sshd";
465 struct passwd *pw;
466 errno = 0;
467 if (!(pw = getpwnam(chroot_user))) {
468 if (verbose > 1) {
469 printf("arping: getpwnam(%s): %s\n",
470 chroot_user, strerror(errno));
471 }
472 return;
473 }
474 if (chdir(pw->pw_dir)) {
475 if (verbose) {
476 printf("arping: chdir(%s): %s\n",
477 pw->pw_dir, strerror(errno));
478 }
479 return;
480 }
481 if (chroot(pw->pw_dir)) {
482 if (verbose) {
483 printf("arping: chroot(%s): %s\n",
484 pw->pw_dir, strerror(errno));
485 }
486 return;
487 }
488 if (chdir("/")) {
489 if (verbose) {
490 printf("arping: chdir(/): %s\n", strerror(errno));
491 }
492 return;
493 }
494 if (verbose > 1) {
495 printf("arping: Successfully chrooted to %s\n", pw->pw_dir);
496 }
497 }
498
499 /**
500 * If possible, drop uid to nobody.
501 *
502 * This code only successfully sets all [ug]ids if running as
503 * root. ARPing is most likely running as root unless using
504 * capabilities, and those are dropped elsewhere.
505 */
506 static void
507 drop_uid(uid_t uid, gid_t gid)
508 {
509 int fail = 0;
510 if (setgroups(0, NULL)) {
511 if (exit_on_drop_fail) {
512 fprintf(stderr, "arping: setgroups(0, NULL): %s\n", strerror(errno));
513 exit(1);
514 } else if (verbose) {
515 printf("arping: setgroups(0, NULL): %s\n", strerror(errno));
516 }
517 fail++;
518 }
519 if (gid && setgid(gid)) {
520 if (exit_on_drop_fail) {
521 fprintf(stderr, "arping: setgid(): %s\n", strerror(errno));
522 exit(1);
523 } else if (verbose) {
524 printf("arping: setgid(): %s\n", strerror(errno));
525 }
526 fail++;
527 }
528 if (uid && setuid(uid)) {
529 if (exit_on_drop_fail) {
530 fprintf(stderr, "arping: setuid(): %s\n", strerror(errno));
531 exit(1);
532 } else if (verbose) {
533 printf("arping: setuid(): %s\n", strerror(errno));
534 }
535 fail++;
536 }
537 if (!fail && verbose > 1) {
538 printf("arping: Successfully dropped uid/gid to %lld/%lld.\n",
539 cast_uid_longlong(uid, NULL), cast_gid_longlong(gid, NULL));
540 }
541 }
542
543 /**
544 * Drop any and all capabilities.
545 */
546 static void
547 drop_capabilities()
548 {
549 #ifdef ACTUALLY_HAS_CAP_INIT
550 cap_t no_cap;
551 if (!(no_cap = cap_init())) {
552 if (verbose) {
553 printf("arping: cap_init(): %s\n", strerror(errno));
554 }
555 return;
556 }
557 if (cap_set_proc(no_cap)) {
558 if (verbose) {
559 printf("arping: cap_set_proc(): %s\n", strerror(errno));
560 }
561 }
562 if (verbose > 1) {
563 printf("arping: Successfully dropped all capabilities.\n");
564 }
565 cap_free(no_cap);
566 #endif
567 }
568
569 /**
570 * Get GID of input (handle both name and number) or die.
571 */
572 static gid_t
573 must_get_group(const char* ident)
574 {
575 // Special case empty string, because strtol.
576 int saved_errno = 0;
577 if (*ident) {
578 // First try it as a name.
579 {
580 struct group* gr;
581 errno = 0;
582 if ((gr = getgrnam(ident))) {
583 return gr->gr_gid;
584 }
585 saved_errno = errno;
586 }
587
588 // Not a name. Try it as an integer.
589 {
590 char ebuf[1024] = {0};
591 const unsigned long v = parse_ulong(ident, "gid", ebuf, sizeof(ebuf));
592 if (!ebuf[0]) {
593 return cast_ulong_gid(v, NULL);
594 }
595 }
596 }
597
598 if (saved_errno != 0) {
599 fprintf(stderr,
600 "arping: %s not a number and getgrnam(%s): %s\n",
601 ident, ident, strerror(saved_errno));
602 } else {
603 // If group was supplied, then not
604 // existing is fatal error too.
605 fprintf(stderr,
606 "arping: %s is not a number or group\n",
607 ident);
608 }
609 exit(1);
610 }
611
612 /**
613 * drop all privileges.
614 *
615 * To be called as early as possible. IOW: immediately after opening
616 * raw socket.
617 */
618 static void
619 drop_privileges(const char* drop_group)
620 {
621 // Need to get uid/gid of 'nobody' before chroot().
622 const char* drop_user = "nobody";
623 struct passwd *pw;
624 errno = 0;
625 uid_t uid = 0;
626 gid_t gid = 0;
627 if (!(pw = getpwnam(drop_user))) {
628 if (exit_on_drop_fail) {
629 if (errno != 0) {
630 fprintf(stderr, "arping: getpwnam(%s): %s\n",
631 drop_user, strerror(errno));
632 } else {
633 fprintf(stderr, "arping: getpwnam(%s): unknown user\n",
634 drop_user);
635 }
636 exit(1);
637 } else if (verbose) {
638 if (errno != 0) {
639 printf("arping: getpwnam(%s): %s\n",
640 drop_user, strerror(errno));
641 } else {
642 printf("arping: getpwnam(%s): unknown user\n",
643 drop_user);
644 }
645 }
646 } else {
647 uid = pw->pw_uid;
648 gid = pw->pw_gid;
649 }
650
651 // If group is supplied, use that gid instead.
652 if (drop_group != NULL) {
653 gid = must_get_group(drop_group);
654 }
655 drop_fs_root();
656 drop_no_new_privs();
657 drop_landlock();
658 drop_uid(uid, gid);
659 drop_capabilities();
660 #ifdef HAVE_UNVEIL
661 if (unveil("/", "")) {
662 fprintf(stderr,
663 "arping: failed to unveil(/, <>): %s\n",
664 strerror(errno));
665 exit(1);
666 }
667 if (unveil(NULL, NULL)) {
668 fprintf(stderr, "arping: failed to unveil(NULL, NULL): %s\n",
669 strerror(errno));
670 exit(1);
671 }
672 if (verbose > 1) {
673 printf("arping: Successfully unveiled\n");
674 }
675 #endif
676 }
677
678 /**
679 * drop even more privileges, where possible.
680 *
681 * After all setup is done and main loop is about to start.
682 */
683 static void
684 drop_more_privileges(int libnet_fd)
685 {
686 UNUSED(libnet_fd);
687 #ifdef HAVE_PLEDGE
688 if (pledge("stdio tty", "")) {
689 fprintf(stderr, "arping: failed to pledge(stdio, <empty>): %s\n",
690 strerror(errno));
691 exit(1);
692 } else if (verbose > 1) {
693 printf("arping: Successfully pledged\n");
694 }
695 #endif
696 if (use_seccomp) {
697 drop_seccomp(libnet_fd);
698 }
699 }
700
701 /**
702 * Check for buggy libpcap version
703 * https://github.com/the-tcpdump-group/libpcap/issues/461
704 *
705 * This list is not authoritative.
706 *
707 * If it's over matching wrong the only impact *should* be that too many packets
708 * come through the BPF filter.
709 *
710 * If it's under-matching then replies with dot1p nonzero will not be seen.
711 */
712 static int
713 bug_pcap_vlan()
714 {
715 const char* bad[] = {
716 // Broken in 1.7.0.
717 "libpcap version 1.7",
718 "libpcap version 1.8",
719 "libpcap version 1.9.0",
720 // Fixed in 1.9.1.
721 // Fixed in 1.10 and up.
722 NULL,
723 };
724 const char* v = pcap_lib_version();
725 for (const char** t = bad; *t; t++) {
726 if (!strncmp(v, *t, strlen(*t))) {
727 return 1;
728 }
729 }
730 return 0;
731 }
732
733 /**
734 * Do pcap_open_live(), except by using the pcap_create() interface
735 * introduced in 2008 (libpcap 0.4) where available.
736 * This is so that we can set some options, which can't be set with
737 * pcap_open_live:
738 * 1) Immediate mode -- this prevents pcap from buffering.
739 * 2) Set timestamp type -- specify what type of timer to use.
740 *
741 * FIXME: Use pcap_set_buffer_size()?
742 */
743 static pcap_t*
744 try_pcap_open_live(const char *device, int snaplen, int to_ms, char *errbuf)
745 {
746 #ifdef HAVE_PCAP_CREATE
747 pcap_t* pcap;
748 int rc;
749
750 if (!(pcap = pcap_create(device, errbuf))) {
751 goto err;
752 }
753 if ((rc = pcap_set_snaplen(pcap, snaplen))) {
754 xsnprintf(errbuf, PCAP_ERRBUF_SIZE, "pcap_set_snaplen(): %s", pcap_statustostr(rc));
755 goto err;
756 }
757 if ((rc = pcap_set_promisc(pcap, promisc))) {
758 xsnprintf(errbuf, PCAP_ERRBUF_SIZE, "pcap_set_promisc(): %s", pcap_statustostr(rc));
759 goto err;
760 }
761 if ((rc = pcap_set_timeout(pcap, to_ms))) {
762 xsnprintf(errbuf, PCAP_ERRBUF_SIZE, "pcap_set_timeout(): %s", pcap_statustostr(rc));
763 goto err;
764 }
765
766 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
767 // Without immediate mode some architectures (e.g. Linux with
768 // TPACKET_V3) will buffer replies and incorrectly report upwards of
769 // hundreds of milliseconds of delay.
770 if ((rc = pcap_set_immediate_mode(pcap, 1))) {
771 if (verbose) {
772 fprintf(stderr, "arping: pcap_set_immediate_mode() failed: %s\n", pcap_statustostr(rc));
773 }
774 }
775 #endif
776 #ifdef HAVE_PCAP_LIST_TSTAMP_TYPES
777 if (timestamp_type) {
778 int err;
779 int v = pcap_tstamp_type_name_to_val(timestamp_type);
780 if (v == PCAP_ERROR) {
781 fprintf(stderr, "arping: Unknown timestamp type \"%s\"\n", timestamp_type);
782 exit(1);
783 }
784 if ((err = pcap_set_tstamp_type(pcap, v))) {
785 fprintf(stderr,
786 "arping: Failed to set timestamp type \"%s\" (%d): %s\n",
787 timestamp_type, v, pcap_statustostr(err));
788 }
789 }
790 #endif
791 if ((rc = pcap_activate(pcap))) {
792 if (timestamp_type) {
793 xsnprintf(errbuf, PCAP_ERRBUF_SIZE, "pcap_activate(tstype=\"%s\"): %s. Try without setting timestamp type.", timestamp_type, pcap_statustostr(rc));
794 } else {
795 xsnprintf(errbuf, PCAP_ERRBUF_SIZE, "pcap_activate(): %s", pcap_statustostr(rc));
796 }
797 goto err;
798 }
799 #ifdef HAVE_PCAP_LIST_TSTAMP_TYPES
800 // List timestamp types after activating, since we don't want to list
801 // them if activating failed.
802 if (verbose > 1) {
803 int *ts;
804 int count;
805 count = pcap_list_tstamp_types(pcap, &ts);
806 if (count == PCAP_ERROR) {
807 fprintf(stderr, "arping: pcap_list_tstamp_types() failed\n");
808 } else {
809 int c;
810 const char* fmt = " %-18s %s\n";
811 fprintf(stderr, "Timestamp types:\n");
812 fprintf(stderr, fmt, "Name", "Description");
813 for (c = 0; c < count; c++) {
814 fprintf(stderr, fmt, pcap_tstamp_type_val_to_name(ts[c]),
815 pcap_tstamp_type_val_to_description(ts[c]));
816 }
817 pcap_free_tstamp_types(ts);
818 }
819 }
820 #endif
821 return pcap;
822 err:
823 if (pcap) {
824 pcap_close(pcap);
825 }
826 return NULL;
827 #else
828 return pcap_open_live(device, snaplen, to_ms, errbuf);
829 #endif
830 }
831
832 /**
833 * Some stupid OSs (Solaris) think it's a good idea to put network
834 * devices in /dev and then play musical chairs with them.
835 *
836 * Since libpcap doesn't seem to have a workaround for that, here's arpings
837 * workaround.
838 *
839 * E.g. if the network interface is called net0, pcap will fail because it
840 * fails to open /dev/net, because it's a directory.
841 */
842 static pcap_t*
843 do_pcap_open_live(const char *device, int snaplen, int to_ms, char *errbuf)
844 {
845 pcap_t* ret;
846 char buf[PATH_MAX];
847
848 if ((ret = try_pcap_open_live(device, snaplen, to_ms, errbuf))) {
849 return ret;
850 }
851
852 xsnprintf(buf, sizeof(buf), "/dev/%s", device);
853 if ((ret = try_pcap_open_live(buf, snaplen, to_ms, errbuf))) {
854 return ret;
855 }
856
857 xsnprintf(buf, sizeof(buf), "/dev/net/%s", device);
858 if ((ret = try_pcap_open_live(buf, snaplen, to_ms, errbuf))) {
859 return ret;
860 }
861
862 /* Call original again to reset the error message. */
863 return try_pcap_open_live(device, snaplen, to_ms, errbuf);
864 }
865
866 /**
867 * Some Libnet error messages end with a newline. Strip that in place.
868 */
869 void
870 strip_newline(char* s) {
871 size_t n;
872 for (n = strlen(s); n && (s[n - 1] == '\n'); --n) {
873 s[n - 1] = 0;
874 }
875 }
876
877 /**
878 * Init libnet with specified ifname. Destroy if already inited.
879 *
880 * Libnet usually needs init before we have searched for the real
881 * interface. In that case, first we just give a NULL pointer as the
882 * interface. But libnet sometimes fails to find an interface (no idea
883 * why), so then we try to use "lo" and "lo0" explicitly.
884 *
885 * If even loopback fails, then it'll preserve the original error
886 * message.
887 *
888 * Call with recursive=0.
889 */
890 void
891 do_libnet_init(const char *inifname, int recursive)
892 {
893 const char* ifname = inifname;
894 int last = 0;
895 switch (recursive) {
896 case 0:
897 break;
898 case 1:
899 ifname = "lo"; // E.g. Linux.
900 break;
901 case 2:
902 ifname = "lo0"; // E.g. OpenBSD.
903 break;
904 default:
905 last = 1;
906 break;
907 }
908
909 // If we're given an interface name then always use that.
910 // No need to be recursive about it.
911 if (inifname != NULL && recursive == 0) {
912 ifname = inifname;
913 last = 1;
914 }
915
916 char ebuf[LIBNET_ERRBUF_SIZE];
917 ebuf[0] = 0;
918 if (verbose > 1) {
919 printf("arping: trying libnet_init(LIBNET_LINK, %s)\n",
920 ifname ? ifname : "<null>");
921 }
922 if (libnet) {
923 /* Probably going to switch interface from temp to real. */
924 libnet_destroy(libnet);
925 libnet = 0;
926 }
927
928 /* Try libnet_init() even though we maybe aren't root. We may have
929 * a capability or something. */
930 if (!(libnet = libnet_init(LIBNET_LINK,
931 (char*)ifname,
932 ebuf))) {
933 strip_newline(ebuf);
934 if (verbose) {
935 fprintf(stderr,
936 "arping: libnet_init(LIBNET_LINK, %s): %s\n",
937 ifname ? ifname : "<null>",
938 *ebuf ? ebuf : "<no error message>");
939 }
940 if (!last) {
941 do_libnet_init(ifname, recursive+1);
942 if (libnet != NULL) {
943 return;
944 }
945 }
946 if (!verbose) {
947 // Prevent double-print when verbose.
948 fprintf(stderr,
949 "arping: libnet_init(LIBNET_LINK, %s): %s\n",
950 ifname ? ifname : "<null>",
951 *ebuf ? ebuf : "<no error message>");
952 }
953 if (getuid() && geteuid()) {
954 fprintf(stderr,
955 "arping: you may need to run as root\n");
956 }
957 exit(1);
958 }
959 }
960
961 /**
962 *
963 */
964 void
965 sigint(int i)
966 {
967 UNUSED(i);
968 time_to_die = 1;
969 }
970
971 /**
972 * idiot-proof clock_gettime() wrapper
973 */
974 static void
975 getclock(struct timespec *ts)
976 {
977 memset(ts, 0, sizeof(struct timespec));
978 #if HAVE_CLOCK_MONOTONIC
979 static int clock_gettime_failed = 0;
980 if (!clock_gettime_failed) {
981 if (0 == clock_gettime(CLOCK_MONOTONIC, ts)) {
982 return;
983 }
984 fprintf(stderr, "arping: clock_gettime(): %s\n",
985 strerror(errno));
986 clock_gettime_failed = 1; // Prevent duplicate error messages.
987 }
988 #endif
989 struct timeval tv;
990 if (-1 == gettimeofday(&tv, NULL)) {
991 fprintf(stderr, "arping: gettimeofday(): %s\n",
992 strerror(errno));
993 sigint(0);
994 }
995 ts->tv_sec = tv.tv_sec;
996 ts->tv_nsec = tv.tv_usec * 1000;
997 }
998
999 /**
1000 *
1001 */
1002 static char*
1003 format_mac(const unsigned char* mac, char* buf, size_t bufsize) {
1004 xsnprintf(buf, bufsize, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
1005 (unsigned)mac[0], (unsigned)mac[1],
1006 (unsigned)mac[2], (unsigned)mac[3],
1007 (unsigned)mac[4], (unsigned)mac[5]);
1008 return buf;
1009 }
1010
1011 /**
1012 *
1013 */
1014 static void
1015 extended_usage()
1016 {
1017 printf("\nOptions:\n");
1018 printf("\n"
1019 " -0 Use this option to ping with source IP address 0.0.0.0. Use this\n"
1020 " when you haven't configured your interface yet. Note that this\n"
1021 " may get the MAC-ping unanswered. This is an alias for -S\n"
1022 " 0.0.0.0.\n"
1023 " -a Audiable ping.\n"
1024 " -A Only count addresses matching requested address (This *WILL*\n"
1025 " break most things you do. Only useful if you are arpinging many\n"
1026 " hosts at once. See arping-scan-net.sh for an example).\n"
1027 " -b Like -0 but source broadcast source address (255.255.255.255).\n"
1028 " Note that this may get the arping unanswered since it's not nor-\n"
1029 " mal behavior for a host.\n"
1030 " -B Use instead of host if you want to address 255.255.255.255.\n"
1031 " -c count\n"
1032 " Only send count requests.\n"
1033 " -C count\n"
1034 " Only wait for this many replies, regardless of -c and -w.\n"
1035 " -d Find duplicate replies. Exit with 1 if there are "
1036 "answers from\n"
1037 " two different MAC addresses.\n"
1038 " -D Display answers as exclamation points and missing packets as dots.\n"
1039 " -e Like -a but beep when there is no reply.\n"
1040 " -F Don't try to be smart about the interface name. (even if this\n"
1041 " switch is not given, -i overrides smartness)\n"
1042 " -g group\n"
1043 " setgid() to this group instead of the nobody group.\n"
1044 " -h Displays a help message and exits.\n"
1045 " -i interface\n"
1046 " Use the specified interface.\n"
1047 " -m type"
1048 #ifndef HAVE_PCAP_LIST_TSTAMP_TYPES
1049 " (Disabled on this system. Option ignored)"
1050 #endif
1051 "\n Type of timestamp to use for incoming packets. Use -vv when\n"
1052 " pinging to list available ones.\n"
1053 " -q Does not display messages, except error messages.\n"
1054 " -Q pri 802.1p priority to set. Should be used with 802.1Q (-V).\n"
1055 " Defaults to 0.\n"
1056 " -r Raw output: only the MAC/IP address is displayed for each reply.\n"
1057 " -R Raw output: Like -r but shows \"the other one\", can be combined\n"
1058 " with -r.\n"
1059 " -s MAC Set source MAC address. You may need to use -p with this.\n"
1060 " -S IP Like -b and -0 but with set source address. Note that this may\n"
1061 " get the arping unanswered if the target does not have routing to\n"
1062 " the IP. If you don't own the IP you are using, you may need to\n"
1063 " turn on promiscious mode on the interface (with -p). With this\n"
1064 " switch you can find out what IP-address a host has without tak-\n"
1065 " ing an IP-address yourself.\n"
1066 " -t MAC Set target MAC address to use when pinging IP address.\n"
1067 " -T IP Use -T as target address when pinging MACs that won't respond to\n"
1068 " a broadcast ping but perhaps to a directed broadcast.\n"
1069 " Example:\n"
1070 " To check the address of MAC-A, use knowledge of MAC-B and IP-B.\n"
1071 " $ arping -S <IP-B> -s <MAC-B> -p <MAC-A>\n"
1072 " -p Turn on promiscious mode on interface, use this if you don't\n"
1073 " \"own\" the MAC address you are using.\n"
1074 " -P Send ARP replies instead of requests. Useful with -U.\n"
1075 " -u Show index=received/sent instead of just index=received when\n"
1076 " pinging MACs.\n"
1077 " -U Send unsolicited ARP.\n"
1078 " -v Verbose output. Use twice for more messages.\n"
1079 " -V num 802.1Q tag to add. Defaults to no VLAN tag.\n"
1080 " -w sec Specify a timeout before ping exits regardless of how many\n"
1081 " packets have been sent or received.\n"
1082 " -W sec Time to wait between pings.\n"
1083 #if USE_SECCOMP
1084 " -z Enable seccomp%s\n"
1085 " -Z Disable seccomp%s\n",
1086 DEFAULT_SECCOMP ? " (default)" : "",
1087 DEFAULT_SECCOMP ? "" : " (default)"
1088 #endif
1089 );
1090 printf("Report bugs to: [email protected]\n"
1091 "Arping home page: <http://www.habets.pp.se/synscan/>\n"
1092 "Development repo: http://github.com/ThomasHabets/arping\n");
1093 }
1094
1095 /**
1096 *
1097 */
1098 static void
1099 standard_usage()
1100 {
1101 printf("ARPing %s, by Thomas Habets <[email protected]>\n",
1102 version);
1103 printf("usage: arping [ -0aAbdDeFpPqrRuUv%s ] [ -w <sec> ] "
1104 "[ -W <sec> ] "
1105 "[ -S <host/ip> ]\n"
1106 " "
1107 "[ -T <host/ip ] "
1108 "[ -s <MAC> ] [ -t <MAC> ] [ -c <count> ]\n"
1109 " "
1110 "[ -C <count> ] [ -i <interface> ] [ -m <type> ]"
1111 " [ -g <group> ]\n"
1112 " "
1113 "[ -V <vlan> ] [ -Q <priority> ] "
1114 "<host/ip/MAC | -B>\n", USE_SECCOMP ? "zZ" : "");
1115 }
1116
1117 /**
1118 *
1119 */
1120 static void
1121 usage(int ret)
1122 {
1123 standard_usage();
1124 if (WIN32) {
1125 extended_usage();
1126 } else {
1127 printf("For complete usage info, use --help"
1128 " or check the manpage.\n");
1129 }
1130 exit(ret);
1131 }
1132
1133 /**
1134 *
1135 */
1136 static void
1137 print_library_versions()
1138 {
1139 fprintf(stderr, "arping: %s\n", pcap_lib_version());
1140 if (bug_pcap_vlan()) {
1141 fprintf(stderr, "arping: bug: https://github.com/the-tcpdump-group/libpcap/issues/461\n");
1142 }
1143 fprintf(stderr, "arping: %s\n", libnet_version());
1144 }
1145
1146 /**
1147 * Check to see if it looks somewhat like a MAC address.
1148 *
1149 * It was unclear from msdn.microsoft.com if their scanf() supported
1150 * [0-9a-fA-F], so I'll stay away from it.
1151 *
1152 */
1153 int is_mac_addr(const char *p)
1154 {
1155 const size_t len = strlen(p);
1156 /* cisco-style hhhh.hhhh.hhhh */
1157 if (len == 14) {
1158 unsigned int c;
1159 for (c = 0; c < 14; c++) {
1160 if ((c % 5) == 4) {
1161 if ('.' != p[c]) {
1162 return 0;
1163 }
1164 } else {
1165 if (!isxdigit((unsigned char)p[c])) {
1166 return 0;
1167 }
1168 }
1169 }
1170 return 1;
1171 }
1172 if (len != 17) {
1173 // Windows and unix ones are 17 characters.
1174 return 0;
1175 }
1176
1177 /* windows-style xx-xx-xx-xx-xx-xx */
1178 unsigned int c;
1179 for (c = 0; c < 17; c++) {
1180 if ((c % 3) == 2) {
1181 if ('-' != p[c]) {
1182 goto checkunix;
1183 }
1184 } else {
1185 if (!isxdigit((unsigned char)p[c])) {
1186 goto checkunix;
1187 }
1188 }
1189 }
1190 return 1;
1191
1192 checkunix:
1193 /* unix xx:xx:xx:xx:xx:xx */
1194 for (c = 0; c < 17; c++) {
1195 if ((c % 3) == 2) {
1196 if (':' != p[c]) {
1197 return 0;
1198 }
1199 } else {
1200 if (!isxdigit((unsigned char)p[c])) {
1201 return 0;
1202 }
1203 }
1204 }
1205 return 1;
1206 }
1207
1208 /**
1209 * parse mac address.
1210 *
1211 * return 1 on success.
1212 */
1213 int
1214 get_mac_addr(const char *in, uint8_t *out)
1215 {
1216 const char *formats[] = {
1217 "%x:%x:%x:%x:%x:%x%n",
1218 "%2x%x.%2x%x.%2x%x%n",
1219 "%x-%x-%x-%x-%x-%x%n",
1220 NULL,
1221 };
1222 if (!is_mac_addr(in)) {
1223 return 0;
1224 }
1225 int c;
1226 for (c = 0; formats[c]; c++) {
1227 unsigned int n[6];
1228 int endp = 0;
1229 if (6 == sscanf(in, formats[c],
1230 &n[0], &n[1], &n[2], &n[3], &n[4], &n[5],
1231 &endp)) {
1232 int i;
1233 if (in[endp] != '\0') {
1234 return 0;
1235 }
1236 for (i = 0; i < 6; i++) {
1237 if (n[i] > 0xff) {
1238 return 0;
1239 }
1240 out[i] = (uint8_t)n[i];
1241 }
1242 return 1;
1243 }
1244 }
1245 return 0;
1246 }
1247
1248 /**
1249 *
1250 */
1251 static void
1252 update_stats(double sample)
1253 {
1254 if (stats_min_time < 0 || sample < stats_min_time) {
1255 stats_min_time = sample;
1256 }
1257 if (sample > stats_max_time) {
1258 stats_max_time = sample;
1259 }
1260 stats_total_time += sample;
1261 stats_total_sq_time += sample * sample;
1262 }
1263
1264 /**
1265 * return 1 if reply limit reached.
1266 */
1267 static int
1268 stop_at_reply_limit(unsigned char* pcap_user)
1269 {
1270 if (numrecvd < max_replies) {
1271 return 0;
1272 }
1273 if (pcap_user) {
1274 pcap_breakloop((pcap_t*)pcap_user);
1275 }
1276 return 1;
1277 }
1278
1279 /**
1280 *
1281 */
1282 static double
1283 timespec2dbl(const struct timespec *tv)
1284 {
1285 return (double)tv->tv_sec + (double)tv->tv_nsec / 1000000000;
1286 }
1287
1288 /**
1289 * return number of microseconds to wait for packets.
1290 */
1291 static uint32_t
1292 wait_time(double deadline, uint32_t packetwait)
1293 {
1294 struct timespec ts;
1295
1296 // If deadline not specified, then don't use it.
1297 if (deadline < 0) {
1298 return packetwait;
1299 }
1300
1301 getclock(&ts);
1302 const double max_wait = deadline - timespec2dbl(&ts);
1303 if (max_wait < 0) {
1304 return 0;
1305 }
1306 if (max_wait > packetwait / 1000000.0) {
1307 return packetwait;
1308 }
1309 return cast_double_uint32(max_wait * 1000000);
1310 }
1311
1312 /**
1313 * max size of buffer is intsize + 1 + intsize + 4 = 70 bytes or so
1314 *
1315 * Still, I'm using at least 128bytes below
1316 */
1317 static char *ts2str(const struct timespec *tv, const struct timespec *tv2,
1318 char *buf, size_t bufsize)
1319 {
1320 double f,f2;
1321 int exp = 0;
1322
1323 f = timespec2dbl(tv);
1324 f2 = timespec2dbl(tv2);
1325 f = (f2 - f) * 1000000000;
1326 while (f > 1000) {
1327 exp += 3;
1328 f /= 1000;
1329 }
1330 switch (exp) {
1331 case 0:
1332 xsnprintf(buf, bufsize, "%.3f nsec", f);
1333 break;
1334 case 3:
1335 xsnprintf(buf, bufsize, "%.3f usec", f);
1336 break;
1337 case 6:
1338 xsnprintf(buf, bufsize, "%.3f msec", f);
1339 break;
1340 case 9:
1341 xsnprintf(buf, bufsize, "%.3f sec", f);
1342 break;
1343 case 12:
1344 xsnprintf(buf, bufsize, "%.3f sec", f*1000);
1345 break;
1346 default:
1347 /* huh, uh, huhuh */
1348 xsnprintf(buf, bufsize, "%.3fe%d sec", f, exp-9);
1349 }
1350 return buf;
1351 }
1352
1353 /** Send directed IPv4 ICMP echo request.
1354 *
1355 * \param id IP id
1356 * \param seq Ping seq
1357 */
1358 static void
1359 pingmac_send(uint16_t id, uint16_t seq)
1360 {
1361 static libnet_ptag_t icmp = 0, ipv4 = 0,eth=0;
1362
1363 // Padding size chosen fairly arbitrarily.
1364 // Without this padding some systems (e.g. Raspberry Pi 3
1365 // wireless interface) failed. dmesg said:
1366 // arping: packet size is too short (42 <= 50)
1367 const size_t padding_size = sizeof(struct timespec) + payload_suffix_size;
1368 uint8_t padding[padding_size];
1369 memset(padding, 0, padding_size);
1370 {
1371 struct timespec ts;
1372 getclock(&ts);
1373 memcpy(padding, &ts, sizeof(struct timespec));
1374 memcpy(&padding[sizeof(struct timespec)],
1375 payload_suffix, payload_suffix_size);
1376 }
1377
1378 if (-1 == (icmp = libnet_build_icmpv4_echo(ICMP_ECHO, /* type */
1379 0, /* code */
1380 0, /* checksum */
1381 id, /* id */
1382 seq, /* seq */
1383 (uint8_t*)padding, /* payload */
1384 cast_size_uint32(padding_size, NULL), /* payload len */
1385 libnet,
1386 icmp))) {
1387 fprintf(stderr, "libnet_build_icmpv4_echo(): %s\n",
1388 libnet_geterror(libnet));
1389 sigint(0);
1390 }
1391
1392 if (-1 == (ipv4 = libnet_build_ipv4(
1393 cast_size_uint16(
1394 LIBNET_IPV4_H + LIBNET_ICMPV4_ECHO_H + padding_size,
1395 NULL),
1396 0, /* ToS */
1397 id, /* id */
1398 0, /* frag */
1399 64, /* ttl */
1400 IPPROTO_ICMP,
1401 0, /* checksum */
1402 srcip,
1403 dstip,
1404 NULL, /* payload */
1405 0,
1406 libnet,
1407 ipv4))) {
1408 fprintf(stderr, "libnet_build_ipv4(): %s\n",
1409 libnet_geterror(libnet));
1410 sigint(0);
1411 }
1412 if (vlan_tag >= 0) {
1413 eth = libnet_build_802_1q(dstmac,
1414 srcmac,
1415 ETHERTYPE_VLAN,
1416 cast_int16_uint8(vlan_prio, NULL),
1417 0, // cfi
1418 cast_int16_uint16(vlan_tag, NULL),
1419 ETHERTYPE_IP,
1420 NULL, // payload
1421 0, // payload length
1422 libnet,
1423 eth);
1424 } else {
1425 eth = libnet_build_ethernet(dstmac,
1426 srcmac,
1427 ETHERTYPE_IP,
1428 NULL, // payload
1429 0, // payload length
1430 libnet,
1431 eth);
1432 }
1433 if (-1 == eth) {
1434 fprintf(stderr, "arping: %s: %s\n",
1435 (vlan_tag >= 0) ? "libnet_build_802_1q()" :
1436 "libnet_build_ethernet()",
1437 libnet_geterror(libnet));
1438 sigint(0);
1439 }
1440 if (verbose > 1) {
1441 getclock(&lastpacketsent);
1442 printf("arping: sending packet at time %"PRIdMAX".%09"PRIdMAX"\n",
1443 (intmax_t)lastpacketsent.tv_sec,
1444 (intmax_t)lastpacketsent.tv_nsec);
1445 }
1446 if (-1 == libnet_write(libnet)) {
1447 fprintf(stderr, "arping: libnet_write(): %s\n",
1448 libnet_geterror(libnet));
1449 libnet_write_failures++;
1450 sigint(0);
1451 }
1452 getclock(&lastpacketsent);
1453 numsent++;
1454 }
1455
1456 /** Send ARP who-has.
1457 *
1458 */
1459 static void
1460 pingip_send()
1461 {
1462 static libnet_ptag_t arp=0,eth=0;
1463
1464 // Padding size chosen fairly arbitrarily.
1465 // Without this padding some systems (e.g. Raspberry Pi 3
1466 // wireless interface) failed. dmesg said:
1467 // arping: packet size is too short (42 <= 50)
1468 const uint8_t padding[16] = {0};
1469
1470 if (-1 == (arp = libnet_build_arp(ARPHRD_ETHER,
1471 ETHERTYPE_IP,
1472 ETH_ALEN,
1473 IP_ALEN,
1474 send_reply ? ARPOP_REPLY : ARPOP_REQUEST,
1475 srcmac,
1476 (uint8_t*)&srcip,
1477 unsolicited ? (uint8_t*)ethxmas : (send_reply ? dstmac : (uint8_t*)ethnull),
1478 (uint8_t*)&dstip,
1479 (uint8_t*)padding,
1480 sizeof padding,
1481 libnet,
1482 arp))) {
1483 fprintf(stderr, "arping: libnet_build_arp(): %s\n",
1484 libnet_geterror(libnet));
1485 sigint(0);
1486 }
1487
1488 if (vlan_tag >= 0) {
1489 eth = libnet_build_802_1q(dstmac,
1490 srcmac,
1491 ETHERTYPE_VLAN,
1492 cast_int16_uint8(vlan_prio, NULL),
1493 0, // cfi
1494 cast_int16_uint16(vlan_tag, NULL),
1495 ETHERTYPE_ARP,
1496 NULL, // payload
1497 0, // payload size
1498 libnet,
1499 eth);
1500 } else {
1501 eth = libnet_build_ethernet(dstmac,
1502 srcmac,
1503 ETHERTYPE_ARP,
1504 NULL, // payload
1505 0, // payload size
1506 libnet,
1507 eth);
1508 }
1509 if (-1 == eth) {
1510 fprintf(stderr, "arping: %s: %s\n",
1511 (vlan_tag >= 0) ? "libnet_build_802_1q()" :
1512 "libnet_build_ethernet()",
1513 libnet_geterror(libnet));
1514 sigint(0);
1515 }
1516 if (verbose > 1) {
1517 getclock(&lastpacketsent);
1518 printf("arping: sending packet at time %"PRIdMAX".%09"PRIdMAX"\n",
1519 (intmax_t)lastpacketsent.tv_sec,
1520 (intmax_t)lastpacketsent.tv_nsec);
1521 }
1522 if (send_reply && display != QUIET) {
1523 printf("Sending ARP reply\n");
1524 }
1525 if (-1 == libnet_write(libnet)) {
1526 fprintf(stderr, "arping: libnet_write(): %s\n",
1527 libnet_geterror(libnet));
1528 libnet_write_failures++;
1529 sigint(0);
1530 }
1531 getclock(&lastpacketsent);
1532 numsent++;
1533 }
1534
1535 /** handle incoming packet when pinging an IP address.
1536 *
1537 * \param h packet metadata
1538 * \param packet packet data
1539 */
1540 void
1541 pingip_recv(unsigned char *pcap_user, const struct pcap_pkthdr *h, const unsigned char * const packet)
1542 {
1543 unsigned char pkt_srcmac[ETH_ALEN];
1544 const unsigned char* arpdata = NULL;
1545 int ethernet_header_size = LIBNET_ETH_H;
1546 struct libnet_arp_hdr harp;
1547 struct timespec arrival;
1548 assert(packet);
1549
1550 if (stop_at_reply_limit(pcap_user)) {
1551 return;
1552 }
1553
1554 if (verbose > 2) {
1555 printf("arping: received response for IP ping\n");
1556 }
1557
1558 getclock(&arrival);
1559
1560 // Handle both sizes of ethernet frames.
1561 if (vlan_tag >= 0) {
1562 struct libnet_802_1q_hdr veth;
1563 if (h->caplen < LIBNET_802_1Q_H + LIBNET_ARP_H + 2*(ETH_ALEN + 4)) {
1564 return;
1565 }
1566 if (verbose > 3) {
1567 printf("arping: ... good length\n");
1568 }
1569 ethernet_header_size = LIBNET_802_1Q_H;
1570 memcpy(&veth, (void*)packet, LIBNET_802_1Q_H);
1571 memcpy(pkt_srcmac, veth.vlan_shost, ETH_ALEN);
1572
1573 if (ntohs(veth.vlan_tpi) != 0x8100) {
1574 return;
1575 }
1576 if (verbose > 3) {
1577 printf("arping: ... TPI 0x8100\n");
1578 }
1579 const int packet_vlan = 0xfff & ntohs(veth.vlan_priority_c_vid);
1580 if (verbose > 4) {
1581 printf("arping: ... is dot1q VLAN %d\n", packet_vlan);
1582 }
1583 if (packet_vlan != vlan_tag) {
1584 return;
1585 }
1586 if (verbose > 3) {
1587 printf("arping: ... right VLAN\n");
1588 }
1589 } else {
1590 if (h->caplen < LIBNET_ETH_H + LIBNET_ARP_H + 2*(ETH_ALEN + 4)) {
1591 return;
1592 }
1593 if (verbose > 3) {
1594 printf("arping: ... good length\n");
1595 }
1596 struct libnet_802_3_hdr heth;
1597 memcpy(&heth, (void*)packet, sizeof(heth));
1598 memcpy(pkt_srcmac, heth._802_3_shost, ETH_ALEN);
1599 }
1600
1601 // Set up aligned structs for further checking.
1602 memcpy(&harp, (char*)packet + ethernet_header_size, LIBNET_ARP_H);
1603 arpdata = packet + ethernet_header_size + LIBNET_ARP_H;
1604
1605 // Not checking ethertype because in theory this could be used for
1606 // Ethernet II.
1607
1608 // Wrong length of hardware address.
1609 if (harp.ar_hln != ETH_ALEN) {
1610 return;
1611 }
1612 if (verbose > 3) {
1613 printf("arping: ... L2 addr len is correct\n");
1614 }
1615
1616 // Wrong length of protocol address.
1617 if (harp.ar_pln != 4) {
1618 return;
1619 }
1620 if (verbose > 3) {
1621 printf("arping: ... L3 addr len is correct\n");
1622 }
1623
1624 // ARP reply.
1625 if (ntohs(harp.ar_op) != ARPOP_REPLY) {
1626 return;
1627 }
1628 if (verbose > 3) {
1629 printf("arping: ... packet is ARP reply\n");
1630 }
1631
1632 // From IPv4 address reply.
1633 if (ntohs(harp.ar_pro) != ETHERTYPE_IP) {
1634 return;
1635 }
1636 if (verbose > 3) {
1637 printf("arping: ... from IPv4 address\n");
1638 }
1639
1640 // To Ethernet address.
1641 if (ntohs(harp.ar_hrd) != ARPHRD_ETHER) {
1642 return;
1643 }
1644 if (verbose > 3) {
1645 printf("arping: ... to Ethernet address\n");
1646 }
1647
1648 // Must be sent from target address.
1649 // Should very likely only be used if using -t.
1650 if (addr_must_be_same) {
1651 if (memcmp(arpdata, dstmac, ETH_ALEN)) {
1652 return;
1653 }
1654 }
1655 if (verbose > 3) {
1656 printf("arping: ... sent by acceptable host\n");
1657 }
1658
1659 // Special case: If we're not in promisc mode we could still
1660 // get packets where DST mac is not us, if they're *sent* from
1661 // the local host. This is an edge case but in general falls under "is promisc?".
1662 //
1663 // It may cause confusion because `-p` now means not just
1664 // enable promisc mode (disable filter on card / in kernel),
1665 // but also allow packets to any destination (disable filter
1666 // in `arping`).
1667 {
1668 const uint8_t* p = (u_char*)arpdata
1669 + ETH_ALEN
1670 + IP_ALEN;
1671 char buf[128];
1672 if (!promisc && memcmp(p, srcmac, ETH_ALEN)) {
1673 format_mac(p, buf, sizeof buf);
1674 if (verbose > 3) {
1675 printf("arping: ... but sent from %s\n", buf);
1676 }
1677 return;
1678 }
1679 }
1680 if (verbose > 3) {
1681 printf("arping: ... destination is the source we used\n");
1682 }
1683
1684 // Actually the IPv4 address we asked for.
1685 uint32_t ip;
1686 memcpy(&ip, (char*)arpdata + harp.ar_hln, 4);
1687 if (dstip != ip) {
1688 return;
1689 }
1690 if (verbose > 3) {
1691 printf("arping: ... for the right IPv4 address!\n");
1692 }
1693
1694 // Packet is correct.
1695
1696 update_stats(timespec2dbl(&arrival) - timespec2dbl(&lastpacketsent));
1697 char buf[128];
1698 if (beep) {
1699 printf("\a");
1700 }
1701 switch(display) {
1702 case DOT:
1703 putchar('!');
1704 break;
1705 case NORMAL:
1706 printf("%u bytes from %s (%s): index=%u",
1707 h->len, format_mac(pkt_srcmac, buf, sizeof(buf)),
1708 libnet_addr2name4(ip, 0), numrecvd);
1709
1710 if (alsototal) {
1711 unsigned int t = numsent;
1712 if (t > 0) {
1713 --t;
1714 }
1715 printf("/%u", t);
1716 }
1717 printf(" time=%s", ts2str(&lastpacketsent, &arrival, buf,
1718 sizeof(buf)));
1719 break;
1720 case QUIET:
1721 break;
1722 case RAWRAW:
1723 printf("%s %s", format_mac(pkt_srcmac, buf, sizeof(buf)),
1724 libnet_addr2name4(ip, 0));
1725 break;
1726 case RRAW:
1727 printf("%s", libnet_addr2name4(ip, 0));
1728 break;
1729 case RAW:
1730 printf("%s", format_mac(pkt_srcmac, buf, sizeof(buf)));
1731 break;
1732 default:
1733 fprintf(stderr, "arping: can't happen!\n");
1734 }
1735 fflush(stdout);
1736
1737 switch (display) {
1738 case QUIET:
1739 case DOT:
1740 break;
1741 default:
1742 printf("\n");
1743 }
1744 if (numrecvd) {
1745 if (memcmp(lastreplymac,
1746 pkt_srcmac, ETH_ALEN)) {
1747 dupfound = 1;
1748 }
1749 }
1750 memcpy(lastreplymac, pkt_srcmac, ETH_ALEN);
1751
1752 numrecvd++;
1753 stop_at_reply_limit(pcap_user);
1754 }
1755
1756 /** handle incoming packet when pinging an MAC address.
1757 *
1758 * \param h packet metadata
1759 * \param packet packet data
1760 */
1761 void
1762 pingmac_recv(unsigned char* pcap_user, const struct pcap_pkthdr *h, const uint8_t *packet)
1763 {
1764 unsigned char pkt_dstmac[ETH_ALEN];
1765 unsigned char pkt_srcmac[ETH_ALEN];
1766 struct libnet_ipv4_hdr hip;
1767 // TODO: also inspect the echo fields.
1768 struct libnet_icmpv4_hdr hicmp;
1769 struct timespec arrival;
1770 const uint8_t* payload = NULL;
1771 assert(packet);
1772
1773 if (stop_at_reply_limit(pcap_user)) {
1774 return;
1775 }
1776
1777 if(verbose>2) {
1778 printf("arping: received response for mac ping len=%u caplen=%u\n",
1779 h->len, h->caplen);
1780 }
1781
1782 getclock(&arrival);
1783
1784 if (vlan_tag >= 0) {
1785 struct libnet_802_1q_hdr veth;
1786 if (h->caplen < LIBNET_802_1Q_H + LIBNET_IPV4_H
1787 + LIBNET_ICMPV4_ECHO_H
1788 + sizeof(struct timespec)
1789 + payload_suffix_size) {
1790 return;
1791 }
1792 if (verbose > 3) {
1793 printf("arping: ... good length\n");
1794 }
1795 memcpy(&veth, packet, LIBNET_802_1Q_H);
1796 memcpy(&hip, (char*)packet
1797 + LIBNET_802_1Q_H, LIBNET_IPV4_H);
1798 memcpy(&hicmp, (char*)packet
1799 + LIBNET_802_1Q_H
1800 + LIBNET_IPV4_H, LIBNET_ICMPV4_ECHO_H);
1801 memcpy(pkt_srcmac, veth.vlan_shost, ETH_ALEN);
1802 memcpy(pkt_dstmac, veth.vlan_dhost, ETH_ALEN);
1803 payload = packet
1804 + LIBNET_802_1Q_H
1805 + LIBNET_IPV4_H
1806 + LIBNET_ICMPV4_ECHO_H;
1807
1808 if (ntohs(veth.vlan_tpi) != 0x8100) {
1809 return;
1810 }
1811 const int packet_vlan = 0xfff & ntohs(veth.vlan_priority_c_vid);
1812 if (verbose > 3) {
1813 printf("arping: ... is dot1q %d\n", packet_vlan);
1814 }
1815 if (packet_vlan != vlan_tag) {
1816 return;
1817 }
1818 if (verbose > 3) {
1819 printf("arping: ... right VLAN\n");
1820 }
1821 } else {
1822 struct libnet_802_3_hdr heth;
1823 if (h->caplen < LIBNET_ETH_H + LIBNET_IPV4_H
1824 + LIBNET_ICMPV4_ECHO_H
1825 + sizeof(struct timespec)
1826 + payload_suffix_size) {
1827 return;
1828 }
1829 if (verbose > 3) {
1830 printf("arping: ... good length\n");
1831 }
1832 memcpy(&heth, packet, LIBNET_ETH_H);
1833 memcpy(&hip, (char*)packet
1834 + LIBNET_ETH_H, LIBNET_IPV4_H);
1835 memcpy(&hicmp, (char*)packet
1836 + LIBNET_ETH_H
1837 + LIBNET_IPV4_H, LIBNET_ICMPV4_ECHO_H);
1838 memcpy(pkt_srcmac, heth._802_3_shost, ETH_ALEN);
1839 memcpy(pkt_dstmac, heth._802_3_dhost, ETH_ALEN);
1840 payload = packet
1841 + LIBNET_ETH_H
1842 + LIBNET_IPV4_H
1843 + LIBNET_ICMPV4_ECHO_H;
1844 }
1845
1846 // Not checking ethertype because in theory this could be used for
1847 // Ethernet II.
1848
1849 // Dest MAC must be me.
1850 if (memcmp(pkt_dstmac, srcmac, ETH_ALEN)) {
1851 return;
1852 }
1853
1854 if (verbose > 3) {
1855 printf("arping: ... right dst mac\n");
1856 }
1857
1858 // Source MAC must match, if set.
1859 if (memcmp(dstmac, ethxmas, ETH_ALEN)) {
1860 if (memcmp(pkt_srcmac, dstmac, ETH_ALEN)) {
1861 return;
1862 }
1863 }
1864
1865 if (verbose > 3) {
1866 printf("arping: ... right src mac\n");
1867 }
1868
1869 // TODO: Even though we have a BPF filter, add checks for IP version and
1870 // protocol fields.
1871
1872 // IPv4 Address must be me (maybe).
1873 if (addr_must_be_same) {
1874 uint32_t tmp;
1875 memcpy(&tmp, &hip.ip_src, 4);
1876 if (dstip != tmp) {
1877 return;
1878 }
1879 }
1880 if (verbose > 3) {
1881 printf("arping: ... src IP acceptable\n");
1882 }
1883
1884 // Must be ICMP echo reply type.
1885 if (hicmp.icmp_type != ICMP_ECHOREPLY) {
1886 return;
1887 }
1888
1889 if (verbose > 3) {
1890 printf("arping: ... is echo reply type\n");
1891 }
1892
1893 // Must be ICMP echo reply code 0.
1894 if (hicmp.icmp_code != 0) {
1895 return;
1896 }
1897
1898 if (verbose > 3) {
1899 printf("arping: ... is echo reply code\n");
1900 }
1901
1902 const size_t tmp = cast_ssize_size(payload - (uint8_t*)packet, NULL);
1903 if (h->caplen < tmp) {
1904 return;
1905 }
1906 const size_t payload_size = h->caplen - tmp;
1907 if (payload_size < sizeof(struct timespec) + payload_suffix_size) {
1908 return;
1909 }
1910 if (verbose > 3) {
1911 printf("arping: ... correct payload size (%zu, suffix %zu)\n",
1912 payload_size, payload_suffix_size);
1913 }
1914 if (memcmp(&payload[sizeof(struct timespec)],
1915 payload_suffix, payload_suffix_size)) {
1916 return;
1917 }
1918 if (verbose > 3) {
1919 printf("arping: ... correct payload suffix\n");
1920 }
1921
1922 // TODO: use timestamp from packet payload instead of last packet sent.
1923 update_stats(timespec2dbl(&arrival) - timespec2dbl(&lastpacketsent));
1924 if (beep) {
1925 printf("\a");
1926 }
1927 char buf[128];
1928 char buf2[128];
1929 switch(display) {
1930 case QUIET:
1931 break;
1932 case DOT:
1933 putchar('!');
1934 break;
1935 case NORMAL:
1936 printf("%u bytes from %s (%s): icmp_seq=%hu time=%s", h->len,
1937 libnet_addr2name4(hip.ip_src.s_addr, 0),
1938 format_mac(pkt_srcmac, buf, sizeof(buf)),
1939 ntohs(hicmp.icmp_seq),
1940 ts2str(&lastpacketsent, &arrival, buf2, sizeof(buf2)));
1941 break;
1942 case RAW:
1943 printf("%s", libnet_addr2name4(hip.ip_src.s_addr, 0));
1944 break;
1945 case RRAW:
1946 printf("%s", format_mac(pkt_srcmac, buf, sizeof(buf)));
1947 break;
1948 case RAWRAW:
1949 printf("%s %s",
1950 format_mac(pkt_srcmac, buf, sizeof(buf)),
1951 libnet_addr2name4(hip.ip_src.s_addr, 0));
1952 break;
1953 default:
1954 fprintf(stderr, "arping: can't-happen-bug\n");
1955 sigint(0);
1956 }
1957 fflush(stdout);
1958 switch (display) {
1959 case QUIET:
1960 case DOT:
1961 break;
1962 default:
1963 printf("\n");
1964 }
1965 numrecvd++;
1966 stop_at_reply_limit(pcap_user);
1967 }
1968
1969 /**
1970 * while negative nanoseconds, take from whole seconds.
1971 * help function for measuring deltas.
1972 */
1973 static void
1974 fixup_timespec(struct timespec *tv)
1975 {
1976 while (tv->tv_nsec < 0) {
1977 tv->tv_sec--;
1978 tv->tv_nsec += 1000000000;
1979 }
1980 while (tv->tv_nsec >= 1000000000) {
1981 tv->tv_sec++;
1982 tv->tv_nsec -= 1000000000;
1983 }
1984 }
1985
1986 /**
1987 * try to receive a packet for 'packetwait' microseconds
1988 */
1989 static void
1990 ping_recv(pcap_t *pcap, uint32_t packetwait, pcap_handler func)
1991 {
1992 struct timespec ts;
1993 struct timespec endtime;
1994 char done = 0;
1995 int fd;
1996 unsigned int old_received;
1997
1998 if (send_reply) {
1999 if (verbose > 3) {
2000 printf("arping: sending replies. Waiting %"PRIdMAX" us…\n",
2001 (intmax_t)packetwait);
2002 }
2003 usleep(packetwait);
2004 return;
2005 }
2006
2007 if (verbose > 3) {
2008 printf("arping: receiving packets...\n");
2009 }
2010
2011 getclock(&ts);
2012 endtime.tv_sec = ts.tv_sec + (packetwait / 1000000);
2013 endtime.tv_nsec = ts.tv_nsec + 1000 * (packetwait % 1000000);
2014 fixup_timespec(&endtime);
2015
2016 fd = pcap_get_selectable_fd(pcap);
2017 if (fd == -1) {
2018 fprintf(stderr, "arping: pcap_get_selectable_fd()=-1: %s\n",
2019 pcap_geterr(pcap));
2020 exit(1);
2021 }
2022 if (fd >= FD_SETSIZE) {
2023 fprintf(stderr, "arping: pcap fd %d >= FD_SETSIZE (%d). Use a modern OS or report a bug.\n",
2024 fd, FD_SETSIZE);
2025 exit(1);
2026 }
2027 old_received = numrecvd;
2028
2029 for (;!done;) {
2030 int trydispatch = 0;
2031
2032 getclock(&ts);
2033 ts.tv_sec = endtime.tv_sec - ts.tv_sec;
2034 ts.tv_nsec = endtime.tv_nsec - ts.tv_nsec;
2035 fixup_timespec(&ts);
2036 if (verbose > 2) {
2037 printf("arping: listen for replies for %"PRIdMAX".%09"PRIdMAX" sec\n",
2038 (intmax_t)ts.tv_sec, (intmax_t)ts.tv_nsec);
2039 }
2040
2041 /* if time has passed, do one last check and then we're done.
2042 * this also triggers if not using monotonic clock and time
2043 * is set forwards */
2044 if (ts.tv_sec < 0) {
2045 ts.tv_sec = 0;
2046 ts.tv_nsec = 1;
2047 done = 1;
2048 }
2049
2050 /* if wait-for-packet time is longer than full period,
2051 * we're obviously not using a monotonic clock and the system
2052 * time has been changed.
2053 * we don't know how far we're into the waiting, so just end
2054 * it here */
2055 if ((ts.tv_sec > packetwait / 1000000)
2056 || ((ts.tv_sec == packetwait / 1000000)
2057 && (ts.tv_nsec/1000 > packetwait % 1000000))) {
2058 ts.tv_sec = 0;
2059 ts.tv_nsec = 1;
2060 done = 1;
2061 }
2062
2063 /* check for sigint */
2064 if (time_to_die) {
2065 return;
2066 }
2067
2068 /* try to wait for data */
2069 {
2070 fd_set fds;
2071 int r;
2072 struct timeval tv;
2073 tv.tv_sec = ts.tv_sec;
2074 tv.tv_usec = ts.tv_nsec / 1000;
2075
2076 FD_ZERO(&fds);
2077 FD_SET(fd, &fds);
2078
2079 r = select(fd + 1, &fds, NULL, NULL, &tv);
2080 switch (r) {
2081 case 0: /* timeout */
2082 if (numrecvd == old_received) {
2083 if (reverse_beep) {
2084 printf("\a");
2085 }
2086 switch (display) {
2087 case NORMAL:
2088 printf("Timeout\n");
2089 break;
2090 case DOT:
2091 printf(".");
2092 break;
2093 case RAW:
2094 case RAWRAW:
2095 case RRAW:
2096 case QUIET:
2097 break;
2098 }
2099 fflush(stdout);
2100 }
2101 done = 1;
2102 break;
2103 case -1: /* error */
2104 if (errno != EINTR) {
2105 done = 1;
2106 sigint(0);
2107 fprintf(stderr,
2108 "arping: select() failed: %s\n",
2109 strerror(errno));
2110 }
2111 break;
2112 default: /* data returned */
2113 trydispatch = 1;
2114 break;
2115 }
2116 }
2117 if (trydispatch) {
2118 int ret;
2119 if (0 > (ret = pcap_dispatch(pcap, -1,
2120 func,
2121 NULL))) {
2122 if (time_to_die) {
2123 return;
2124 }
2125 /* rest, so we don't take 100% CPU... mostly
2126 hmm... does usleep() exist everywhere? */
2127 usleep(1);
2128
2129 /* weird is normal on bsd :) */
2130 if (verbose > 3) {
2131 fprintf(stderr,
2132 "arping: select says ok, but "
2133 "pcap_dispatch=%d!\n",
2134 ret);
2135 }
2136 }
2137 }
2138 }
2139 }
2140
2141 // return 1 on success.
2142 static int
2143 xresolve(libnet_t* l, const char *name, uint8_t r, uint32_t *addr)
2144 {
2145 if (!strcmp(ip_broadcast, name)) {
2146 *addr = 0xffffffff;
2147 return 1;
2148 }
2149 *addr = libnet_name2addr4(l, (char*)name, r);
2150 return *addr != 0xffffffff;
2151 }
2152
2153 /**
2154 *
2155 */
2156 int
2157 arping_main(int argc, char **argv)
2158 {
2159 char ebuf[LIBNET_ERRBUF_SIZE + PCAP_ERRBUF_SIZE];
2160 char *cp;
2161 const char *srcip_opt = NULL;
2162 const char *dstip_opt = NULL;
2163 // `dstip_given` can be set even when there's no arg past flags on the
2164 // cmdline and -B not set. E.g. -d defaults to self, so requires no
2165 // extra arg.
2166 int dstip_given = 0;
2167 const char *srcmac_opt = NULL;
2168 const char *dstmac_opt = NULL;
2169 const char *ifname = NULL; // -i/-I
2170 int opt_B = 0;
2171 int opt_T = 0;
2172 int opt_U = 0;
2173 int c;
2174 const char* drop_group = NULL; // -g
2175 const char *parm; // First argument, meaning the target IP.
2176 int maxcount = -1;
2177 int dont_use_arping_lookupdev=0;
2178 struct bpf_program bp;
2179 pcap_t *pcap;
2180 enum { NONE, PINGMAC, PINGIP } mode = NONE;
2181 unsigned int packetwait = 1000000; // Default one second.
2182 double deadline = -1;
2183 char bpf_filter[64];
2184 ebuf[0] = 0;
2185 srandom((unsigned)time(NULL));
2186
2187 {
2188 int c;
2189 for (c = 1; c < argc; c++) {
2190 if (!strcmp(argv[c], "--help")) {
2191 standard_usage();
2192 extended_usage();
2193 exit(0);
2194 }
2195 }
2196 }
2197
2198 srcip = 0;
2199 dstip = 0xffffffff;
2200 memcpy(dstmac, ethxmas, ETH_ALEN);
2201
2202 while (EOF != (c = getopt(argc, argv,
2203 "0aAbBC:c:dDeFg:hi:I:m:pPqQ:rRs:S:t:T:uUvV:w:W:zZ"))) {
2204 switch(c) {
2205 case '0':
2206 srcip_opt = "0.0.0.0";
2207 break;
2208 case 'a':
2209 beep = 1;
2210 break;
2211 case 'A':
2212 addr_must_be_same = 1;
2213 break;
2214 case 'b':
2215 srcip_opt = ip_broadcast;
2216 break;
2217 case 'B':
2218 dstip_opt = ip_broadcast;
2219 dstip_given = 1;
2220 opt_B = 1;
2221 break;
2222 case 'c':
2223 maxcount = must_parse_int(optarg, "count (-c)");
2224 if (maxcount < 0) {
2225 fprintf(stderr,
2226 "arping: count (-c) must be >0. Got %d\n",
2227 maxcount);
2228 exit(1);
2229 }
2230 break;
2231 case 'C':
2232 max_replies = must_parse_uint(optarg,
2233 "max replies (-C)");
2234 break;
2235 case 'd':
2236 finddup = 1;
2237 break;
2238 case 'D':
2239 display = DOT;
2240 break;
2241 case 'e':
2242 reverse_beep = 1;
2243 break;
2244 case 'F':
2245 dont_use_arping_lookupdev=1;
2246 break;
2247 case 'h':
2248 usage(0);
2249 exit(0); // Needless but shuts up compiler warnings.
2250 case 'g':
2251 drop_group = optarg;
2252 break;
2253 case 'i':
2254 if (strchr(optarg, ':')) {
2255 fprintf(stderr, "arping: If you're trying to "
2256 "feed me an interface alias then you "
2257 "don't really\nknow what this programs"
2258 " does, do you?\nUse -I if you really"
2259 " mean it (undocumented on "
2260 "purpose)\n");
2261 exit(1);
2262 }
2263 ifname = optarg;
2264 break;
2265 case 'I':
2266 ifname = optarg;
2267 break;
2268 case 'm':
2269 timestamp_type = optarg;
2270 break;
2271 case 'p':
2272 promisc = 1;
2273 break;
2274 case 'P':
2275 send_reply = 1;
2276 break;
2277 case 'q':
2278 display = QUIET;
2279 break;
2280 case 'Q':
2281 vlan_prio = must_parse_int16(optarg, "802.1p prio (-Q)");
2282 if (vlan_prio < 0 || vlan_prio > 7) {
2283 fprintf(stderr,
2284 "arping: 802.1p priority must be 0-7. It's %d\n",
2285 vlan_prio);
2286 exit(1);
2287 }
2288 break;
2289 case 'r':
2290 display = (display==RRAW)?RAWRAW:RAW;
2291 break;
2292 case 'R':
2293 display = (display==RAW)?RAWRAW:RRAW;
2294 break;
2295 case 's': { /* spoof source MAC */
2296 srcmac_opt = optarg;
2297 break;
2298 }
2299 case 'S': /* set source IP, may be null for don't-know */
2300 srcip_opt = optarg;
2301 break;
2302 case 't': { /* set taget mac */
2303 dstmac_opt = optarg;
2304 mode = PINGIP;
2305 break;
2306 }
2307 case 'T': /* set destination IP */
2308 opt_T = 1;
2309 dstip_opt = optarg;
2310 mode = PINGMAC;
2311 break;
2312 case 'u':
2313 alsototal = 1;
2314 break;
2315 case 'U':
2316 opt_U = 1;
2317 unsolicited = 1;
2318 mode = PINGIP;
2319 break;
2320 case 'v':
2321 verbose++;
2322 break;
2323 case 'V':
2324 vlan_tag = must_parse_int16(optarg, "VLAN (-V)");
2325 if (vlan_tag < 0 || vlan_tag > 4095) {
2326 fprintf(stderr,
2327 "arping: vlan tag must be 0-4095. Is %d\n",
2328 vlan_tag);
2329 exit(1);
2330 }
2331 break;
2332 case 'w':
2333 deadline = must_parse_float(optarg, "deadline (-w)");
2334 if (deadline < 0 || !isfinite(deadline)) {
2335 fprintf(stderr,
2336 "arping: deadline (-w) must be finite value >=0. Is %f.\n",
2337 deadline);
2338 exit(1);
2339 }
2340 break;
2341 case 'W': {
2342 const float val = must_parse_float(optarg,
2343 "packetwait (-W)");
2344 if (val < 0.0) {
2345 fprintf(stderr,
2346 "arping: packetwait (-W) must be >=0. Is %f\n",
2347 val);
2348 exit(1);
2349 }
2350 // This overflows (asserts) if the user tries to wait
2351 // more than unsigned max number of us. And that's fine.
2352 packetwait = cast_float_unsigned(1000000.0f * val);
2353 break;
2354 }
2355 case 'z':
2356 use_seccomp = 1;
2357 break;
2358 case 'Z':
2359 use_seccomp = 0;
2360 break;
2361 default:
2362 usage(1);
2363 }
2364 }
2365
2366 if (argc - optind > 1) {
2367 // Can be zero if using -d or -B.
2368 fprintf(stderr, "arping: Too many args on command line."
2369 " Expected at most one.\n");
2370 exit(1);
2371 }
2372
2373 if (verbose > 2) {
2374 print_library_versions();
2375 }
2376
2377 // Generate random payload suffix for MAC pings, to be able to
2378 // differentiate from unrelated ping replies.
2379 payload_suffix = malloc(payload_suffix_size);
2380 if (!payload_suffix) {
2381 fprintf(stderr, "arping: failed to allocate %zu bytes for payload suffix.\n",
2382 payload_suffix_size);
2383 exit(1);
2384 }
2385
2386 // Create some default content.
2387 {
2388 const char* def = "arping/";
2389 for (size_t c = 0; c < payload_suffix_size; c++) {
2390 payload_suffix[c] = def[c % strlen(def)];
2391 }
2392 }
2393
2394 // Randomize should be even better.
2395 const ssize_t rc = xgetrandom(payload_suffix, payload_suffix_size, 0);
2396 if (rc < 0) {
2397 fprintf(stderr,
2398 "arping: failed to get %zu random bytes: %s\n",
2399 payload_suffix_size,
2400 strerror(errno));
2401 } else if (payload_suffix_size != cast_ssize_size(rc, NULL)) {
2402 fprintf(stderr,
2403 "arping: only got %zd out of %zu bytes for random suffix\n",
2404 rc, payload_suffix_size);
2405 }
2406
2407 if (((mode == PINGIP) && opt_T)
2408 || ((mode == PINGMAC) && (opt_B || dstmac_opt || opt_U))) {
2409 fprintf(stderr, "arping: -T can only be used to ping MAC"
2410 " and -BtU only to ping IPs\n");
2411 exit(1);
2412 }
2413 if (opt_T && opt_B) {
2414 fprintf(stderr,
2415 "arping: -B can't be used with -T,"
2416 " since they set the same thing\n");
2417 exit(1);
2418 }
2419
2420 if (srcmac_opt != NULL) {
2421 if (!get_mac_addr(srcmac_opt, srcmac)) {
2422 fprintf(stderr, "arping: Weird MAC addr %s\n",
2423 srcmac_opt);
2424 exit(1);
2425 }
2426 }
2427
2428 if (dstmac_opt != NULL) {
2429 if (!get_mac_addr(dstmac_opt, dstmac)) {
2430 fprintf(stderr, "Illegal MAC addr %s\n", dstmac_opt);
2431 exit(1);
2432 }
2433 }
2434
2435 if (srcip_opt != NULL) {
2436 do_libnet_init(ifname, 0);
2437 if (!xresolve(libnet, srcip_opt, LIBNET_RESOLVE, &srcip)) {
2438 fprintf(stderr, "arping: Can't resolve %s, or "
2439 "%s is broadcast. If it is, use -b"
2440 " instead of -S\n", srcip_opt,srcip_opt);
2441 exit(1);
2442 }
2443 }
2444
2445 if (dstip_opt) {
2446 do_libnet_init(ifname, 0);
2447 if (!xresolve(libnet, dstip_opt, LIBNET_RESOLVE, &dstip)) {
2448 fprintf(stderr,"arping: Can't resolve %s, or "
2449 "%s is broadcast. If it is, use -B "
2450 "instead of -T\n",dstip_opt,dstip_opt);
2451 exit(1);
2452 }
2453 }
2454
2455 if (vlan_prio >= 0 && vlan_tag == -1) {
2456 fprintf(stderr, "arping: -Q requires the use of 802.1Q (-V)\n");
2457 exit(1);
2458 }
2459 if (vlan_prio == -1) {
2460 vlan_prio = 0;
2461 }
2462
2463 if (verbose > 1) {
2464 #if HAVE_CLOCK_MONOTONIC
2465 struct timespec ts;
2466 if (clock_getres(CLOCK_MONOTONIC, &ts)) {
2467 fprintf(stderr,
2468 "arping: clock_getres(CLOCK_MONOTONIC, ...): %s\n",
2469 strerror(errno));
2470 } else {
2471 printf("arping: clock_getres() = %"PRIdMAX"s %"PRIdMAX"ns\n",
2472 (intmax_t)ts.tv_sec, (intmax_t)ts.tv_nsec);
2473 }
2474 #else
2475 printf("arping: Using gettimeofday() for time measurements\n");
2476 #endif
2477 }
2478
2479 if (display == DOT) {
2480 if (0 != setvbuf(stdout, NULL, _IONBF, 0)) {
2481 fprintf(stderr,
2482 "arping: setvbuf(stdout, NULL, IONBF, 0): %s\n",
2483 strerror(errno));
2484 }
2485 }
2486
2487 if (finddup && maxcount == -1) {
2488 maxcount = 3;
2489 }
2490
2491 parm = (optind < argc) ? argv[optind] : NULL;
2492 if (parm && dstip_given) {
2493 fprintf(stderr, "arping: options (e.g. -B) not compatible with specifying a destination.\n");
2494 exit(1);
2495 }
2496
2497 /* default to own IP address when doing -d */
2498 if (finddup && !parm) {
2499 dstip_given = 1;
2500 do_libnet_init(ifname, 0);
2501 dstip = libnet_get_ipaddr4(libnet);
2502 if (verbose) {
2503 printf("defaulting to checking dup for %s\n",
2504 libnet_addr2name4(dstip, 0));
2505 }
2506 }
2507
2508 /*
2509 * Handle dstip_given instead of ip address after parms (-B really)
2510 */
2511 if (mode == NONE) {
2512 if (parm) {
2513 mode = is_mac_addr(parm)?PINGMAC:PINGIP;
2514 } else if (dstip_given) {
2515 mode = PINGIP;
2516 do_libnet_init(ifname, 0);
2517 parm = strdup(libnet_addr2name4(dstip,0));
2518 if (!parm) {
2519 fprintf(stderr, "arping: out of memory\n");
2520 exit(1);
2521 }
2522 }
2523 }
2524
2525 if (!parm) {
2526 usage(1);
2527 }
2528
2529 if (send_reply && mode != PINGIP) {
2530 fprintf(stderr, "arping: -P can't be used with MAC destination.\n");
2531 exit(1);
2532 }
2533
2534 /*
2535 *
2536 */
2537 if (mode == NONE) {
2538 usage(1);
2539 }
2540
2541 /*
2542 * libnet init (may be done already for resolving)
2543 */
2544 do_libnet_init(ifname, 0);
2545 if (verbose > 1) {
2546 printf("arping: libnet_getfd(): %d\n", libnet_getfd(libnet));
2547 }
2548
2549 /*
2550 * Make sure dstip and parm like eachother
2551 */
2552 if (mode == PINGIP && (!dstip_given)) {
2553 if (is_mac_addr(parm)) {
2554 fprintf(stderr, "arping: Options given only apply to "
2555 "IP ping, but MAC address given as argument"
2556 "\n");
2557 exit(1);
2558 }
2559 if (!xresolve(libnet, parm, LIBNET_RESOLVE, &dstip)) {
2560 fprintf(stderr, "arping: Can't resolve %s\n", parm);
2561 exit(1);
2562 }
2563 parm = strdup(libnet_addr2name4(dstip,0));
2564 if (!parm) {
2565 fprintf(stderr, "arping: strdup of hostname failed\n");
2566 exit(1);
2567 }
2568 }
2569
2570 /*
2571 * parse parm into dstmac
2572 */
2573 if (mode == PINGMAC) {
2574 if (optind + 1 != argc) {
2575 usage(1);
2576 }
2577 if (!is_mac_addr(parm)) {
2578 fprintf(stderr, "arping: Options given only apply to "
2579 "MAC ping, but no MAC address given as "
2580 "argument\n");
2581 exit(1);
2582 }
2583 if (!get_mac_addr(argv[optind], dstmac)) {
2584 fprintf(stderr, "arping: Illegal mac addr %s\n",
2585 argv[optind]);
2586 return 1;
2587 }
2588 }
2589
2590 target = parm;
2591 /*
2592 * Argument processing done, parameters considered sane below
2593 */
2594
2595 /*
2596 * Get some good iface.
2597 */
2598 if (!ifname) {
2599 if (!dont_use_arping_lookupdev) {
2600 ifname = arping_lookupdev(srcip, dstip, ebuf);
2601 strip_newline(ebuf);
2602 if (!ifname) {
2603 fprintf(stderr, "arping: lookup dev: %s\n",
2604 ebuf);
2605 }
2606 }
2607 if (!ifname) {
2608 ifname = arping_lookupdev_default(srcip, dstip, ebuf);
2609 strip_newline(ebuf);
2610 if (ifname && !dont_use_arping_lookupdev) {
2611 fprintf(stderr,
2612 "arping: Unable to automatically find "
2613 "interface to use. Is it on the local "
2614 "LAN?\n"
2615 "arping: Use -i to manually "
2616 "specify interface. "
2617 "Guessing interface %s.\n", ifname);
2618 }
2619 }
2620 if (!ifname) {
2621 fprintf(stderr, "arping: Gave up looking for interface"
2622 " to use: %s\n", ebuf);
2623 exit(1);
2624 }
2625 /* FIXME: check for other probably-not interfaces */
2626 if (!strcmp(ifname, "ipsec")
2627 || !strcmp(ifname,"lo")) {
2628 fprintf(stderr, "arping: Um.. %s looks like the wrong "
2629 "interface to use. Is it? "
2630 "(-i switch)\n", ifname);
2631 fprintf(stderr, "arping: using it anyway this time\n");
2632 }
2633 }
2634
2635 /*
2636 * Init libnet again, because we now know the interface name.
2637 * We should know it by know at least
2638 */
2639 do_libnet_init(ifname, 0);
2640
2641 /*
2642 * pcap init
2643 */
2644 if (!(pcap = do_pcap_open_live(ifname, pcap_snaplen,
2645 pcap_timeout_ms, ebuf))) {
2646 strip_newline(ebuf);
2647 fprintf(stderr, "arping: pcap_open_live(): %s\n", ebuf);
2648 exit(1);
2649 }
2650 drop_privileges(drop_group);
2651 if (pcap_setnonblock(pcap, 1, ebuf)) {
2652 strip_newline(ebuf);
2653 fprintf(stderr, "arping: pcap_set_nonblock(): %s\n", ebuf);
2654 exit(1);
2655 }
2656 if (verbose > 1) {
2657 printf("arping: pcap_get_selectable_fd(): %d\n",
2658 pcap_get_selectable_fd(pcap));
2659 }
2660
2661 #ifdef BIOCIMMEDIATE
2662 {
2663 // This may be redundant if pcap_set_immediate_mode() is present.
2664 uint32_t on = 1;
2665 if (0 != (ioctl(pcap_fileno(pcap), BIOCIMMEDIATE,
2666 &on))) {
2667 fprintf(stderr, "arping: ioctl(fd,BIOCIMMEDIATE, 1) "
2668 "failed, continuing anyway, YMMV: %s\n",
2669 strerror(errno));
2670 }
2671 }
2672 #endif
2673
2674 if (vlan_tag >= 0 && bug_pcap_vlan() && verbose) {
2675 fprintf(stderr,
2676 "arping: Working around bug in libpcap 1.7-1.9.0.\n");
2677 }
2678
2679 if (mode == PINGIP) {
2680 /* FIXME: better filter with addresses? */
2681 if (vlan_tag >= 0 && !bug_pcap_vlan()) {
2682 xsnprintf(bpf_filter, sizeof(bpf_filter),
2683 "vlan %"PRId16" and arp", vlan_tag);
2684 } else {
2685 xsnprintf(bpf_filter, sizeof(bpf_filter), "arp");
2686 }
2687 if (-1 == pcap_compile(pcap, &bp, bpf_filter, 0,
2688 PCAP_NETMASK_UNKNOWN)) {
2689 fprintf(stderr, "arping: pcap_compile(%s): %s\n",
2690 bpf_filter, pcap_geterr(pcap));
2691 exit(1);
2692 }
2693 } else { /* ping mac */
2694 /* FIXME: better filter with addresses? */
2695 if (vlan_tag >= 0 && !bug_pcap_vlan()) {
2696 xsnprintf(bpf_filter, sizeof(bpf_filter),
2697 "vlan %"PRId16" and icmp", vlan_tag);
2698 } else {
2699 xsnprintf(bpf_filter, sizeof(bpf_filter), "icmp");
2700 }
2701 if (-1 == pcap_compile(pcap, &bp, bpf_filter, 0,
2702 PCAP_NETMASK_UNKNOWN)) {
2703 fprintf(stderr, "arping: pcap_compile(%s): %s\n",
2704 bpf_filter, pcap_geterr(pcap));
2705 exit(1);
2706 }
2707 }
2708 if (-1 == pcap_setfilter(pcap, &bp)) {
2709 fprintf(stderr, "arping: pcap_setfilter(): %s\n",
2710 pcap_geterr(pcap));
2711 exit(1);
2712 }
2713
2714 /*
2715 * final init
2716 */
2717 if (srcmac_opt == NULL) {
2718 if (!(cp = (char*)libnet_get_hwaddr(libnet))) {
2719 fprintf(stderr, "arping: libnet_get_hwaddr(): %s\n",
2720 libnet_geterror(libnet));
2721 exit(1);
2722 }
2723 memcpy(srcmac, cp, ETH_ALEN);
2724 }
2725 if (srcip_opt == NULL) {
2726 if (ip_broadcast_num == (srcip = libnet_get_ipaddr4(libnet))) {
2727 fprintf(stderr,
2728 "arping: Unable to get the IPv4 address of "
2729 "interface %s:\narping: %s"
2730 "arping: "
2731 "Use -S to specify address manually.\n",
2732 ifname, libnet_geterror(libnet));
2733 exit(1);
2734 }
2735 }
2736 do_signal_init();
2737
2738 if (verbose) {
2739 char buf[128];
2740 printf("This box: Interface: %s IP: %s MAC address: %s\n",
2741 ifname,
2742 libnet_addr2name4(libnet_get_ipaddr4(libnet), 0),
2743 format_mac(srcmac, buf, sizeof(buf)));
2744 }
2745
2746 drop_more_privileges(libnet_getfd(libnet));
2747
2748 if (display == NORMAL) {
2749 printf("ARPING %s\n", parm);
2750 }
2751
2752 /*
2753 * let's roll
2754 */
2755 if (deadline > 0) {
2756 struct timespec ts;
2757 getclock(&ts);
2758 deadline += timespec2dbl(&ts);
2759 }
2760 if (mode == PINGIP) {
2761 int c;
2762 for (c = 0; (maxcount < 0 || c < maxcount); c++) {
2763 if (time_to_die) {
2764 break;
2765 }
2766 if (c == INT_MAX) {
2767 --c;
2768 }
2769 pingip_send();
2770 if (max_replies != UINT_MAX && numrecvd >= max_replies) {
2771 break;
2772 }
2773 const uint32_t w = wait_time(deadline, packetwait);
2774 if (w == 0) {
2775 break;
2776 }
2777 ping_recv(pcap, w, (pcap_handler)pingip_recv);
2778 }
2779 } else { /* PINGMAC */
2780 int c;
2781 for (c = 0; (maxcount < 0 || c < maxcount); c++) {
2782 if (time_to_die) {
2783 break;
2784 }
2785 if (c == INT_MAX) {
2786 --c;
2787 }
2788 pingmac_send(xrandom16(),
2789 cast_int_uint16(c & 0xffff, NULL));
2790 if (max_replies != UINT_MAX && numrecvd >= max_replies) {
2791 break;
2792 }
2793 const uint32_t w = wait_time(deadline, packetwait);
2794 if (w == 0) {
2795 break;
2796 }
2797 ping_recv(pcap, w, (pcap_handler)pingmac_recv);
2798 }
2799 }
2800 if (display == DOT) {
2801 double succ = 0.0;
2802 if (numsent > 0) {
2803 succ = 100.0 - 100.0 * (double)(numrecvd)/(double)numsent;
2804 }
2805 printf("\t%3.0f%% packet loss (%u extra)\n",
2806 (succ < 0.0) ? 0.0 : succ,
2807 (succ < 0.0) ? (numrecvd - numsent) : 0);
2808 } else if (display == NORMAL) {
2809 double succ = 0.0;
2810 if (numsent > 0) {
2811 succ = 100.0 - 100.0 * (double)(numrecvd)/(double)numsent;
2812 }
2813 printf("\n--- %s statistics ---\n"
2814 "%u packets transmitted, "
2815 "%u packets received, "
2816 "%3.0f%% "
2817 "unanswered (%u extra)\n",
2818 target,numsent,numrecvd,
2819 (succ < 0.0) ? 0.0 : succ,
2820 (succ < 0.0) ? (numrecvd - numsent): 0);
2821 if (numrecvd) {
2822 double avg = stats_total_time / numrecvd;
2823 double stddev2 = stats_total_sq_time/numrecvd-avg*avg;
2824 if (stddev2 < 0.0) {
2825 // Due to floating point precision, this could be negative.
2826 stddev2 = 0.0;
2827 }
2828
2829 printf("rtt min/avg/max/std-dev = "
2830 "%.3f/%.3f/%.3f/%.3f ms",
2831 1000*stats_min_time,
2832 1000*avg,
2833 1000*stats_max_time,
2834 1000*sqrt(stddev2));
2835 }
2836 printf("\n");
2837 }
2838
2839 if (fflush(stdout)) {
2840 fprintf(stderr, "arping: Failed to write to stdout: %s\n",
2841 strerror(errno));
2842 return EXIT_FAILURE;
2843 }
2844
2845 if (ferror(stdout)) {
2846 fprintf(stderr, "arping: Write failure to stdout: %s\n",
2847 strerror(errno));
2848 return EXIT_FAILURE;
2849 }
2850
2851 if (fflush(stderr)) {
2852 // Likely this will go nowhere. But we can't write to
2853 // stdout in case it's being machine parsed.
2854 //
2855 // At least it should show up in strace.
2856 fprintf(stderr, "arping: Failed to write to stderr: %s\n",
2857 strerror(errno));
2858 return EXIT_FAILURE;
2859 }
2860
2861 if (ferror(stderr)) {
2862 // Same here. Likely will go nowhere.
2863 fprintf(stderr, "arping: Write failure to stderr: %s\n",
2864 strerror(errno));
2865 return EXIT_FAILURE;
2866 }
2867
2868 // We could close stdout/stdin too, but that'll interfere with
2869 // unit testing.
2870
2871 if (finddup) {
2872 return dupfound;
2873 }
2874 if (libnet_write_failures > 0) {
2875 return EXIT_FAILURE;
2876 }
2877 if ((numrecvd > 0) || send_reply) {
2878 return EXIT_SUCCESS;
2879 }
2880 return EXIT_FAILURE;
2881 }
2882 /* ---- Emacs Variables ----
2883 * Local Variables:
2884 * c-basic-offset: 8
2885 * indent-tabs-mode: nil
2886 * End:
2887 *
2888 * vim: ts=8 sw=8
2889 */