4f1a2e2c5a50e8ecd70365b0f826de7ba1798fa3
[oweals/busybox.git] / networking / arping.c
1 /* vi:set 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 <sys/ioctl.h>
12 #include <signal.h>
13 #include <sys/time.h>
14
15 #include <errno.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <unistd.h>
19
20 #include <arpa/inet.h>
21 #include <net/if.h>
22 #include <netinet/ether.h>
23 #include <netpacket/packet.h>
24
25 #include "busybox.h"
26
27 static struct in_addr src;
28 static struct in_addr dst;
29 static struct sockaddr_ll me;
30 static struct sockaddr_ll he;
31 static struct timeval last;
32
33 enum cfg_e {
34         dad = 1,
35         unsolicited = 2,
36         advert = 4,
37         quiet = 8,
38         quit_on_reply = 16,
39         unicasting = 32,
40         broadcast_only = 64
41 };
42 static int cfg;
43
44 static int s;
45 static int count = -1;
46 static int timeout;
47 static int sent;
48 static int brd_sent;
49 static int received;
50 static int brd_recv;
51 static int req_recv;
52
53
54 #define MS_TDIFF(tv1,tv2) ( ((tv1).tv_sec-(tv2).tv_sec)*1000 + \
55                            ((tv1).tv_usec-(tv2).tv_usec)/1000 )
56 #if 0
57 static void set_signal(int signo, void (*handler) (void))
58 {
59         struct sigaction sa;
60
61         memset(&sa, 0, sizeof(sa));
62         sa.sa_handler = (void (*)(int)) handler;
63         sa.sa_flags = SA_RESTART;
64         sigaction(signo, &sa, NULL);
65 }
66 #endif
67
68 static int send_pack(int sock, struct in_addr *src_addr,
69                                          struct in_addr *dst_addr, struct sockaddr_ll *ME,
70                                          struct sockaddr_ll *HE)
71 {
72         int err;
73         struct timeval now;
74         RESERVE_CONFIG_UBUFFER(buf, 256);
75         struct arphdr *ah = (struct arphdr *) buf;
76         unsigned char *p = (unsigned char *) (ah + 1);
77
78         ah->ar_hrd = htons(ME->sll_hatype);
79         ah->ar_hrd = htons(ARPHRD_ETHER);
80         ah->ar_pro = htons(ETH_P_IP);
81         ah->ar_hln = ME->sll_halen;
82         ah->ar_pln = 4;
83         ah->ar_op = cfg&advert ? htons(ARPOP_REPLY) : htons(ARPOP_REQUEST);
84
85         memcpy(p, &ME->sll_addr, ah->ar_hln);
86         p += ME->sll_halen;
87
88         memcpy(p, src_addr, 4);
89         p += 4;
90
91         if (cfg&advert)
92                 memcpy(p, &ME->sll_addr, ah->ar_hln);
93         else
94                 memcpy(p, &HE->sll_addr, ah->ar_hln);
95         p += ah->ar_hln;
96
97         memcpy(p, dst_addr, 4);
98         p += 4;
99
100         gettimeofday(&now, NULL);
101         err = sendto(sock, buf, p - buf, 0, (struct sockaddr *) HE, sizeof(*HE));
102         if (err == p - buf) {
103                 last = now;
104                 sent++;
105                 if (!(cfg&unicasting))
106                         brd_sent++;
107         }
108         RELEASE_CONFIG_BUFFER(buf);
109         return err;
110 }
111
112 static void finish(void)
113 {
114         if (!(cfg&quiet)) {
115                 printf("Sent %d probes (%d broadcast(s))\n", sent, brd_sent);
116                 printf("Received %d repl%s", received, (received > 1) ? "ies" : "y");
117                 if (brd_recv || req_recv) {
118                         printf(" (");
119                         if (req_recv)
120                                 printf("%d request(s)", req_recv);
121                         if (brd_recv)
122                                 printf("%s%d broadcast(s)", req_recv ? ", " : "", brd_recv);
123                         putchar(')');
124                 }
125                 putchar('\n');
126                 fflush(stdout);
127         }
128         if (cfg&dad)
129                 exit(!!received);
130         if (cfg&unsolicited)
131                 exit(0);
132         exit(!received);
133 }
134
135 static void catcher(void)
136 {
137         struct timeval tv;
138         static struct timeval start;
139
140         gettimeofday(&tv, NULL);
141
142         if (start.tv_sec == 0)
143                 start = tv;
144
145         if (count-- == 0
146                 || (timeout && MS_TDIFF(tv, start) > timeout * 1000 + 500))
147                 finish();
148
149         if (last.tv_sec == 0 || MS_TDIFF(tv, last) > 500) {
150                 send_pack(s, &src, &dst, &me, &he);
151                 if (count == 0 && cfg&unsolicited)
152                         finish();
153         }
154         alarm(1);
155 }
156
157 static int recv_pack(unsigned char *buf, int len, struct sockaddr_ll *FROM)
158 {
159         struct arphdr *ah = (struct arphdr *) buf;
160         unsigned char *p = (unsigned char *) (ah + 1);
161         struct in_addr src_ip, dst_ip;
162
163         /* Filter out wild packets */
164         if (FROM->sll_pkttype != PACKET_HOST &&
165                 FROM->sll_pkttype != PACKET_BROADCAST &&
166                 FROM->sll_pkttype != PACKET_MULTICAST)
167                 return 0;
168
169         /* Only these types are recognised */
170         if (ah->ar_op != htons(ARPOP_REQUEST) && ah->ar_op != htons(ARPOP_REPLY))
171                 return 0;
172
173         /* ARPHRD check and this darned FDDI hack here :-( */
174         if (ah->ar_hrd != htons(FROM->sll_hatype) &&
175                 (FROM->sll_hatype != ARPHRD_FDDI
176                  || ah->ar_hrd != htons(ARPHRD_ETHER)))
177                 return 0;
178
179         /* Protocol must be IP. */
180         if (ah->ar_pro != htons(ETH_P_IP))
181                 return 0;
182         if (ah->ar_pln != 4)
183                 return 0;
184         if (ah->ar_hln != me.sll_halen)
185                 return 0;
186         if (len < sizeof(*ah) + 2 * (4 + ah->ar_hln))
187                 return 0;
188         memcpy(&src_ip, p + ah->ar_hln, 4);
189         memcpy(&dst_ip, p + ah->ar_hln + 4 + ah->ar_hln, 4);
190         if (!(cfg&dad)) {
191                 if (src_ip.s_addr != dst.s_addr)
192                         return 0;
193                 if (src.s_addr != dst_ip.s_addr)
194                         return 0;
195                 if (memcmp(p + ah->ar_hln + 4, &me.sll_addr, ah->ar_hln))
196                         return 0;
197         } else {
198                 /* DAD packet was:
199                    src_ip = 0 (or some src)
200                    src_hw = ME
201                    dst_ip = tested address
202                    dst_hw = <unspec>
203
204                    We fail, if receive request/reply with:
205                    src_ip = tested_address
206                    src_hw != ME
207                    if src_ip in request was not zero, check
208                    also that it matches to dst_ip, otherwise
209                    dst_ip/dst_hw do not matter.
210                  */
211                 if (src_ip.s_addr != dst.s_addr)
212                         return 0;
213                 if (memcmp(p, &me.sll_addr, me.sll_halen) == 0)
214                         return 0;
215                 if (src.s_addr && src.s_addr != dst_ip.s_addr)
216                         return 0;
217         }
218         if (!(cfg&quiet)) {
219                 int s_printed = 0;
220                 struct timeval tv;
221
222                 gettimeofday(&tv, NULL);
223
224                 printf("%s ",
225                            FROM->sll_pkttype == PACKET_HOST ? "Unicast" : "Broadcast");
226                 printf("%s from ",
227                            ah->ar_op == htons(ARPOP_REPLY) ? "reply" : "request");
228                 printf("%s ", inet_ntoa(src_ip));
229                 printf("[%s]", ether_ntoa((struct ether_addr *) p));
230                 if (dst_ip.s_addr != src.s_addr) {
231                         printf("for %s ", inet_ntoa(dst_ip));
232                         s_printed = 1;
233                 }
234                 if (memcmp(p + ah->ar_hln + 4, me.sll_addr, ah->ar_hln)) {
235                         if (!s_printed)
236                                 printf("for ");
237                         printf("[%s]",
238                                    ether_ntoa((struct ether_addr *) p + ah->ar_hln + 4));
239                 }
240
241                 if (last.tv_sec) {
242                         long usecs = (tv.tv_sec - last.tv_sec) * 1000000 +
243                                 tv.tv_usec - last.tv_usec;
244                         long msecs = (usecs + 500) / 1000;
245
246                         usecs -= msecs * 1000 - 500;
247                         printf(" %ld.%03ldms\n", msecs, usecs);
248                 } else {
249                         printf(" UNSOLICITED?\n");
250                 }
251                 fflush(stdout);
252         }
253         received++;
254         if (FROM->sll_pkttype != PACKET_HOST)
255                 brd_recv++;
256         if (ah->ar_op == htons(ARPOP_REQUEST))
257                 req_recv++;
258         if (cfg&quit_on_reply)
259                 finish();
260         if (!(cfg&broadcast_only)) {
261                 memcpy(he.sll_addr, p, me.sll_halen);
262                 cfg |= unicasting;
263         }
264         return 1;
265 }
266
267 int arping_main(int argc, char **argv)
268 {
269         char *device = "eth0";
270         int ifindex;
271         char *source = NULL;
272         char *target;
273
274         s = socket(PF_PACKET, SOCK_DGRAM, 0);
275         ifindex = errno;
276
277         setuid(getuid());
278
279         {
280                 unsigned long opt;
281                 char *_count, *_timeout, *_device;
282                 opt = bb_getopt_ulflags(argc, argv, "DUAqfbc:w:i:s:",
283                                                 &_count, &_timeout, &_device);
284                 if (opt & 1) { /* Dad */
285                         cfg |= dad;
286                         cfg |= quit_on_reply;
287                 }
288                 if (opt & 2) /* Unsolicited */
289                         cfg |= unsolicited;
290                 if (opt & 4) { /* Advert */
291                         cfg |= advert;
292                         cfg |= unsolicited;
293                 }
294                 if (opt & 8) /* quiet */
295                         cfg |= quiet;
296                 if (opt & 16) /* quit on reply */
297                         cfg |= quit_on_reply;
298                 if (opt & 32) /* broadcast only */
299                         cfg |= broadcast_only;
300                 if (opt & 64) /* count */
301                         count = atoi(_count);
302                 if (opt & 128) /* timeout */
303                         timeout = atoi(_timeout);
304                 if (opt & 256) { /* interface */
305                         if (bb_strlen(_device) > IF_NAMESIZE) {
306                                 bb_error_msg_and_die("Interface name `%s' must be less than %d",
307                                                                 _device, IF_NAMESIZE);
308                         }
309                         device = _device;
310                 }
311                 if (opt & 512) /* source */
312                         source = optarg;
313         }
314         argc -= optind;
315         argv += optind;
316
317         if (argc != 1)
318                 bb_show_usage();
319
320         target = *argv;
321
322
323         if (s < 0) {
324                 bb_default_error_retval = ifindex;
325                 bb_perror_msg_and_die("socket");
326         }
327         bb_default_error_retval = 2;
328
329         {
330                 struct ifreq ifr;
331
332                 memset(&ifr, 0, sizeof(ifr));
333                 strncpy(ifr.ifr_name, device, IFNAMSIZ - 1);
334                 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
335                         bb_error_msg_and_die("Interface %s not found", device);
336                 }
337                 ifindex = ifr.ifr_ifindex;
338
339                 if (ioctl(s, SIOCGIFFLAGS, (char *) &ifr)) {
340                         bb_error_msg_and_die("SIOCGIFFLAGS");
341                 }
342                 if (!(ifr.ifr_flags & IFF_UP)) {
343                         bb_error_msg_and_die("Interface %s is down", device);
344                 }
345                 if (ifr.ifr_flags & (IFF_NOARP | IFF_LOOPBACK)) {
346                         bb_error_msg("Interface %s is not ARPable", device);
347                         exit(cfg&dad ? 0 : 2);
348                 }
349         }
350
351         if (!inet_aton(target, &dst)) {
352                 struct hostent *hp;
353
354                 hp = gethostbyname2(target, AF_INET);
355                 if (!hp) {
356                         bb_error_msg_and_die("invalid or unknown target %s", target);
357                 }
358                 memcpy(&dst, hp->h_addr, 4);
359         }
360
361         if (source && !inet_aton(source, &src)) {
362                 bb_error_msg_and_die("invalid source address %s", source);
363         }
364
365         if (!(cfg&dad) && cfg&unsolicited && src.s_addr == 0)
366                 src = dst;
367
368         if (!(cfg&dad) || src.s_addr) {
369                 struct sockaddr_in saddr;
370                 int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
371
372                 if (probe_fd < 0) {
373                         bb_error_msg_and_die("socket");
374                 }
375                 if (device) {
376                         if (setsockopt
377                                 (probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device,
378                                  strlen(device) + 1) == -1)
379                                 bb_error_msg("WARNING: interface %s is ignored", device);
380                 }
381                 memset(&saddr, 0, sizeof(saddr));
382                 saddr.sin_family = AF_INET;
383                 if (src.s_addr) {
384                         saddr.sin_addr = src;
385                         if (bind(probe_fd, (struct sockaddr *) &saddr, sizeof(saddr)) == -1) {
386                                 bb_error_msg_and_die("bind");
387                         }
388                 } else if (!(cfg&dad)) {
389                         int on = 1;
390                         socklen_t alen = sizeof(saddr);
391
392                         saddr.sin_port = htons(1025);
393                         saddr.sin_addr = dst;
394
395                         if (setsockopt
396                                 (probe_fd, SOL_SOCKET, SO_DONTROUTE, (char *) &on,
397                                  sizeof(on)) == -1)
398                                 bb_perror_msg("WARNING: setsockopt(SO_DONTROUTE)");
399                         if (connect(probe_fd, (struct sockaddr *) &saddr, sizeof(saddr))
400                                 == -1) {
401                                 bb_error_msg_and_die("connect");
402                         }
403                         if (getsockname(probe_fd, (struct sockaddr *) &saddr, &alen) ==
404                                 -1) {
405                                 bb_error_msg_and_die("getsockname");
406                         }
407                         src = saddr.sin_addr;
408                 }
409                 close(probe_fd);
410         };
411
412         me.sll_family = AF_PACKET;
413         me.sll_ifindex = ifindex;
414         me.sll_protocol = htons(ETH_P_ARP);
415         if (bind(s, (struct sockaddr *) &me, sizeof(me)) == -1) {
416                 bb_error_msg_and_die("bind");
417         }
418
419         {
420                 socklen_t alen = sizeof(me);
421
422                 if (getsockname(s, (struct sockaddr *) &me, &alen) == -1) {
423                         bb_error_msg_and_die("getsockname");
424                 }
425         }
426         if (me.sll_halen == 0) {
427                 bb_error_msg("Interface \"%s\" is not ARPable (no ll address)", device);
428                 exit(cfg&dad ? 0 : 2);
429         }
430         he = me;
431         memset(he.sll_addr, -1, he.sll_halen);
432
433         if (!(cfg&quiet)) {
434                 printf("ARPING to %s", inet_ntoa(dst));
435                 printf(" from %s via %s\n", inet_ntoa(src),
436                            device ? device : "unknown");
437         }
438
439         if (!src.s_addr && !(cfg&dad)) {
440                 bb_error_msg_and_die("no src address in the non-DAD mode");
441         }
442
443         {
444                 struct sigaction sa;
445
446                 memset(&sa, 0, sizeof(sa));
447                 sa.sa_flags = SA_RESTART;
448
449                 sa.sa_handler = (void (*)(int)) finish;
450                 sigaction(SIGINT, &sa, NULL);
451
452                 sa.sa_handler = (void (*)(int)) catcher;
453                 sigaction(SIGALRM, &sa, NULL);
454         }
455
456         catcher();
457
458         while (1) {
459                 sigset_t sset, osset;
460                 RESERVE_CONFIG_UBUFFER(packet, 4096);
461                 struct sockaddr_ll from;
462                 socklen_t alen = sizeof(from);
463                 int cc;
464
465                 if ((cc = recvfrom(s, packet, 4096, 0,
466                                                    (struct sockaddr *) &from, &alen)) < 0) {
467                         perror("recvfrom");
468                         continue;
469                 }
470                 sigemptyset(&sset);
471                 sigaddset(&sset, SIGALRM);
472                 sigaddset(&sset, SIGINT);
473                 sigprocmask(SIG_BLOCK, &sset, &osset);
474                 recv_pack(packet, cc, &from);
475                 sigprocmask(SIG_SETMASK, &osset, NULL);
476                 RELEASE_CONFIG_BUFFER(packet);
477         }
478 }