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