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