Initial public busybox upstream commit
[busybox4maemo] / 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 static int send_pack(struct in_addr *src_addr,
70                         struct in_addr *dst_addr, struct sockaddr_ll *ME,
71                         struct sockaddr_ll *HE)
72 {
73         int err;
74         unsigned char 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 = option_mask32 & 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 (option_mask32 & 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         err = sendto(sock_fd, buf, p - buf, 0, (struct sockaddr *) HE, sizeof(*HE));
101         if (err == p - buf) {
102                 last = MONOTONIC_US();
103                 sent++;
104                 if (!(option_mask32 & UNICASTING))
105                         brd_sent++;
106         }
107         return err;
108 }
109
110 static void finish(void) ATTRIBUTE_NORETURN;
111 static void finish(void)
112 {
113         if (!(option_mask32 & QUIET)) {
114                 printf("Sent %u probe(s) (%u broadcast(s))\n"
115                         "Received %u repl%s"
116                         " (%u request(s), %u broadcast(s))\n",
117                         sent, brd_sent,
118                         received, (received == 1) ? "ies" : "y",
119                         req_recv, brd_recv);
120         }
121         if (option_mask32 & DAD)
122                 exit(!!received);
123         if (option_mask32 & UNSOLICITED)
124                 exit(EXIT_SUCCESS);
125         exit(!received);
126 }
127
128 static void catcher(void)
129 {
130         unsigned now;
131
132         now = MONOTONIC_US();
133         if (start == 0)
134                 start = now;
135
136         if (count == 0 || (timeout_us && (now - start) > timeout_us))
137                 finish();
138
139         /* count < 0 means "infinite count" */
140         if (count > 0)
141                 count--;
142
143         if (last == 0 || (now - last) > 500000) {
144                 send_pack(&src, &dst, &me, &he);
145                 if (count == 0 && (option_mask32 & UNSOLICITED))
146                         finish();
147         }
148         alarm(1);
149 }
150
151 static bool recv_pack(unsigned char *buf, int len, struct sockaddr_ll *FROM)
152 {
153         struct arphdr *ah = (struct arphdr *) buf;
154         unsigned char *p = (unsigned char *) (ah + 1);
155         struct in_addr src_ip, dst_ip;
156
157         /* Filter out wild packets */
158         if (FROM->sll_pkttype != PACKET_HOST
159          && FROM->sll_pkttype != PACKET_BROADCAST
160          && FROM->sll_pkttype != PACKET_MULTICAST)
161                 return false;
162
163         /* Only these types are recognised */
164         if (ah->ar_op != htons(ARPOP_REQUEST) && ah->ar_op != htons(ARPOP_REPLY))
165                 return false;
166
167         /* ARPHRD check and this darned FDDI hack here :-( */
168         if (ah->ar_hrd != htons(FROM->sll_hatype)
169          && (FROM->sll_hatype != ARPHRD_FDDI || ah->ar_hrd != htons(ARPHRD_ETHER)))
170                 return false;
171
172         /* Protocol must be IP. */
173         if (ah->ar_pro != htons(ETH_P_IP)
174                 || (ah->ar_pln != 4)
175                 || (ah->ar_hln != me.sll_halen)
176                 || (len < sizeof(*ah) + 2 * (4 + ah->ar_hln)))
177                 return false;
178
179         memcpy(&src_ip, p + ah->ar_hln, 4);
180         memcpy(&dst_ip, p + ah->ar_hln + 4 + ah->ar_hln, 4);
181
182         if (dst.s_addr != src_ip.s_addr)
183                 return false;
184         if (!(option_mask32 & DAD)) {
185                 if ((src.s_addr != dst_ip.s_addr)
186                         || (memcmp(p + ah->ar_hln + 4, &me.sll_addr, ah->ar_hln)))
187                         return false;
188         } else {
189                 /* DAD packet was:
190                    src_ip = 0 (or some src)
191                    src_hw = ME
192                    dst_ip = tested address
193                    dst_hw = <unspec>
194
195                    We fail, if receive request/reply with:
196                    src_ip = tested_address
197                    src_hw != ME
198                    if src_ip in request was not zero, check
199                    also that it matches to dst_ip, otherwise
200                    dst_ip/dst_hw do not matter.
201                  */
202                 if ((memcmp(p, &me.sll_addr, me.sll_halen) == 0)
203                         || (src.s_addr && src.s_addr != dst_ip.s_addr))
204                         return false;
205         }
206         if (!(option_mask32 & QUIET)) {
207                 int s_printed = 0;
208
209                 printf("%scast re%s from %s [%s]",
210                         FROM->sll_pkttype == PACKET_HOST ? "Uni" : "Broad",
211                         ah->ar_op == htons(ARPOP_REPLY) ? "ply" : "quest",
212                         inet_ntoa(src_ip),
213                         ether_ntoa((struct ether_addr *) p));
214                 if (dst_ip.s_addr != src.s_addr) {
215                         printf("for %s ", inet_ntoa(dst_ip));
216                         s_printed = 1;
217                 }
218                 if (memcmp(p + ah->ar_hln + 4, me.sll_addr, ah->ar_hln)) {
219                         if (!s_printed)
220                                 printf("for ");
221                         printf("[%s]",
222                                 ether_ntoa((struct ether_addr *) p + ah->ar_hln + 4));
223                 }
224
225                 if (last) {
226                         unsigned diff = MONOTONIC_US() - last;
227                         printf(" %u.%03ums\n", diff / 1000, diff % 1000);
228                 } else {
229                         printf(" UNSOLICITED?\n");
230                 }
231                 fflush(stdout);
232         }
233         received++;
234         if (FROM->sll_pkttype != PACKET_HOST)
235                 brd_recv++;
236         if (ah->ar_op == htons(ARPOP_REQUEST))
237                 req_recv++;
238         if (option_mask32 & QUIT_ON_REPLY)
239                 finish();
240         if (!(option_mask32 & BCAST_ONLY)) {
241                 memcpy(he.sll_addr, p, me.sll_halen);
242                 option_mask32 |= UNICASTING;
243         }
244         return true;
245 }
246
247 int arping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
248 int arping_main(int argc ATTRIBUTE_UNUSED, char **argv)
249 {
250         const char *device = "eth0";
251         char *source = NULL;
252         char *target;
253         unsigned char *packet;
254         char *err_str;
255
256         INIT_G();
257
258         sock_fd = xsocket(AF_PACKET, SOCK_DGRAM, 0);
259
260         // Drop suid root privileges
261         // Need to remove SUID_NEVER from applets.h for this to work
262         //xsetuid(getuid());
263
264         err_str = xasprintf("interface %s %%s", device);
265         {
266                 unsigned opt;
267                 char *str_timeout;
268
269                 /* Dad also sets quit_on_reply.
270                  * Advert also sets unsolicited.
271                  */
272                 opt_complementary = "=1:Df:AU:c+";
273                 opt = getopt32(argv, "DUAqfbc:w:I:s:",
274                                 &count, &str_timeout, &device, &source);
275                 if (opt & 0x80) /* -w: timeout */
276                         timeout_us = xatou_range(str_timeout, 0, INT_MAX/2000000) * 1000000 + 500000;
277                 //if (opt & 0x200) /* -s: source */
278                 option_mask32 &= 0x3f; /* set respective flags */
279         }
280
281         target = argv[optind];
282
283         xfunc_error_retval = 2;
284
285         {
286                 struct ifreq ifr;
287
288                 memset(&ifr, 0, sizeof(ifr));
289                 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name) - 1);
290                 /* We use ifr.ifr_name in error msg so that problem
291                  * with truncated name will be visible */
292                 ioctl_or_perror_and_die(sock_fd, SIOCGIFINDEX, &ifr, err_str, "not found");
293                 me.sll_ifindex = ifr.ifr_ifindex;
294
295                 xioctl(sock_fd, SIOCGIFFLAGS, (char *) &ifr);
296
297                 if (!(ifr.ifr_flags & IFF_UP)) {
298                         bb_error_msg_and_die(err_str, "is down");
299                 }
300                 if (ifr.ifr_flags & (IFF_NOARP | IFF_LOOPBACK)) {
301                         bb_error_msg(err_str, "is not ARPable");
302                         return (option_mask32 & DAD ? 0 : 2);
303                 }
304         }
305
306         /* if (!inet_aton(target, &dst)) - not needed */ {
307                 len_and_sockaddr *lsa;
308                 lsa = xhost_and_af2sockaddr(target, 0, AF_INET);
309                 memcpy(&dst, &lsa->u.sin.sin_addr.s_addr, 4);
310                 if (ENABLE_FEATURE_CLEAN_UP)
311                         free(lsa);
312         }
313
314         if (source && !inet_aton(source, &src)) {
315                 bb_error_msg_and_die("invalid source address %s", source);
316         }
317
318         if ((option_mask32 & (DAD|UNSOLICITED)) == UNSOLICITED && src.s_addr == 0)
319                 src = dst;
320
321         if (!(option_mask32 & DAD) || src.s_addr) {
322                 struct sockaddr_in saddr;
323                 int probe_fd = xsocket(AF_INET, SOCK_DGRAM, 0);
324
325                 if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device) + 1) == -1)
326                         bb_perror_msg("cannot bind to device %s", device);
327                 memset(&saddr, 0, sizeof(saddr));
328                 saddr.sin_family = AF_INET;
329                 if (src.s_addr) {
330                         /* Check that this is indeed our IP */
331                         saddr.sin_addr = src;
332                         xbind(probe_fd, (struct sockaddr *) &saddr, sizeof(saddr));
333                 } else { /* !(option_mask32 & DAD) case */
334                         /* Find IP address on this iface */
335                         socklen_t alen = sizeof(saddr);
336
337                         saddr.sin_port = htons(1025);
338                         saddr.sin_addr = dst;
339
340                         if (setsockopt(probe_fd, SOL_SOCKET, SO_DONTROUTE, &const_int_1, sizeof(const_int_1)) == -1)
341                                 bb_perror_msg("setsockopt(SO_DONTROUTE)");
342                         xconnect(probe_fd, (struct sockaddr *) &saddr, sizeof(saddr));
343                         if (getsockname(probe_fd, (struct sockaddr *) &saddr, &alen) == -1) {
344                                 bb_perror_msg_and_die("getsockname");
345                         }
346                         if (saddr.sin_family != AF_INET)
347                                 bb_error_msg_and_die("no IP address configured");
348                         src = saddr.sin_addr;
349                 }
350                 close(probe_fd);
351         }
352
353         me.sll_family = AF_PACKET;
354         //me.sll_ifindex = ifindex; - done before
355         me.sll_protocol = htons(ETH_P_ARP);
356         xbind(sock_fd, (struct sockaddr *) &me, sizeof(me));
357
358         {
359                 socklen_t alen = sizeof(me);
360
361                 if (getsockname(sock_fd, (struct sockaddr *) &me, &alen) == -1) {
362                         bb_perror_msg_and_die("getsockname");
363                 }
364         }
365         if (me.sll_halen == 0) {
366                 bb_error_msg(err_str, "is not ARPable (no ll address)");
367                 return (option_mask32 & DAD ? 0 : 2);
368         }
369         he = me;
370         memset(he.sll_addr, -1, he.sll_halen);
371
372         if (!(option_mask32 & QUIET)) {
373                 /* inet_ntoa uses static storage, can't use in same printf */
374                 printf("ARPING to %s", inet_ntoa(dst));
375                 printf(" from %s via %s\n", inet_ntoa(src), device);
376         }
377
378         signal_SA_RESTART_empty_mask(SIGINT,  (void (*)(int))finish);
379         signal_SA_RESTART_empty_mask(SIGALRM, (void (*)(int))catcher);
380
381         catcher();
382
383         packet = xmalloc(4096);
384         while (1) {
385                 sigset_t sset, osset;
386                 struct sockaddr_ll from;
387                 socklen_t alen = sizeof(from);
388                 int cc;
389
390                 cc = recvfrom(sock_fd, packet, 4096, 0, (struct sockaddr *) &from, &alen);
391                 if (cc < 0) {
392                         bb_perror_msg("recvfrom");
393                         continue;
394                 }
395                 sigemptyset(&sset);
396                 sigaddset(&sset, SIGALRM);
397                 sigaddset(&sset, SIGINT);
398                 sigprocmask(SIG_BLOCK, &sset, &osset);
399                 recv_pack(packet, cc, &from);
400                 sigprocmask(SIG_SETMASK, &osset, NULL);
401         }
402 }