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