Magellan Linux

Annotation of /trunk/mkinitrd-magellan/busybox/networking/zcip.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 984 - (hide annotations) (download)
Sun May 30 11:32:42 2010 UTC (14 years ago) by niro
File MIME type: text/plain
File size: 15394 byte(s)
-updated to busybox-1.16.1 and enabled blkid/uuid support in default config
1 niro 532 /* vi: set sw=4 ts=4: */
2     /*
3     * RFC3927 ZeroConf IPv4 Link-Local addressing
4     * (see <http://www.zeroconf.org/>)
5     *
6     * Copyright (C) 2003 by Arthur van Hoff (avh@strangeberry.com)
7     * Copyright (C) 2004 by David Brownell
8     *
9     * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
10     */
11    
12     /*
13     * ZCIP just manages the 169.254.*.* addresses. That network is not
14     * routed at the IP level, though various proxies or bridges can
15     * certainly be used. Its naming is built over multicast DNS.
16     */
17    
18     //#define DEBUG
19    
20     // TODO:
21     // - more real-world usage/testing, especially daemon mode
22     // - kernel packet filters to reduce scheduling noise
23     // - avoid silent script failures, especially under load...
24     // - link status monitoring (restart on link-up; stop on link-down)
25    
26     #include <netinet/ether.h>
27     #include <net/ethernet.h>
28     #include <net/if.h>
29     #include <net/if_arp.h>
30     #include <linux/if_packet.h>
31     #include <linux/sockios.h>
32    
33 niro 816 #include "libbb.h"
34     #include <syslog.h>
35 niro 532
36 niro 816 /* We don't need more than 32 bits of the counter */
37     #define MONOTONIC_US() ((unsigned)monotonic_us())
38    
39 niro 532 struct arp_packet {
40 niro 816 struct ether_header eth;
41 niro 532 struct ether_arp arp;
42 niro 816 } PACKED;
43 niro 532
44     enum {
45     /* 169.254.0.0 */
46     LINKLOCAL_ADDR = 0xa9fe0000,
47    
48     /* protocol timeout parameters, specified in seconds */
49     PROBE_WAIT = 1,
50     PROBE_MIN = 1,
51     PROBE_MAX = 2,
52     PROBE_NUM = 3,
53     MAX_CONFLICTS = 10,
54     RATE_LIMIT_INTERVAL = 60,
55     ANNOUNCE_WAIT = 2,
56     ANNOUNCE_NUM = 2,
57     ANNOUNCE_INTERVAL = 2,
58     DEFEND_INTERVAL = 10
59     };
60    
61     /* States during the configuration process. */
62     enum {
63     PROBE = 0,
64     RATE_LIMIT_PROBE,
65     ANNOUNCE,
66     MONITOR,
67     DEFEND
68     };
69    
70 niro 816 #define VDBG(...) do { } while (0)
71 niro 532
72    
73 niro 816 enum {
74     sock_fd = 3
75     };
76    
77     struct globals {
78     struct sockaddr saddr;
79     struct ether_addr eth_addr;
80     };
81     #define G (*(struct globals*)&bb_common_bufsiz1)
82     #define saddr (G.saddr )
83     #define eth_addr (G.eth_addr)
84    
85    
86 niro 532 /**
87     * Pick a random link local IP address on 169.254/16, except that
88     * the first and last 256 addresses are reserved.
89     */
90 niro 816 static uint32_t pick(void)
91 niro 532 {
92     unsigned tmp;
93    
94     do {
95 niro 816 tmp = rand() & IN_CLASSB_HOST;
96 niro 532 } while (tmp > (IN_CLASSB_HOST - 0x0200));
97 niro 816 return htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
98 niro 532 }
99    
100     /**
101     * Broadcast an ARP packet.
102     */
103 niro 816 static void arp(
104     /* int op, - always ARPOP_REQUEST */
105     /* const struct ether_addr *source_eth, - always &eth_addr */
106     struct in_addr source_ip,
107     const struct ether_addr *target_eth, struct in_addr target_ip)
108 niro 532 {
109 niro 816 enum { op = ARPOP_REQUEST };
110     #define source_eth (&eth_addr)
111    
112 niro 532 struct arp_packet p;
113     memset(&p, 0, sizeof(p));
114    
115     // ether header
116 niro 816 p.eth.ether_type = htons(ETHERTYPE_ARP);
117     memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
118     memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
119 niro 532
120     // arp request
121     p.arp.arp_hrd = htons(ARPHRD_ETHER);
122     p.arp.arp_pro = htons(ETHERTYPE_IP);
123     p.arp.arp_hln = ETH_ALEN;
124     p.arp.arp_pln = 4;
125     p.arp.arp_op = htons(op);
126 niro 816 memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
127     memcpy(&p.arp.arp_spa, &source_ip, sizeof(p.arp.arp_spa));
128     memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
129     memcpy(&p.arp.arp_tpa, &target_ip, sizeof(p.arp.arp_tpa));
130 niro 532
131     // send it
132 niro 816 // Even though sock_fd is already bound to saddr, just send()
133     // won't work, because "socket is not connected"
134     // (and connect() won't fix that, "operation not supported").
135     // Thus we sendto() to saddr. I wonder which sockaddr
136     // (from bind() or from sendto()?) kernel actually uses
137     // to determine iface to emit the packet from...
138     xsendto(sock_fd, &p, sizeof(p), &saddr, sizeof(saddr));
139     #undef source_eth
140 niro 532 }
141    
142     /**
143     * Run a script.
144 niro 816 * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
145 niro 532 */
146 niro 816 static int run(char *argv[3], const char *param, struct in_addr *ip)
147 niro 532 {
148 niro 816 int status;
149     char *addr = addr; /* for gcc */
150     const char *fmt = "%s %s %s" + 3;
151 niro 532
152 niro 816 argv[2] = (char*)param;
153 niro 532
154 niro 816 VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
155 niro 532
156 niro 816 if (ip) {
157     addr = inet_ntoa(*ip);
158     xsetenv("ip", addr);
159     fmt -= 3;
160 niro 532 }
161 niro 816 bb_info_msg(fmt, argv[2], argv[0], addr);
162    
163     status = wait4pid(spawn(argv + 1));
164     if (status < 0) {
165     bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
166     return -errno;
167     }
168     if (status != 0)
169     bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status);
170 niro 532 return status;
171     }
172    
173     /**
174     * Return milliseconds of random delay, up to "secs" seconds.
175     */
176 niro 816 static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
177 niro 532 {
178 niro 816 return rand() % (secs * 1000);
179 niro 532 }
180    
181     /**
182     * main program
183     */
184 niro 816 int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
185 niro 984 int zcip_main(int argc UNUSED_PARAM, char **argv)
186 niro 816 {
187     int state;
188     char *r_opt;
189     unsigned opts;
190 niro 532
191 niro 816 // ugly trick, but I want these zeroed in one go
192     struct {
193     const struct in_addr null_ip;
194     const struct ether_addr null_addr;
195     struct in_addr ip;
196     struct ifreq ifr;
197     int timeout_ms; /* must be signed */
198     unsigned conflicts;
199     unsigned nprobes;
200     unsigned nclaims;
201     int ready;
202     int verbose;
203     } L;
204     #define null_ip (L.null_ip )
205     #define null_addr (L.null_addr )
206     #define ip (L.ip )
207     #define ifr (L.ifr )
208     #define timeout_ms (L.timeout_ms)
209     #define conflicts (L.conflicts )
210     #define nprobes (L.nprobes )
211     #define nclaims (L.nclaims )
212     #define ready (L.ready )
213     #define verbose (L.verbose )
214 niro 532
215 niro 816 memset(&L, 0, sizeof(L));
216 niro 532
217 niro 816 #define FOREGROUND (opts & 1)
218     #define QUIT (opts & 2)
219 niro 532 // parse commandline: prog [options] ifname script
220 niro 816 // exactly 2 args; -v accumulates and implies -f
221     opt_complementary = "=2:vv:vf";
222     opts = getopt32(argv, "fqr:v", &r_opt, &verbose);
223     #if !BB_MMU
224     // on NOMMU reexec early (or else we will rerun things twice)
225     if (!FOREGROUND)
226     bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
227     #endif
228     // open an ARP socket
229     // (need to do it before openlog to prevent openlog from taking
230     // fd 3 (sock_fd==3))
231     xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
232 niro 532 if (!FOREGROUND) {
233 niro 816 // do it before all bb_xx_msg calls
234 niro 532 openlog(applet_name, 0, LOG_DAEMON);
235 niro 816 logmode |= LOGMODE_SYSLOG;
236 niro 532 }
237     if (opts & 4) { // -r n.n.n.n
238     if (inet_aton(r_opt, &ip) == 0
239     || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR
240     ) {
241     bb_error_msg_and_die("invalid link address");
242     }
243     }
244 niro 816 argv += optind - 1;
245 niro 532
246 niro 816 /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
247     /* We need to make space for script argument: */
248     argv[0] = argv[1];
249     argv[1] = argv[2];
250     /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
251     #define argv_intf (argv[0])
252    
253     xsetenv("interface", argv_intf);
254    
255 niro 532 // initialize the interface (modprobe, ifup, etc)
256 niro 816 if (run(argv, "init", NULL))
257 niro 532 return EXIT_FAILURE;
258    
259     // initialize saddr
260 niro 816 // saddr is: { u16 sa_family; u8 sa_data[14]; }
261     //memset(&saddr, 0, sizeof(saddr));
262     //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
263     safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data));
264 niro 532
265     // bind to the interface's ARP socket
266 niro 816 xbind(sock_fd, &saddr, sizeof(saddr));
267 niro 532
268     // get the interface's ethernet address
269 niro 816 //memset(&ifr, 0, sizeof(ifr));
270 niro 984 strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
271 niro 816 xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
272 niro 532 memcpy(&eth_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
273    
274     // start with some stable ip address, either a function of
275     // the hardware address or else the last address we used.
276 niro 816 // we are taking low-order four bytes, as top-order ones
277     // aren't random enough.
278 niro 532 // NOTE: the sequence of addresses we try changes only
279     // depending on when we detect conflicts.
280 niro 816 {
281 niro 984 uint32_t t;
282     move_from_unaligned32(t, ((char *)&eth_addr + 2));
283 niro 816 srand(t);
284     }
285 niro 532 if (ip.s_addr == 0)
286 niro 816 ip.s_addr = pick();
287 niro 532
288     // FIXME cases to handle:
289     // - zcip already running!
290     // - link already has local address... just defend/update
291    
292     // daemonize now; don't delay system startup
293     if (!FOREGROUND) {
294 niro 816 #if BB_MMU
295     bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
296     #endif
297     bb_info_msg("start, interface %s", argv_intf);
298 niro 532 }
299    
300     // run the dynamic address negotiation protocol,
301     // restarting after address conflicts:
302     // - start with some address we want to try
303     // - short random delay
304 niro 816 // - arp probes to see if another host uses it
305 niro 532 // - arp announcements that we're claiming it
306     // - use it
307     // - defend it, within limits
308 niro 816 // exit if:
309     // - address is successfully obtained and -q was given:
310     // run "<script> config", then exit with exitcode 0
311     // - poll error (when does this happen?)
312     // - read error (when does this happen?)
313     // - sendto error (in arp()) (when does this happen?)
314     // - revents & POLLERR (link down). run "<script> deconfig" first
315     state = PROBE;
316 niro 532 while (1) {
317     struct pollfd fds[1];
318 niro 816 unsigned deadline_us;
319 niro 532 struct arp_packet p;
320 niro 816 int source_ip_conflict;
321     int target_ip_conflict;
322 niro 532
323 niro 816 fds[0].fd = sock_fd;
324 niro 532 fds[0].events = POLLIN;
325     fds[0].revents = 0;
326    
327     // poll, being ready to adjust current timeout
328 niro 816 if (!timeout_ms) {
329     timeout_ms = random_delay_ms(PROBE_WAIT);
330     // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
331 niro 532 // make the kernel filter out all packets except
332     // ones we'd care about.
333     }
334 niro 816 // set deadline_us to the point in time when we timeout
335     deadline_us = MONOTONIC_US() + timeout_ms * 1000;
336 niro 532
337 niro 816 VDBG("...wait %d %s nprobes=%u, nclaims=%u\n",
338     timeout_ms, argv_intf, nprobes, nclaims);
339 niro 532
340 niro 816 switch (safe_poll(fds, 1, timeout_ms)) {
341    
342     default:
343     //bb_perror_msg("poll"); - done in safe_poll
344     return EXIT_FAILURE;
345    
346 niro 532 // timeout
347     case 0:
348     VDBG("state = %d\n", state);
349     switch (state) {
350     case PROBE:
351     // timeouts in the PROBE state mean no conflicting ARP packets
352     // have been received, so we can progress through the states
353     if (nprobes < PROBE_NUM) {
354     nprobes++;
355 niro 816 VDBG("probe/%u %s@%s\n",
356     nprobes, argv_intf, inet_ntoa(ip));
357     arp(/* ARPOP_REQUEST, */
358     /* &eth_addr, */ null_ip,
359 niro 532 &null_addr, ip);
360 niro 816 timeout_ms = PROBE_MIN * 1000;
361     timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
362 niro 532 }
363     else {
364     // Switch to announce state.
365     state = ANNOUNCE;
366     nclaims = 0;
367 niro 816 VDBG("announce/%u %s@%s\n",
368     nclaims, argv_intf, inet_ntoa(ip));
369     arp(/* ARPOP_REQUEST, */
370     /* &eth_addr, */ ip,
371 niro 532 &eth_addr, ip);
372 niro 816 timeout_ms = ANNOUNCE_INTERVAL * 1000;
373 niro 532 }
374     break;
375     case RATE_LIMIT_PROBE:
376     // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
377     // have been received, so we can move immediately to the announce state
378     state = ANNOUNCE;
379     nclaims = 0;
380 niro 816 VDBG("announce/%u %s@%s\n",
381     nclaims, argv_intf, inet_ntoa(ip));
382     arp(/* ARPOP_REQUEST, */
383     /* &eth_addr, */ ip,
384 niro 532 &eth_addr, ip);
385 niro 816 timeout_ms = ANNOUNCE_INTERVAL * 1000;
386 niro 532 break;
387     case ANNOUNCE:
388     // timeouts in the ANNOUNCE state mean no conflicting ARP packets
389     // have been received, so we can progress through the states
390     if (nclaims < ANNOUNCE_NUM) {
391     nclaims++;
392 niro 816 VDBG("announce/%u %s@%s\n",
393     nclaims, argv_intf, inet_ntoa(ip));
394     arp(/* ARPOP_REQUEST, */
395     /* &eth_addr, */ ip,
396 niro 532 &eth_addr, ip);
397 niro 816 timeout_ms = ANNOUNCE_INTERVAL * 1000;
398 niro 532 }
399     else {
400     // Switch to monitor state.
401     state = MONITOR;
402     // link is ok to use earlier
403     // FIXME update filters
404 niro 816 run(argv, "config", &ip);
405 niro 532 ready = 1;
406     conflicts = 0;
407 niro 816 timeout_ms = -1; // Never timeout in the monitor state.
408 niro 532
409     // NOTE: all other exit paths
410     // should deconfig ...
411     if (QUIT)
412     return EXIT_SUCCESS;
413     }
414     break;
415     case DEFEND:
416     // We won! No ARP replies, so just go back to monitor.
417     state = MONITOR;
418 niro 816 timeout_ms = -1;
419 niro 532 conflicts = 0;
420     break;
421     default:
422     // Invalid, should never happen. Restart the whole protocol.
423     state = PROBE;
424 niro 816 ip.s_addr = pick();
425     timeout_ms = 0;
426 niro 532 nprobes = 0;
427     nclaims = 0;
428     break;
429     } // switch (state)
430     break; // case 0 (timeout)
431 niro 816
432     // packets arriving, or link went down
433 niro 532 case 1:
434     // We need to adjust the timeout in case we didn't receive
435     // a conflicting packet.
436 niro 816 if (timeout_ms > 0) {
437     unsigned diff = deadline_us - MONOTONIC_US();
438     if ((int)(diff) < 0) {
439 niro 532 // Current time is greater than the expected timeout time.
440     // Should never happen.
441     VDBG("missed an expected timeout\n");
442 niro 816 timeout_ms = 0;
443 niro 532 } else {
444     VDBG("adjusting timeout\n");
445 niro 816 timeout_ms = (diff / 1000) | 1; /* never 0 */
446 niro 532 }
447     }
448    
449     if ((fds[0].revents & POLLIN) == 0) {
450     if (fds[0].revents & POLLERR) {
451     // FIXME: links routinely go down;
452     // this shouldn't necessarily exit.
453 niro 816 bb_error_msg("iface %s is down", argv_intf);
454 niro 532 if (ready) {
455 niro 816 run(argv, "deconfig", &ip);
456 niro 532 }
457     return EXIT_FAILURE;
458     }
459     continue;
460     }
461    
462     // read ARP packet
463 niro 816 if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
464     bb_perror_msg_and_die(bb_msg_read_error);
465 niro 532 }
466 niro 816 if (p.eth.ether_type != htons(ETHERTYPE_ARP))
467 niro 532 continue;
468     #ifdef DEBUG
469     {
470 niro 816 struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
471     struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
472     struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
473     struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
474 niro 532 VDBG("%s recv arp type=%d, op=%d,\n",
475 niro 816 argv_intf, ntohs(p.eth.ether_type),
476 niro 532 ntohs(p.arp.arp_op));
477     VDBG("\tsource=%s %s\n",
478     ether_ntoa(sha),
479     inet_ntoa(*spa));
480     VDBG("\ttarget=%s %s\n",
481     ether_ntoa(tha),
482     inet_ntoa(*tpa));
483     }
484     #endif
485     if (p.arp.arp_op != htons(ARPOP_REQUEST)
486 niro 816 && p.arp.arp_op != htons(ARPOP_REPLY))
487 niro 532 continue;
488    
489 niro 816 source_ip_conflict = 0;
490     target_ip_conflict = 0;
491    
492     if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0
493     && memcmp(&p.arp.arp_sha, &eth_addr, ETH_ALEN) != 0
494     ) {
495 niro 532 source_ip_conflict = 1;
496     }
497 niro 816 if (p.arp.arp_op == htons(ARPOP_REQUEST)
498     && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0
499     && memcmp(&p.arp.arp_tha, &eth_addr, ETH_ALEN) != 0
500     ) {
501 niro 532 target_ip_conflict = 1;
502     }
503    
504     VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
505     state, source_ip_conflict, target_ip_conflict);
506     switch (state) {
507     case PROBE:
508     case ANNOUNCE:
509     // When probing or announcing, check for source IP conflicts
510     // and other hosts doing ARP probes (target IP conflicts).
511     if (source_ip_conflict || target_ip_conflict) {
512     conflicts++;
513     if (conflicts >= MAX_CONFLICTS) {
514 niro 816 VDBG("%s ratelimit\n", argv_intf);
515     timeout_ms = RATE_LIMIT_INTERVAL * 1000;
516 niro 532 state = RATE_LIMIT_PROBE;
517     }
518    
519     // restart the whole protocol
520 niro 816 ip.s_addr = pick();
521     timeout_ms = 0;
522 niro 532 nprobes = 0;
523     nclaims = 0;
524     }
525     break;
526     case MONITOR:
527     // If a conflict, we try to defend with a single ARP probe.
528     if (source_ip_conflict) {
529     VDBG("monitor conflict -- defending\n");
530     state = DEFEND;
531 niro 816 timeout_ms = DEFEND_INTERVAL * 1000;
532     arp(/* ARPOP_REQUEST, */
533     /* &eth_addr, */ ip,
534     &eth_addr, ip);
535 niro 532 }
536     break;
537     case DEFEND:
538     // Well, we tried. Start over (on conflict).
539     if (source_ip_conflict) {
540     state = PROBE;
541     VDBG("defend conflict -- starting over\n");
542     ready = 0;
543 niro 816 run(argv, "deconfig", &ip);
544 niro 532
545     // restart the whole protocol
546 niro 816 ip.s_addr = pick();
547     timeout_ms = 0;
548 niro 532 nprobes = 0;
549     nclaims = 0;
550     }
551     break;
552     default:
553     // Invalid, should never happen. Restart the whole protocol.
554     VDBG("invalid state -- starting over\n");
555     state = PROBE;
556 niro 816 ip.s_addr = pick();
557     timeout_ms = 0;
558 niro 532 nprobes = 0;
559     nclaims = 0;
560     break;
561     } // switch state
562     break; // case 1 (packets arriving)
563     } // switch poll
564 niro 816 } // while (1)
565     #undef argv_intf
566 niro 532 }