1/*
2 * zeroconf.c
3 *
4 * Copyright (c) 2006 Anand Kumria
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * See the file COPYING for the full details
12 *
13 */
14
15#include <sys/types.h>
16#include <sys/socket.h>
17#include <linux/rtnetlink.h>
18#include <linux/if.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#define _GNU_SOURCE
23#include <getopt.h>
24#undef _GNU_SOURCE
25#include <errno.h>
26#include <unistd.h>
27#include <fcntl.h>
28#include <sys/poll.h>
29#include <sys/ioctl.h>
30#include <netpacket/packet.h>
31#include <net/ethernet.h>
32#include <arpa/inet.h>
33#include <net/if_arp.h>
34#include <sys/time.h>
35#include <signal.h>
36
37#include "delay.h"
38
39/* constants from RFC2937 */
40#define PROBE_WAIT           1 /*second  (initial random delay)              */
41#define PROBE_MIN            1 /*second  (minimum delay till repeated probe) */
42#define PROBE_MAX            2 /*seconds (maximum delay till repeated probe) */
43#define PROBE_NUM            3 /*         (number of probe packets)          */
44#define ANNOUNCE_NUM         2 /*        (number of announcement packets)    */
45#define ANNOUNCE_INTERVAL    2 /*seconds (time between announcement packets) */
46#define ANNOUNCE_WAIT        2 /*seconds  (delay before announcing)          */
47#define MAX_CONFLICTS       10 /*        (max conflicts before rate limiting)*/
48#define RATE_LIMIT_INTERVAL 60 /*seconds (delay between successive attempts) */
49#define DEFEND_INTERVAL     10 /*seconds (min. wait between defensive ARPs)  */
50
51/* compilation constants */
52#define NLBUF 512
53#define ARP_IP_PROTO 2048
54#define IPV4_LLBASE 0xa9fe0000 /* 169.254.0.0 */
55
56/* some helpful macros */
57#define FLAG_TEST_DUMP(x, y) if (x & y) fprintf(stderr, "%s ", #y);
58
59/* our state machine */
60enum {
61  ADDR_INIT,
62  ADDR_PROBE,
63  ADDR_CLAIM,
64  ADDR_TAKE,
65  ADDR_DEFEND,
66  ADDR_FINAL,
67  ADDR_RELEASE
68};
69
70/* structures */
71struct intf {
72  char              name[IFNAMSIZ+1];
73  int               index;
74  unsigned int      flags;
75  int               up;
76  struct ether_addr mac;
77  struct in_addr    ip;
78};
79
80struct arp_packet {
81  struct arphdr       arp;
82  struct ether_addr   sender_mac;
83  struct in_addr      sender_ip;
84  struct ether_addr   target_mac;
85  struct in_addr      target_ip;
86  unsigned char       reserved[18];
87} __attribute__ ((packed));
88
89/* forward declarations */
90void check_args(int argc, char * const argv[], struct intf *intf);
91void zeroconf_counter_reset(void);
92int  netlink_open(int proto, __u32 groups);
93int  netlink_close(int nl);
94int  netlink_send(int nl, struct nlmsghdr *n);
95void netlink_dump(struct nlmsghdr *n);
96void netlink_dump_rta(struct rtattr *rta, int length, int family);
97int  netlink_is_link_up(struct intf *intf, struct nlmsghdr *n);
98int  netlink_is_from_us(struct nlmsghdr *n);
99void netlink_is_our_iface(struct intf *intf, struct nlmsghdr *n);
100int  netlink_qualify(struct nlmsghdr *n, size_t length);
101void netlink_addr_add(int nl, struct intf *intf);
102void netlink_addr_del(int nl, struct intf *intf);
103int  check_ifname_exists(int nl, struct intf *intf);
104int  check_ifname_type(struct intf *intf);
105int  arp_open(struct intf *intf);
106int  arp_conflict(struct intf *intf, struct arp_packet *pkt);
107/* Foxconn added start pling 02/25/2011 */
108int  arp_conflict_defend(struct intf *intf, struct arp_packet *pkt);
109/* Foxconn added end pling 02/25/2011 */
110void arp_packet_dump(struct arp_packet *pkt);
111void arp_packet_send(int as,
112		     struct intf *intf,
113		     short int arp_op,
114		     int null_sender);
115void arp_probe(int as, struct intf *intf);
116void arp_claim(int as, struct intf *intf);
117void arp_defend(int as, struct intf *intf);
118void usage(void);
119int  signal_install(int signo);
120int addattr_l(struct nlmsghdr *n, unsigned int maxlen, int type, const void *data, int alen);
121
122/* globals */
123int force = 0;
124int verbose = 0;
125int nofork = 0;
126
127pid_t mypid = -1;
128
129int probe_count = 0;
130int conflict_count = 0;
131int claim_count = 0;
132int address_picked = 0;
133
134int self_pipe[2] = { -1, -1 };
135
136/* Foxconn added start pling 03/23/2011 */
137int use_previous_address = 0;
138/* Foxconn added end pling 03/23/2011 */
139
140static void sig_handler(int signo)
141{
142  write(self_pipe[1], &signo, sizeof(signo));
143}
144
145
146int main(int argc, char **argv)
147{
148
149  int nl, as;
150  int keep_running = 1;
151  struct itimerval  delay;
152  char pidloc[PATH_MAX];
153
154  struct intf intf = {
155    .index = -1,
156    .flags = 0,
157    .up = 0,
158  };
159
160  /* Foxconn added start pling 03/25/2011 */
161  static int defence_done = 0;
162  /* Foxconn added end pling 03/25/2011 */
163
164  check_args(argc, argv, &intf);
165
166  if ((nl = netlink_open(NETLINK_ROUTE, 0)) < 0) {
167    fprintf(stderr, "unable to connect to netlink\n");
168    exit(1);
169  }
170
171  if (check_ifname_exists(nl, &intf) < 0) {
172    fprintf(stderr, "Interface %s does not exist\n", intf.name);
173    exit(1);
174  }
175
176  if ((check_ifname_type(&intf) < 0) && (!force)) {
177    fprintf(stderr, "Interface %s (%d) not suitable for zeroconf\n",
178	    intf.name, intf.index);
179    exit(1);
180  }
181
182  if ((as = arp_open(&intf)) < 0) {
183    fprintf(stderr, "unable to obtain ARP socket: %s\n", strerror(errno));
184    exit(1);
185  }
186
187  /* convert our generic netlink socket into one which only
188   * reports link, ipv4 address and ipv4 route events
189   */
190  if (netlink_close(nl) < 0) {
191    fprintf(stderr, "netlink close error: %s\n", strerror(errno));
192    exit(1);
193  }
194
195  if ((nl = netlink_open(NETLINK_ROUTE,
196			 RTMGRP_LINK|RTMGRP_IPV4_IFADDR|RTMGRP_IPV4_ROUTE))< 0){
197    fprintf(stderr, "unable to connect to netlink groups\n");
198    exit(1);
199  }
200
201  if (!nofork)
202    daemon(0, 0);
203
204  if (!verbose) {
205    close(STDIN_FILENO);
206    close(STDOUT_FILENO);
207    close(STDERR_FILENO);
208  }
209
210  /* write /var/run/zeroconf.intf.pid */
211  {
212    FILE *pidfile;
213
214    if (snprintf(pidloc, PATH_MAX, "/var/run/zeroconf.%s.pid", intf.name) < 0) {
215      fprintf(stderr, "unable to construct pid file location: %s\n", strerror(errno));
216      exit(1);
217    }
218
219    pidfile = fopen(pidloc, "w+");
220
221    if (pidfile != NULL) {
222
223      mypid = getpid();
224
225      fprintf(pidfile, "%d\n", mypid);
226
227      fclose(pidfile);
228
229    } else {
230
231      fprintf(stderr, "unable to create pid file (%s): %s\n", pidloc, strerror(errno));
232
233    }
234
235  }
236
237
238  /* setup random number generator
239   * we key this off the MAC-48 HW identifier
240   * the first 3 octets are the manufacturer
241   * the next 3 the serial number
242   * we'll use the last four for the largest variety
243   */
244  srandom((intf.mac.ether_addr_octet[2] << 24) |
245	  (intf.mac.ether_addr_octet[3] << 16) |
246	  (intf.mac.ether_addr_octet[4] <<  8) |
247	  (intf.mac.ether_addr_octet[5] <<  0)  );
248
249  /* handle signals
250   * SIGALARM: set delay_timeout = 1
251   * SIGTERM : perform address release and exit
252   * SIGINT  : perform address release and exit
253   * SIGHUP  : perform address release and re-init
254   */
255
256  if (pipe(self_pipe) < 0) {
257    fprintf(stderr, "unable to create self-pipe fds: %s\n", strerror(errno));
258    exit(1);
259  }
260
261  if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) {
262    fprintf(stderr, "unable to set self-pipe fd non-blocking: %s\n", strerror(errno));
263    exit(1);
264  }
265
266  if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) {
267    fprintf(stderr, "unable to set self-pipe fd non-blocking: %s\n", strerror(errno));
268    exit(1);
269  }
270
271  if (signal_install(SIGALRM) < 0) {
272    fprintf(stderr, "unable to install SIGALRM: %s\n", strerror(errno));
273    exit(1);
274  }
275
276  if (signal_install(SIGTERM) < 0) {
277    fprintf(stderr, "unable to install SIGTERM: %s\n", strerror(errno));
278    exit(1);
279  }
280
281  if (signal_install(SIGINT) < 0) {
282    fprintf(stderr, "unable to install SIGINT: %s\n", strerror(errno));
283    exit(1);
284  }
285
286  if (signal_install(SIGHUP) < 0) {
287    fprintf(stderr, "unable to install SIGHUP: %s\n", strerror(errno));
288    exit(1);
289  }
290
291  /* setup an immediate delay to kick things off */
292
293  delay_setup_immed(&delay);
294
295  delay_run(&delay);
296
297  while (keep_running) {
298
299    static int state = ADDR_INIT;
300
301    struct pollfd     fds[3];
302    struct arp_packet *pkt;
303    struct nlmsghdr   *n;
304
305    int           timeout;
306    unsigned char replybuf[4096];
307
308    timeout = 0;
309    pkt = NULL;
310    n = NULL;
311
312    fds[0].fd = nl;
313    fds[0].events = POLLIN|POLLERR;
314    fds[1].fd = as;
315    fds[1].events = POLLIN|POLLERR;
316    fds[2].fd = self_pipe[0];
317    fds[2].events = POLLIN|POLLERR;
318
319    switch (poll(fds, 3, -1)) {
320    case -1:
321      /* signals are handled as file descriptors via the self-pipe */
322      if (errno == EINTR)
323	continue;
324
325      fprintf(stderr, "poll err: %s\n", strerror(errno));
326      exit(1);
327      break;
328    case 0:
329      fprintf(stderr, "poll timed out during infinity\n");
330      exit(1);
331      break;
332    default:
333      {
334
335	ssize_t ret;
336
337	/* okay, one of our descriptors has been changed
338	 * pull the data out, processing takes place later
339	 */
340
341	/* netlink */
342	if (fds[0].revents) {
343
344	  n = (struct nlmsghdr *)&replybuf;
345	  if (verbose)
346	    fprintf(stderr, "netlink event\n");
347	  ret = recv(fds[0].fd, replybuf, sizeof(replybuf), 0);
348#if 0
349	  for (int i = 0; i < ret; i++)
350	    fprintf(stderr, "!%02X", replybuf[i]);
351	  fprintf(stderr, "\n");
352#endif
353	  if (verbose)
354	    netlink_dump(n);
355
356	  if (netlink_qualify(n, ret) < 0)
357	    n = NULL;
358
359	}
360
361	/* arp packet */
362	if (fds[1].revents) {
363	  if (verbose)
364	    fprintf(stderr, "arp event\n");
365	  ret = recv(fds[1].fd, replybuf, sizeof(replybuf), 0);
366	  pkt = (struct arp_packet *)&replybuf;
367	  if (verbose)
368	    arp_packet_dump(pkt);
369	  intf.up = 1;
370	}
371
372	/* signal */
373	if (fds[2].revents) {
374	  int signo;
375	  ret = read(fds[2].fd, &signo, sizeof(signo));
376	  if (ret < 0)
377	    fprintf(stderr, "signal read failed: %s\n", strerror(errno));
378
379	  if (verbose)
380	    fprintf(stderr, "signal %d\n", signo);
381
382	  if (ret == sizeof(signo)) {
383	    switch(signo) {
384	    case SIGALRM:
385	      delay_timeout = 1;
386	      delay_is_running = 0;
387	      break;
388	    case SIGINT:
389	    case SIGTERM:
390	      state = ADDR_RELEASE;
391	      keep_running = 0;
392	      break;
393	    case SIGHUP:
394	      state = ADDR_RELEASE;
395	      break;
396	    default:
397	      fprintf(stderr, "unhandled signal %d\n", signo);
398	      break;
399	    }
400	  }
401	}
402
403      }
404      break;
405    }
406
407    /* ARP could possibly have various types of address formats.
408     * Only Ethernet, IP protocol addresses and
409     * ARP_REQUESTs or ARP_REPLYs are interesting
410     */
411    if ((pkt) &&
412	(ntohs(pkt->arp.ar_hrd) != ARPHRD_ETHER) &&
413	(ntohs(pkt->arp.ar_pro) != ARP_IP_PROTO) &&
414	(
415	 (ntohs(pkt->arp.ar_op) != ARPOP_REQUEST) ||
416	 (ntohs(pkt->arp.ar_op) != ARPOP_REPLY)
417	)
418       ) {
419      pkt = NULL;
420    }
421
422    intf.up = netlink_is_link_up(&intf, n);
423
424    if ((n) && (!netlink_is_from_us(n))) {
425
426      /* we have a message that is from elsewhere
427       * the only ones we get are:
428       * RTM_NEWLINK,  RTM_DELLINK
429       * RTM_NEWADDR,  RTM_DELADDR
430       * RTM_NEWROUTE, RTM_DELROUTE
431       *
432       * At this point a LINK message could happen. We deal with
433       * some NEWLINKs in netlink_is_link_up(); but the interface
434       * index might have changed. So we have to check here and
435       * snarf it if the interface name matches our command line.
436       *
437       * Even though it is common to remove a wireless module
438       * on suspend, there isn't anything special we can do.
439       * Removing the module generates a DELLINK which we flag as
440       * a termination event. Hopefully when the interface is
441       * recreated zeroconf is re-invoked.
442       *
443       * DELADDR is possible from either the administrator or
444       * another program (e.g. buggy DHCP program).
445       * We could add the address back straight away but we
446       * play safe by re-probing once again
447       *
448       * NEWADDR we should investigate to see if another IPv4
449       * link-local is being assigned and then terminate if so.
450       *
451       * NEWROUTE / DELROUTE TODO
452       *
453       */
454
455      switch (n->nlmsg_type) {
456      case RTM_NEWLINK:
457	netlink_is_our_iface(&intf, n);
458	state = ADDR_PROBE;
459	break;
460      case RTM_DELLINK:
461	{
462	  struct ifinfomsg *i;
463
464	  i = NLMSG_DATA(n);
465
466	  if (intf.index == i->ifi_index) {
467	    state = ADDR_RELEASE;
468	    keep_running = 0;
469	  }
470	}
471	break;
472      case RTM_NEWADDR:
473	{
474	  struct ifaddrmsg *a;
475	  int len;
476
477	  a = NLMSG_DATA(n);
478	  len = NLMSG_PAYLOAD(n, sizeof(struct ifaddrmsg));
479
480	  if ((a->ifa_index == intf.index) &&
481	      (a->ifa_family == AF_INET)) {
482	    struct rtattr  *rta;
483	    struct in_addr  ip;
484
485	    rta = IFA_RTA(a);
486
487	    while (RTA_OK(rta, len)) {
488	      if (rta->rta_type == IFLA_ADDRESS) {
489
490		memcpy(&ip, RTA_DATA(rta), rta->rta_len);
491
492		if (verbose)
493		  fprintf(stderr,"saw %s\n",inet_ntoa(ip));
494
495		if ((ip.s_addr & htonl(IPV4_LLBASE)) == htonl(IPV4_LLBASE)) {
496		  /* perhaps a second instance is running?
497		   * or the administrator has set an address
498		   * manually. Either way, let's exit
499		   */
500		  state = ADDR_RELEASE;
501		  keep_running = 0;
502		}
503
504	      }
505
506	      rta = RTA_NEXT(rta, len);
507
508	    }
509	  }
510	}
511	break;
512      case RTM_DELADDR:
513	{
514
515	  struct ifaddrmsg *a;
516	  int len;
517
518	  a = NLMSG_DATA(n);
519	  len = NLMSG_PAYLOAD(n, sizeof(struct ifaddrmsg));
520
521	  if ((a->ifa_index == intf.index) &&
522	      (a->ifa_family == AF_INET)) {
523
524	    struct rtattr  *rta;
525	    struct in_addr  ip;
526
527	    rta = IFA_RTA(a);
528
529	    while (RTA_OK(rta, len)) {
530	      if (rta->rta_type == IFLA_ADDRESS) {
531
532		memcpy(&ip, RTA_DATA(rta), rta->rta_len);
533
534		if (verbose)
535		  fprintf(stderr,"saw %s\n",inet_ntoa(ip));
536
537		if ((ip.s_addr & htonl(IPV4_LLBASE)) == htonl(IPV4_LLBASE)) {
538
539		  if (verbose)
540		    fprintf(stderr, "reasserting our address\n");
541
542		  zeroconf_counter_reset();
543		  state = ADDR_PROBE;
544		}
545	      }
546
547	      rta = RTA_NEXT(rta, len);
548
549	    }
550	  }
551	}
552	break;
553      case RTM_NEWROUTE:
554	/* TODO */
555	break;
556      case RTM_DELROUTE:
557	/* TODO */
558	break;
559      default:
560	fprintf(stderr, "unhandled case\n");
561	break;
562      }
563
564    }
565
566    /* if we aren't up, continue waiting */
567    if (!intf.up) {
568
569      delay_cancel();
570
571      zeroconf_counter_reset();
572      state = ADDR_PROBE;
573
574      continue;
575    }
576
577    switch (state) {
578    case ADDR_INIT:
579      {
580	if (verbose)
581	  fprintf(stderr, "entering ADDR_INIT\n");
582
583	delay_setup_random(&delay, 0, PROBE_WAIT);
584
585	delay_run(&delay);
586
587	zeroconf_counter_reset();
588
589    /* Foxconn added start pling 03/23/2011 */
590    /* Use previous Auto IP address if available */
591    if (use_previous_address) {
592      use_previous_address = 0;
593	  address_picked = 1;
594    } else
595    /* Foxconn added end pling 03/23/2011 */
596	address_picked = 0;
597
598	state = ADDR_PROBE;
599
600	if (verbose)
601	  fprintf(stderr, "leaving  ADDR_INIT\n");
602      }
603      break;
604    case ADDR_PROBE:
605      {
606	if (verbose)
607	  fprintf(stderr, "entering ADDR_PROBE\n");
608
609	delay_wait();
610
611	if (arp_conflict(&intf, pkt)) {
612	  conflict_count++;
613	  address_picked = 0;
614	  probe_count = 0;
615	}
616
617	if (!delay_is_waiting()) {
618
619	  if (!address_picked) {
620
621	    /*
622	     * pick random IP address in IPv4 link-local range
623	     * 169.254.0.0/16 is the allowed address range however
624	     * 169.254.0.0/24 and 169.254.255.0/24 must be excluded,
625	     * which removes 512 address from our 65535 candidates.
626	     * That leaves us with 65023 (0xfdff) to which we add
627	     * 256 (0x0100) to make sure it is within range.
628	     */
629
630	    intf.ip.s_addr = htonl(IPV4_LLBASE |
631				    ((abs(random()) % 0xfdff) + 0x0100));
632
633	    if (verbose)
634	      fprintf(stderr, "picked address: %s\n", inet_ntoa(intf.ip));
635
636	    address_picked = 1;
637
638	  }
639
640	  arp_probe(as, &intf);
641
642	  probe_count++;
643
644	}
645
646	if (probe_count >= PROBE_NUM) {
647	  state = ADDR_CLAIM;
648
649	  delay_setup_fixed(&delay, ANNOUNCE_WAIT);
650
651	  delay_run(&delay);
652
653	  if (verbose) /* really only here to make things look tidy */
654	    fprintf(stderr,"leaving  ADDR_PROBE\n");
655	  break;
656	}
657
658	if (conflict_count > MAX_CONFLICTS) {
659
660	  delay_setup_fixed(&delay, RATE_LIMIT_INTERVAL);
661
662	} else {
663
664	  delay_setup_random(&delay, PROBE_MIN, PROBE_MAX);
665
666	}
667
668	delay_run(&delay);
669
670	if (verbose)
671	  fprintf(stderr, "leaving  ADDR_PROBE\n");
672      }
673      break;
674    case ADDR_CLAIM:
675      {
676	if (verbose)
677	  fprintf(stderr, "entering ADDR_CLAIM\n");
678
679	if (arp_conflict(&intf, pkt)) {
680	  state = ADDR_PROBE;
681
682	  /* Foxconn added start pling 03/01/2011 */
683	  /* If addr conflict, we need to choose another auto ip */
684	  address_picked = 0;
685	  /* Foxconn added end pling 03/01/2011 */
686
687	  delay_setup_immed(&delay);
688
689	  delay_run(&delay);
690
691	  if (verbose)
692	    fprintf(stderr, "leaving  ADDR_CLAIM\n");
693	  break;
694	}
695
696	delay_wait();
697
698	arp_claim(as, &intf);
699
700	claim_count++;
701
702	if (claim_count >= ANNOUNCE_NUM) {
703	  state = ADDR_TAKE;
704
705	  delay_setup_immed(&delay);
706
707	  delay_run(&delay);
708
709	  if (verbose)
710	    fprintf(stderr, "leaving  ADDR_CLAIM\n");
711	  break;
712	}
713
714	delay_setup_fixed(&delay, ANNOUNCE_INTERVAL);
715
716	delay_run(&delay);
717
718	if (verbose)
719	  fprintf(stderr, "leaving  ADDR_CLAIM\n");
720      }
721      break;
722    case ADDR_TAKE:
723      {
724	if (verbose)
725	  fprintf(stderr, "entering ADDR_TAKE\n");
726
727	delay_wait();
728
729	netlink_addr_add(nl, &intf);
730
731    /* Foxonn added start pling 02/24/2011 */
732    /* Tell autoipd that we configured an auto ip */
733    system("killall -SIGINT autoipd 2>/dev/null");
734    /* Foxonn added end pling 02/24/2011 */
735
736	state = ADDR_DEFEND;
737
738    /* Foxconn added start pling 03/25/2011 */
739    /* Clear this flag so that 2nd ARP conflict will work */
740	defence_done = 0;
741    /* Foxconn added end pling 03/25/2011 */
742
743	delay_setup_immed(&delay);
744
745	delay_run(&delay);
746
747	if (verbose)
748	  fprintf(stderr, "leaving  ADDR_TAKE\n");
749      }
750      break;
751    case ADDR_DEFEND:
752      {
753
754	if (verbose)
755	  fprintf(stderr, "entering ADDR_DEFEND\n");
756
757    /* Foxconn modified start pling 02/25/2011 */
758    /* At DEFEND state, RFC requires only compare
759     * ARP's sender IP and our IP.
760     * So we should not use the common
761     * 'arp_conflict' function.
762     */
763#if 0
764	if (arp_conflict(&intf, pkt))
765#endif
766	if (arp_conflict_defend(&intf, pkt)) {
767    /* Foxconn modified end pling 02/25/2011 */
768
769	  arp_defend(as, &intf);
770
771	  delay_setup_immed(&delay);
772
773	  delay_run(&delay);
774
775	  state = ADDR_FINAL;
776
777	  /* no need to break here, since we fall out anyway */
778	}
779
780	if (verbose)
781	  fprintf(stderr, "leaving  ADDR_DEFEND\n");
782      }
783      break;
784    case ADDR_FINAL:
785      {
786
787    /* Foxconn removed start pling 03/25/2011 */
788    /* Make this variable global to this function */
789	/* static int defence_done = 0; */
790    /* Foxconn removed end pling 03/25/2011 */
791
792	if (verbose)
793	  fprintf(stderr, "entering ADDR_FINAL\n");
794
795	if (!defence_done) {
796
797	  delay_setup_fixed(&delay, DEFEND_INTERVAL);
798
799	  delay_run(&delay);
800
801	  defence_done = 1;
802
803	}
804
805	if (arp_conflict(&intf, pkt)) {
806
807	  delay_cancel();
808
809	  state = ADDR_RELEASE;
810
811	  delay_setup_immed(&delay);
812
813	  delay_run(&delay);
814
815	  if (verbose)
816	    fprintf(stderr, "leaving  ADDR_FINAL\n");
817	  break;
818	}
819
820	delay_wait();
821
822	/* we get here only if the timeout has
823	 * finished and there were no conflicts
824	 */
825	state = ADDR_DEFEND;
826
827	defence_done = 0;
828
829	if (verbose)
830	  fprintf(stderr, "leaving  ADDR_FINAL\n");
831      }
832      break;
833    case ADDR_RELEASE:
834      {
835
836	if (verbose)
837	  fprintf(stderr, "entering ADDR_RELEASE\n");
838
839	netlink_addr_del(nl, &intf);
840
841	delay_setup_immed(&delay);
842
843	delay_run(&delay);
844
845	state = ADDR_INIT;
846
847	if (verbose)
848	  fprintf(stderr, "leaving  ADDR_RELEASE\n");
849      }
850      break;
851    default:
852      fprintf(stderr, "unhandled state\n");
853      exit(1);
854    }
855
856
857  }
858
859  netlink_close(nl);
860
861  unlink(pidloc);
862
863  return 0;
864}
865
866void check_args(int argc, char * const argv[], struct intf *intf)
867{
868
869  int ret;
870  int optindex = 0;
871
872  /* command line options */
873  static struct option opts[] = {
874    {"force", 0, 0, 'f'},
875    {"interface", 1, 0, 'i'},
876    {"no-fork", 0, 0, 'n'},
877    {"ipaddr", 1, 0, 'p'},
878    {"verbose", 0, 0, 'v'},
879    {0, 0, 0, 0}
880  };
881
882  if (argc < 3) {
883    usage();
884  }
885
886  memset(intf->name, 0, IFNAMSIZ+1);
887
888  while (1) {
889#ifdef __KLIBC__
890#define getopt_long(a, b, c, d, e) getopt(a, b, c);
891#endif
892    ret = getopt_long(argc, argv, "fi:np:v", opts, &optindex);
893
894    if (ret == -1)
895      break;
896
897    switch (ret) {
898    case 'f':
899      force = 1;
900      break;
901    case 'i':
902      strncpy(intf->name, optarg, IFNAMSIZ);
903      break;
904    case 'n':
905      nofork = 1;
906      break;
907    case 'p':
908      /* Foxconn modified start pling 03/23/2011 */
909      /* Use previous auto ip address if available */
910#if 0
911      fprintf(stderr, "XXX: not implemented\n"); /* TODO */
912#endif
913      fprintf(stderr, "Try to use previous address '%s'\n", optarg);
914      if (inet_aton(optarg, &(intf->ip))) {
915          use_previous_address = 1;
916          //fprintf(stderr, "intf->ip=%u\n", intf->ip.s_addr);
917      }
918      /* Foxconn modified end pling 03/23/2011 */
919      break;
920    case 'v':
921      verbose = 1;
922      break;
923    default:
924      fprintf(stderr, "unknown option '%c'\n", ret);
925      usage();
926      break;
927    }
928
929  }
930
931  if (strlen(intf->name) == 0) {
932    fprintf(stderr, "no interface specified\n");
933    exit(1);
934  }
935
936}
937
938void zeroconf_counter_reset(void)
939{
940  probe_count = 0;
941  conflict_count = 0;
942  claim_count = 0;
943}
944
945int netlink_open(int proto, __u32 groups)
946{
947
948  int sock;
949  struct sockaddr_nl addr;
950
951  if ((sock = socket(PF_NETLINK, SOCK_RAW, proto)) < 0) {
952    fprintf(stderr, "socket(PF_NETLINK): %s\n", strerror(errno));
953    return sock;
954  }
955
956  memset(&addr, 0, sizeof(addr));
957
958  addr.nl_family = AF_NETLINK;
959  addr.nl_pid = getpid();
960  addr.nl_groups = groups;
961
962  if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
963    fprintf(stderr, "bind(): %s\n", strerror(errno));
964    return sock;
965  }
966
967  return sock;
968}
969
970int netlink_close(int nl)
971{
972  return close(nl);
973}
974
975int netlink_send(int nl, struct nlmsghdr *n)
976{
977
978  if ((nl < 0) || (!n))
979    return -1;
980
981  return send(nl, n, n->nlmsg_len, 0);
982
983}
984
985void netlink_dump(struct nlmsghdr *n)
986{
987  struct ifinfomsg *i;
988  struct ifaddrmsg *a;
989  struct rtmsg     *r;
990  int               l;
991
992  fprintf(stderr, "%u %u %u %u %u:",
993	  n->nlmsg_len,
994	  n->nlmsg_type,
995	  n->nlmsg_flags,
996	  n->nlmsg_seq,
997	  n->nlmsg_pid);
998
999  switch (n->nlmsg_type) {
1000
1001  case NLMSG_ERROR:
1002    fprintf(stderr, "netlink error\n");
1003    break;
1004
1005  case RTM_NEWLINK:
1006    fprintf(stderr, "RTM_NEWLINK\n");
1007
1008    i = NLMSG_DATA(n);
1009    l = NLMSG_PAYLOAD(n, sizeof(struct ifinfomsg));
1010
1011    fprintf(stderr,"ifinfomsg: %u %u %d %u %u ",i->ifi_family, i->ifi_type, i->ifi_index, i->ifi_flags, i->ifi_change);
1012
1013    FLAG_TEST_DUMP(i->ifi_flags,IFF_UP);
1014    FLAG_TEST_DUMP(i->ifi_flags,IFF_BROADCAST);
1015    FLAG_TEST_DUMP(i->ifi_flags,IFF_DEBUG);
1016    FLAG_TEST_DUMP(i->ifi_flags,IFF_LOOPBACK);
1017    FLAG_TEST_DUMP(i->ifi_flags,IFF_POINTOPOINT);
1018    FLAG_TEST_DUMP(i->ifi_flags,IFF_NOTRAILERS);
1019    FLAG_TEST_DUMP(i->ifi_flags,IFF_RUNNING);
1020    FLAG_TEST_DUMP(i->ifi_flags,IFF_NOARP);
1021    FLAG_TEST_DUMP(i->ifi_flags,IFF_PROMISC);
1022    FLAG_TEST_DUMP(i->ifi_flags,IFF_ALLMULTI);
1023    FLAG_TEST_DUMP(i->ifi_flags,IFF_MASTER);
1024    FLAG_TEST_DUMP(i->ifi_flags,IFF_SLAVE);
1025    FLAG_TEST_DUMP(i->ifi_flags,IFF_MULTICAST);
1026    FLAG_TEST_DUMP(i->ifi_flags,IFF_PORTSEL);
1027    FLAG_TEST_DUMP(i->ifi_flags,IFF_AUTOMEDIA);
1028    FLAG_TEST_DUMP(i->ifi_flags,IFF_DYNAMIC);
1029
1030    netlink_dump_rta(IFLA_RTA(i), l, i->ifi_family);
1031
1032    fprintf(stderr,"\n");
1033
1034    break;
1035  case RTM_DELLINK:
1036    fprintf(stderr,"RTM_DELLINK\n");
1037
1038    i = NLMSG_DATA(n);
1039    l = NLMSG_PAYLOAD(n, sizeof(struct ifinfomsg));
1040
1041    fprintf(stderr, "ifinfomsg: %u %u %d %u %u ", i->ifi_family, i->ifi_type, i->ifi_index, i->ifi_flags, i->ifi_change);
1042
1043    FLAG_TEST_DUMP(i->ifi_flags, IFF_UP);
1044    FLAG_TEST_DUMP(i->ifi_flags, IFF_BROADCAST);
1045    FLAG_TEST_DUMP(i->ifi_flags, IFF_DEBUG);
1046    FLAG_TEST_DUMP(i->ifi_flags, IFF_LOOPBACK);
1047    FLAG_TEST_DUMP(i->ifi_flags, IFF_POINTOPOINT);
1048    FLAG_TEST_DUMP(i->ifi_flags, IFF_NOTRAILERS);
1049    FLAG_TEST_DUMP(i->ifi_flags, IFF_RUNNING);
1050    FLAG_TEST_DUMP(i->ifi_flags, IFF_NOARP);
1051    FLAG_TEST_DUMP(i->ifi_flags, IFF_PROMISC);
1052    FLAG_TEST_DUMP(i->ifi_flags, IFF_ALLMULTI);
1053    FLAG_TEST_DUMP(i->ifi_flags, IFF_MASTER);
1054    FLAG_TEST_DUMP(i->ifi_flags, IFF_SLAVE);
1055    FLAG_TEST_DUMP(i->ifi_flags, IFF_MULTICAST);
1056    FLAG_TEST_DUMP(i->ifi_flags, IFF_PORTSEL);
1057    FLAG_TEST_DUMP(i->ifi_flags, IFF_AUTOMEDIA);
1058    FLAG_TEST_DUMP(i->ifi_flags, IFF_DYNAMIC);
1059
1060    netlink_dump_rta(IFLA_RTA(i), l, i->ifi_family);
1061
1062    fprintf(stderr, "\n");
1063
1064    break;
1065  case RTM_NEWADDR:
1066    fprintf(stderr, "RTM_NEWADDR\n");
1067
1068    a = NLMSG_DATA(n);
1069    l = NLMSG_PAYLOAD(n, sizeof(struct ifaddrmsg));
1070
1071    fprintf(stderr, "ifaddrmsg: %u %u %u %u %d",
1072	    a->ifa_family, a->ifa_prefixlen,
1073	    a->ifa_flags, a->ifa_scope, a->ifa_index);
1074
1075    switch (a->ifa_family){
1076    case AF_INET:
1077      fprintf(stderr, " AF_INET ");
1078      break;
1079    case AF_INET6:
1080      fprintf(stderr, " AF_INET6 ");
1081      break;
1082    default:
1083      fprintf(stderr, " AF unknown ");
1084      break;
1085    }
1086
1087    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_SECONDARY);
1088    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_DEPRECATED);
1089    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_TENTATIVE);
1090    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_PERMANENT);
1091
1092    netlink_dump_rta(IFA_RTA(a), l, a->ifa_family);
1093
1094    fprintf(stderr, "\n");
1095
1096    break;
1097  case RTM_DELADDR:
1098    fprintf(stderr, "RTM_DELADDR\n");
1099
1100    a = NLMSG_DATA(n);
1101    l = NLMSG_PAYLOAD(n, sizeof(struct ifaddrmsg));
1102
1103    fprintf(stderr, "ifaddrmsg: %u %u %u %u %d",
1104	    a->ifa_family, a->ifa_prefixlen,
1105	    a->ifa_flags, a->ifa_scope, a->ifa_index);
1106
1107    switch (a->ifa_family){
1108    case AF_INET:
1109      fprintf(stderr, " AF_INET ");
1110      break;
1111    case AF_INET6:
1112      fprintf(stderr, " AF_INET6 ");
1113      break;
1114    default:
1115      fprintf(stderr, " AF unknown ");
1116      break;
1117    }
1118
1119    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_SECONDARY);
1120    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_DEPRECATED);
1121    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_TENTATIVE);
1122    FLAG_TEST_DUMP(a->ifa_flags, IFA_F_PERMANENT);
1123
1124    netlink_dump_rta(IFA_RTA(a), l, a->ifa_family);
1125
1126    fprintf(stderr, "\n");
1127    break;
1128  case RTM_NEWROUTE:
1129    fprintf(stderr, "RTM_NEWROUTE\n");
1130
1131    r = NLMSG_DATA(n);
1132    l = NLMSG_PAYLOAD(n, sizeof(struct rtmsg));
1133
1134    fprintf(stderr, "rtmsg: %u %u %u %u %u %u %u %u %u",
1135	    r->rtm_family, r->rtm_dst_len, r->rtm_src_len,
1136	    r->rtm_tos, r->rtm_table, r->rtm_protocol,
1137	    r->rtm_scope, r->rtm_type, r->rtm_flags);
1138
1139    switch (r->rtm_family){
1140    case AF_INET:
1141      fprintf(stderr, " AF_INET ");
1142      break;
1143    case AF_INET6:
1144      fprintf(stderr, " AF_INET6 ");
1145      break;
1146    default:
1147      fprintf(stderr, " AF unknown ");
1148      break;
1149    }
1150
1151    FLAG_TEST_DUMP(r->rtm_flags, RTM_F_NOTIFY);
1152    FLAG_TEST_DUMP(r->rtm_flags, RTM_F_CLONED);
1153    FLAG_TEST_DUMP(r->rtm_flags, RTM_F_EQUALIZE);
1154
1155    netlink_dump_rta(RTM_RTA(r), l, r->rtm_family);
1156
1157    fprintf(stderr, "\n");
1158    break;
1159  case RTM_DELROUTE:
1160    fprintf(stderr, "RTM_DELROUTE\n");
1161
1162    r = NLMSG_DATA(n);
1163    l = NLMSG_PAYLOAD(n, sizeof(struct rtmsg));
1164
1165    fprintf(stderr, "rtmsg: %u %u %u %u %u %u %u %u %u",
1166	    r->rtm_family, r->rtm_dst_len, r->rtm_src_len,
1167	    r->rtm_tos, r->rtm_table, r->rtm_protocol,
1168	    r->rtm_scope, r->rtm_type, r->rtm_flags);
1169
1170    switch (r->rtm_family){
1171    case AF_INET:
1172      fprintf(stderr, " AF_INET ");
1173      break;
1174    case AF_INET6:
1175      fprintf(stderr, " AF_INET6 ");
1176      break;
1177    default:
1178      fprintf(stderr, " AF unknown ");
1179      break;
1180    }
1181
1182    FLAG_TEST_DUMP(r->rtm_flags, RTM_F_NOTIFY);
1183    FLAG_TEST_DUMP(r->rtm_flags, RTM_F_CLONED);
1184    FLAG_TEST_DUMP(r->rtm_flags, RTM_F_EQUALIZE);
1185
1186    netlink_dump_rta(RTM_RTA(r), l, r->rtm_family);
1187
1188    fprintf(stderr, "\n");
1189    break;
1190  }
1191
1192  fprintf(stderr, "\n");
1193}
1194
1195
1196void netlink_dump_rta(struct rtattr *rta, int length, int family)
1197{
1198
1199  struct rtnl_link_stats *stats;
1200  struct rtnl_link_ifmap *map;
1201  unsigned char          *addr;
1202
1203  /* family is a kludge so we know what format to
1204   * print IFLA_ADDRESS and IFLA_BROADCAST in
1205   */
1206
1207  while (RTA_OK(rta, length)) {
1208
1209    fprintf(stderr, ", %u %u:", rta->rta_len, rta->rta_type);
1210
1211    switch(rta->rta_type) {
1212    case IFLA_UNSPEC:
1213      fprintf(stderr, "IFLA_UNSPEC");
1214      break;
1215    case IFLA_ADDRESS:
1216      fprintf(stderr, "IFLA_ADDRESS ");
1217      addr = (unsigned char *)RTA_DATA(rta);
1218      switch (family) {
1219      case AF_INET:
1220	fprintf(stderr, "%u.%u.%u.%u", addr[0], addr[1], addr[2], addr[3]);
1221	break;
1222      default:
1223	/* assume only print 6 - it's wrong but I can't see a better way */
1224	fprintf(stderr, "%02X:%02X:%02X:%02X:%02X:%02X",
1225		addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1226	break;
1227      }
1228      break;
1229    case IFLA_BROADCAST:
1230      fprintf(stderr, "IFLA_BROADCAST ");
1231      addr = (unsigned char *)RTA_DATA(rta);
1232      switch (family) {
1233      case AF_INET:
1234	fprintf(stderr, "%u.%u.%u.%u", addr[0], addr[1], addr[2], addr[3]);
1235	break;
1236      default:
1237	/* assume only print 6 - it's wrong but I can't see a better way */
1238	fprintf(stderr, "%02X:%02X:%02X:%02X:%02X:%02X",
1239		addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1240	break;
1241      }
1242      break;
1243    case IFLA_IFNAME:
1244      fprintf(stderr, "IFLA_IFNAME: %s", (char *)RTA_DATA(rta));
1245      break;
1246    case IFLA_MTU:
1247      fprintf(stderr, "IFLA_MTU: %u", (unsigned int)RTA_DATA(rta));
1248      break;
1249    case IFLA_LINK:
1250      fprintf(stderr, "IFLA_LINK: %d", (int)RTA_DATA(rta));
1251      break;
1252    case IFLA_QDISC:
1253      fprintf(stderr, "IFLA_QDISC: %s", (char *)RTA_DATA(rta));
1254      break;
1255    case IFLA_STATS:
1256      fprintf(stderr, "IFLA_STATS");
1257      stats = (struct rtnl_link_stats *)RTA_DATA(rta);
1258      break;
1259    case IFLA_COST:
1260      fprintf(stderr, "IFLA_COST");
1261      break;
1262    case IFLA_PRIORITY:
1263      fprintf(stderr, "IFLA_PRIORITY");
1264      break;
1265    case IFLA_MASTER:
1266      fprintf(stderr, "IFLA_MASTER: %u", (unsigned int)RTA_DATA(rta));
1267      break;
1268    case IFLA_WIRELESS:
1269      fprintf(stderr, "IFLA_WIRELESS");
1270      break;
1271    case IFLA_PROTINFO:
1272      fprintf(stderr, "IFLA_PROTINFO");
1273      break;
1274    case IFLA_TXQLEN:
1275      fprintf(stderr, "IFLA_TXQLEN: %u", (unsigned int)RTA_DATA(rta));
1276      break;
1277    case IFLA_MAP:
1278      map = (struct rtnl_link_ifmap *)RTA_DATA(rta);
1279      fprintf(stderr, "IFLA_MAP");
1280      break;
1281    case IFLA_WEIGHT:
1282      fprintf(stderr, "IFLA_WEIGHT: %u", (unsigned int)RTA_DATA(rta));
1283      break;
1284    default:
1285      fprintf(stderr, "unhandled rta type");
1286      break;
1287    }
1288
1289    rta = RTA_NEXT(rta, length);
1290  }
1291
1292}
1293
1294int netlink_is_link_up(struct intf *intf, struct nlmsghdr *n)
1295{
1296
1297  struct ifinfomsg *i;
1298
1299  if (!n)
1300    return intf->up;
1301
1302  if (n->nlmsg_type != RTM_NEWLINK)
1303    return intf->up;
1304
1305  i = NLMSG_DATA(n);
1306
1307  if (intf->index != i->ifi_index)
1308    return intf->up;
1309
1310  return ((i->ifi_flags & IFF_RUNNING) == IFF_RUNNING);
1311
1312}
1313
1314int netlink_is_from_us(struct nlmsghdr *n)
1315{
1316  /* NOTE: does not handle case when n is NULL */
1317
1318  /*
1319   * if the netlink message came from
1320   * either the kernel or our process id
1321   * return 1 otherwise return 0
1322   */
1323
1324  if ((n->nlmsg_pid == 0 /* kernel */) ||
1325      (n->nlmsg_pid == mypid))
1326    return 1;
1327
1328  return 0;
1329
1330}
1331
1332int netlink_qualify(struct nlmsghdr *n, size_t length)
1333{
1334  if (!NLMSG_OK(n, length) ||
1335      length < sizeof(struct nlmsghdr) ||
1336      length < n->nlmsg_len) {
1337    fprintf(stderr, "netlink: packet too small or truncated. %u!=%u!=%u",
1338	    length, sizeof(struct nlmsghdr), n->nlmsg_len);
1339    return -1;
1340  }
1341
1342  if (n->nlmsg_type == NLMSG_ERROR) {
1343    struct nlmsgerr *e = (struct nlmsgerr *) NLMSG_DATA(n);
1344
1345    if (e->error) {
1346      fprintf(stderr, "netlink error: %s\n", strerror(-e->error));
1347    }
1348    return -1;
1349  }
1350
1351  return 0;
1352}
1353
1354static
1355void netlink_addr_do(int nl, int op, struct intf *intf)
1356{
1357
1358  struct in_addr brd;
1359
1360  struct {
1361    struct nlmsghdr  n;
1362    struct ifaddrmsg a;
1363    char   opts[32];
1364  } req;
1365
1366  if (inet_aton("169.254.255.255", &brd) == 0) {
1367    fprintf(stderr, "couldn't generate broadcast address\n");
1368    exit(1);
1369  }
1370
1371  memset(&req, 0, sizeof(req));
1372
1373  req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
1374  req.n.nlmsg_type = op;
1375  req.n.nlmsg_flags = NLM_F_REQUEST;
1376
1377  req.a.ifa_family = AF_INET;
1378  req.a.ifa_prefixlen = 16; /* AIPPA is 169.254.0.0/16 */
1379  req.a.ifa_flags = IFA_F_PERMANENT;
1380  req.a.ifa_scope = RT_SCOPE_LINK;
1381  req.a.ifa_index = intf->index;
1382
1383  if (addattr_l(&req.n, sizeof(req),
1384		IFA_LOCAL, (void *)&intf->ip,
1385		sizeof(struct in_addr)) < 0) {
1386    fprintf(stderr, "addattr_l: unable to add IFA_LOCAL attribute to netlink message\n");
1387  }
1388
1389  if (addattr_l(&req.n, sizeof(req),
1390		IFA_BROADCAST, (void *)&brd,
1391		sizeof(struct in_addr)) < 0) {
1392    fprintf(stderr, "addattr_l: unable to add IFA_BROADCAST attribute to netlink message\n");
1393  }
1394
1395  if (netlink_send(nl, (struct nlmsghdr *)&req) < 0) {
1396    fprintf(stderr, "netlink_send(): %s\n", strerror(errno));
1397  }
1398}
1399
1400void netlink_addr_add(int nl, struct intf *intf)
1401{
1402
1403  netlink_addr_do(nl, RTM_NEWADDR, intf);
1404
1405}
1406
1407void netlink_addr_del(int nl, struct intf *intf)
1408{
1409
1410  netlink_addr_do(nl, RTM_DELADDR, intf);
1411
1412}
1413
1414int check_ifname_exists(int nl, struct intf *intf)
1415{
1416
1417#if 0
1418  /* in theory, the below should work. in practise it doesn't
1419   * so we use the more complicated netlink method to get the index
1420   */
1421  struct ifreq ifr;
1422
1423  memset( &ifr, 0, sizeof(struct ifreq));
1424  strncpy(ifr.ifr_name, int.name, sizeof(ifr.ifr_name));
1425
1426  if (ioctl(nl, SIOCGIFINDEX, &ifr) < 0) {
1427    fprintf(stderr, "ioctl SIOCGIFINDEX failed: %s\n", strerror(errno));
1428    return -1;
1429  }
1430
1431  intf->index = ifr.ifr_ifindex;
1432
1433  if (ioctl(nl, SIOCGIFFLAGS, &ifr) < 0) {
1434    fprintf(stderr, "ioctl SIOCGIFINDEX failed: %s\n", strerror(errno));
1435    return -1;
1436  }
1437
1438  intf->flags = ifr.ifr_flags;
1439
1440  return 0;
1441#else
1442  struct pollfd fds[1];
1443
1444  struct {
1445    struct nlmsghdr  n;
1446    struct ifinfomsg i;
1447    char             ifnamebuf[NLBUF];
1448  } req;
1449
1450  memset(&req, 0, sizeof(req));
1451  req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
1452  req.n.nlmsg_flags = NLM_F_REQUEST|NLM_F_MATCH;
1453  req.n.nlmsg_type = RTM_GETLINK;
1454  req.i.ifi_family = AF_UNSPEC;
1455  req.i.ifi_change = 0xffffffff;
1456
1457  if (addattr_l(&req.n, sizeof(req), IFLA_IFNAME, intf->name, IFNAMSIZ+1) < 0) {
1458    fprintf(stderr, "addattr_l: unable to add IFNAME attribute to netlink message\n");
1459    return -1;
1460  }
1461
1462
1463  if (netlink_send(nl, (struct nlmsghdr *)&req) < 0) {
1464    fprintf(stderr, "netlink_send(): %s\n", strerror(errno));
1465    return -1;
1466  }
1467
1468  /* wait up to 5 seconds for the kernel to decide
1469   * modprobe or udev might take that long
1470   */
1471  fds[0].fd = nl;
1472  fds[0].events = POLLIN|POLLERR;
1473
1474  switch (poll(fds, 1, 5*100)) {
1475  case -1:
1476    fprintf(stderr, "poll err: %s\n", strerror(errno));
1477    exit(1);
1478    break;
1479  case 0:
1480    fprintf(stderr, "couldn't find interface\n");
1481    return -1;
1482    break;
1483  case 1:
1484    {
1485      /* this is annoyingly complicated */
1486      if (verbose)
1487	fprintf(stderr, "we got a netlink message in %s\n", __FUNCTION__);
1488
1489      ssize_t  bytes;
1490      char replybuf[4096];
1491      struct nlmsghdr *n = (struct nlmsghdr *)&replybuf;
1492
1493      if ((bytes = recv(nl, replybuf, sizeof(replybuf), 0)) < 0) {
1494	fprintf(stderr, "recv(): %s\n", strerror(errno));
1495	return -1;
1496      }
1497
1498      for (; bytes > 0; n = NLMSG_NEXT(n, bytes)) {
1499
1500	if (netlink_qualify(n, (size_t)bytes)< 0)
1501	  return -1;
1502
1503	if (n->nlmsg_type == NLMSG_DONE) {
1504	  if (verbose)
1505	    fprintf(stderr, "finished processing RTM_GETLINK in %s\n", __FUNCTION__);
1506	  return intf->index;
1507	}
1508
1509	if (n->nlmsg_type != RTM_NEWLINK) {
1510	  fprintf(stderr, "received unexpected %u response\n", n->nlmsg_type);
1511	  return -1;
1512	}
1513
1514	netlink_is_our_iface(intf, n);
1515
1516      }
1517
1518      return intf->index;
1519
1520    }
1521    break;
1522  default:
1523    fprintf(stderr, "something abnormal happened in poll. aborting\n");
1524    exit(1);
1525    break;
1526  }
1527
1528  return -1;
1529#endif
1530}
1531
1532int check_ifname_type(struct intf *intf)
1533{
1534
1535  if ((intf->flags & IFF_NOARP) ||
1536      (intf->flags & IFF_LOOPBACK) ||
1537      (intf->flags & IFF_SLAVE) ||
1538      (intf->flags & IFF_POINTOPOINT))
1539    return -1;
1540
1541  return 0;
1542}
1543
1544int arp_open(struct intf *intf)
1545{
1546  int as;
1547  struct sockaddr_ll ll;
1548
1549  if ((as = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ARP))) < 0) {
1550    fprintf(stderr, "arp socket failed: %s\n", strerror(errno));
1551    return -1;
1552  }
1553
1554  memset(&ll, 0, sizeof(ll));
1555  ll.sll_family = AF_PACKET;
1556  ll.sll_ifindex = intf->index;
1557
1558  if (bind(as, (struct sockaddr *)&ll, sizeof(ll)) < 0) {
1559    fprintf(stderr, "arp bind failed: %s\n", strerror(errno));
1560    return -1;
1561  }
1562
1563  return as;
1564}
1565
1566void arp_packet_dump(struct arp_packet *pkt)
1567{
1568
1569  if (!pkt)
1570    return;
1571
1572  fprintf(stderr, "%d %d %d %d %d: ",
1573	  ntohs(pkt->arp.ar_hrd),
1574	  ntohs(pkt->arp.ar_pro),
1575	  pkt->arp.ar_hln,
1576	  pkt->arp.ar_pln,
1577	  ntohs(pkt->arp.ar_op));
1578
1579  /* ARP could possibly have various types of address formats
1580   * only Ethernet, IP protocol addresses and
1581   * ARP_REQUESTs or ARP_REPLYs are interesting
1582   */
1583  if ((ntohs(pkt->arp.ar_hrd) != ARPHRD_ETHER) &&
1584      (ntohs(pkt->arp.ar_pro) != ARP_IP_PROTO) &&
1585      (
1586       (ntohs(pkt->arp.ar_op) != ARPOP_REQUEST) ||
1587       (ntohs(pkt->arp.ar_op) != ARPOP_REPLY)
1588      )
1589     ) {
1590    fprintf(stderr, "unhandled kind of ARP packet\n");
1591    return;
1592  }
1593
1594  fprintf(stderr, "%02X:%02X:%02X:%02X:%02X:%02X",
1595	  pkt->sender_mac.ether_addr_octet[0],
1596	  pkt->sender_mac.ether_addr_octet[1],
1597	  pkt->sender_mac.ether_addr_octet[2],
1598	  pkt->sender_mac.ether_addr_octet[3],
1599	  pkt->sender_mac.ether_addr_octet[4],
1600	  pkt->sender_mac.ether_addr_octet[5]);
1601
1602  fprintf(stderr, " %s", inet_ntoa(pkt->sender_ip));
1603
1604  fprintf(stderr, " -> ");
1605
1606  fprintf(stderr, "%02X:%02X:%02X:%02X:%02X:%02X",
1607	  pkt->target_mac.ether_addr_octet[0],
1608	  pkt->target_mac.ether_addr_octet[1],
1609	  pkt->target_mac.ether_addr_octet[2],
1610	  pkt->target_mac.ether_addr_octet[3],
1611	  pkt->target_mac.ether_addr_octet[4],
1612	  pkt->target_mac.ether_addr_octet[5]);
1613
1614  fprintf(stderr, " %s", inet_ntoa(pkt->target_ip));
1615
1616  fprintf(stderr, "\n");
1617}
1618
1619/* while the RFC (and my design) notes that there are three
1620 * ways to detect a conflict, those three collapse readily
1621 * into just these two required tests
1622 */
1623int  arp_conflict(struct intf *intf, struct arp_packet *pkt)
1624{
1625  if (!pkt)
1626    return 0;
1627
1628  /* handles 2.2.1: ARP packet (request or reply)
1629   * handles 2.5  : ARP packet (request of reply)
1630   * sender IP is our probe address
1631   */
1632  /* Foxconn modified start pling 02/25/2011 */
1633  /* In addition to packet "sender IP" == Interface IP,
1634   * add condition: packet "src MAC" != Interface MAC
1635   */
1636#if 0
1637  if (memcmp(&intf->ip, &pkt->sender_ip, sizeof(struct in_addr)) == 0)
1638#endif
1639  if ((memcmp(&intf->ip, &pkt->sender_ip, sizeof(struct in_addr)) == 0) &&
1640      (memcmp(&intf->mac, &pkt->sender_mac, sizeof(struct ether_addr)) != 0))
1641  /* Foxconn modified end pling 02/25/2011 */
1642  {
1643    printf("ARP conflict#1: sender IP:%ssender MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
1644            inet_ntoa(pkt->sender_ip),
1645            pkt->sender_mac.ether_addr_octet[0],
1646    	    pkt->sender_mac.ether_addr_octet[1],
1647	        pkt->sender_mac.ether_addr_octet[2],
1648    	    pkt->sender_mac.ether_addr_octet[3],
1649	        pkt->sender_mac.ether_addr_octet[4],
1650      	    pkt->sender_mac.ether_addr_octet[5]);
1651    return 1;
1652  }
1653
1654  /* handles 2.2.1: ARP packet (ARP PROBE)
1655   * sender HW address is not our MAC address
1656   * target IP address is our probe address
1657   */
1658  if ((ntohs(pkt->arp.ar_op) == ARPOP_REQUEST) &&
1659      (memcmp(&intf->mac, &pkt->sender_mac, sizeof(struct ether_addr)) != 0) &&
1660      (memcmp(&intf->ip, &pkt->target_ip, sizeof(struct in_addr)) == 0))
1661  {
1662    printf("ARP conflict#2: sender MAC %02x:%02x:%02x:%02x:%02x:%02x, target IP: %s\n",
1663            pkt->sender_mac.ether_addr_octet[0],
1664	        pkt->sender_mac.ether_addr_octet[1],
1665 	        pkt->sender_mac.ether_addr_octet[2],
1666	        pkt->sender_mac.ether_addr_octet[3],
1667	        pkt->sender_mac.ether_addr_octet[4],
1668	        pkt->sender_mac.ether_addr_octet[5],
1669            inet_ntoa(pkt->target_ip));
1670    return 1;
1671  }
1672
1673  return 0;
1674
1675}
1676
1677/* Foxconn added start pling 02/25/2011 */
1678/* At DEFEND state, we only check the ARP packet's
1679 * sender IP is same as our IP or not.
1680 */
1681int  arp_conflict_defend(struct intf *intf, struct arp_packet *pkt)
1682{
1683  if (!pkt)
1684    return 0;
1685
1686  /* handles 2.2.1: ARP packet (request or reply)
1687   * handles 2.5  : ARP packet (request of reply)
1688   * sender IP is our probe address
1689   */
1690  if ((memcmp(&intf->ip, &pkt->sender_ip, sizeof(struct in_addr)) == 0) &&
1691      (memcmp(&intf->mac, &pkt->sender_mac, sizeof(struct ether_addr)) != 0))
1692  {
1693    printf("ARP conflict@DEFEND: sender IP:%ssender MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
1694            inet_ntoa(pkt->sender_ip),
1695            pkt->sender_mac.ether_addr_octet[0],
1696    	    pkt->sender_mac.ether_addr_octet[1],
1697	        pkt->sender_mac.ether_addr_octet[2],
1698    	    pkt->sender_mac.ether_addr_octet[3],
1699	        pkt->sender_mac.ether_addr_octet[4],
1700      	    pkt->sender_mac.ether_addr_octet[5]);
1701    return 1;
1702  }
1703  return 0;
1704}
1705
1706
1707void arp_packet_send(int as,
1708		     struct intf *intf,
1709		     short int arp_op,
1710		     int null_sender)
1711{
1712
1713  struct arp_packet  ap;
1714  struct sockaddr_ll ll;
1715  ssize_t ret;
1716
1717  memset(&ap, 0, sizeof(struct arp_packet));
1718
1719  ap.arp.ar_hrd = htons(ARPHRD_ETHER);
1720  ap.arp.ar_pro = htons(ARP_IP_PROTO);
1721  ap.arp.ar_hln = ETH_ALEN;
1722  ap.arp.ar_pln = 4; /* octets in IPv4 address */
1723  ap.arp.ar_op = htons(arp_op);
1724
1725  /* filling with 0xff sets the destination to
1726   * the broadcast link-layer address for free
1727   */
1728  memset(&ll, 0xff, sizeof(struct sockaddr_ll));
1729  ll.sll_family = AF_PACKET;
1730  ll.sll_protocol = htons(ETH_P_ARP);
1731  ll.sll_ifindex = intf->index;
1732  ll.sll_halen = ETH_ALEN;
1733
1734  memcpy(&ap.sender_mac, &intf->mac, sizeof(struct ether_addr));
1735  memcpy(&ap.target_ip, &intf->ip, sizeof(struct in_addr));
1736
1737  if (!null_sender)
1738    memcpy(&ap.sender_ip, &intf->ip, sizeof(struct in_addr));
1739
1740  ret = sendto(as, (void *)&ap,
1741	       sizeof(struct arp_packet), 0,
1742	       (struct sockaddr *)&ll, sizeof(struct sockaddr_ll));
1743
1744  if (ret < 0) {
1745     fprintf(stderr,"failed to send ARP packet: %s\n", strerror(errno));
1746    if (errno == ENETDOWN) {
1747      intf->up = 0;
1748    }
1749  }
1750
1751}
1752
1753void arp_probe(int as, struct intf *intf)
1754{
1755
1756  arp_packet_send(as, intf, ARPOP_REQUEST, 1);
1757
1758}
1759
1760void arp_claim(int as, struct intf *intf)
1761{
1762
1763  arp_packet_send(as, intf, ARPOP_REQUEST, 0);
1764
1765}
1766
1767void arp_defend(int as, struct intf *intf)
1768{
1769
1770  arp_packet_send(as, intf, ARPOP_REPLY, 0);
1771
1772}
1773
1774void usage(void)
1775{
1776  fprintf(stderr, "usage error\n");
1777  fprintf(stderr, "zeroconf [-f|--force] [-v|--verbose] [-n|--no-fork] [-i|--interface] <interface>\n");
1778  fprintf(stderr, "where:\n");
1779  fprintf(stderr, "\t-f\tforce zeroconf to run on the specified interface\n");
1780  fprintf(stderr, "\t-v\treport verbose information\n");
1781  fprintf(stderr, "\t-n\tdo not fork into the background\n");
1782  fprintf(stderr, "\t-i\twhich interface to run on [required]\n");
1783  exit(1);
1784}
1785
1786
1787int signal_install(int signo)
1788{
1789
1790  sigset_t         signals;
1791  struct sigaction sighdlr = {
1792    .sa_handler = sig_handler,
1793    .sa_flags = SA_RESTART,
1794  };
1795
1796  if (sigemptyset(&signals) < 0) {
1797    fprintf(stderr, "unable to clear signal set: %s\n", strerror(errno));
1798    return -1;
1799  }
1800
1801  if (sigaddset(&signals, signo) < 0) {
1802    fprintf(stderr, "unable to add signal to set: %s\n", strerror(errno));
1803    return -1;
1804  }
1805
1806  if (sigaction(signo, &sighdlr, NULL ) < 0) {
1807    fprintf(stderr, "unable to set signal handler: %s\n", strerror(errno));
1808    return -1;
1809  }
1810
1811  if (sigprocmask(SIG_UNBLOCK, &signals, NULL) < 0) {
1812    fprintf(stderr, "unable to unblock %d: %s\n", signo, strerror(errno));
1813    return -1;
1814  }
1815
1816  return 0;
1817}
1818
1819int addattr_l(struct nlmsghdr *n,
1820	      unsigned int maxlen,
1821	      int type,
1822	      const void *data,
1823	      int alen)
1824{
1825	int len = RTA_LENGTH(alen);
1826	struct rtattr *rta;
1827
1828	if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) {
1829		fprintf(stderr, "addattr_l ERROR: message exceeded bound of %d\n", maxlen);
1830		return -1;
1831	}
1832	rta = (struct rtattr*)(((char*)n) + NLMSG_ALIGN(n->nlmsg_len));
1833	rta->rta_type = type;
1834	rta->rta_len = len;
1835	memcpy(RTA_DATA(rta), data, alen);
1836	n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len;
1837	return 0;
1838}
1839
1840
1841void netlink_is_our_iface(struct intf *intf, struct nlmsghdr *n)
1842{
1843
1844  struct ifinfomsg *i   = NULL;
1845  struct rtattr    *rta = NULL;
1846  int len;
1847
1848  i   = NLMSG_DATA(n);
1849  len = NLMSG_PAYLOAD(n, sizeof(struct ifinfomsg));
1850  rta = IFLA_RTA(i);
1851
1852  while (RTA_OK(rta, len)) {
1853
1854    if (rta->rta_type == IFLA_IFNAME) {
1855      if (verbose)
1856	fprintf(stderr, "got iface %d:%s\n", i->ifi_index,
1857		                             (char *)RTA_DATA(rta));
1858
1859      if (!strncmp(intf->name, RTA_DATA(rta), strlen(intf->name))) {
1860	intf->index = i->ifi_index;
1861	intf->flags = i->ifi_flags;
1862	intf->up = ((i->ifi_flags & IFF_RUNNING) == IFF_RUNNING);
1863      } else {
1864	break;
1865      }
1866    }
1867
1868    if (rta->rta_type == IFLA_ADDRESS) {
1869      unsigned char *addr;
1870
1871      addr = (unsigned char *)RTA_DATA(rta);
1872
1873      intf->mac.ether_addr_octet[0] = addr[0];
1874      intf->mac.ether_addr_octet[1] = addr[1];
1875      intf->mac.ether_addr_octet[2] = addr[2];
1876      intf->mac.ether_addr_octet[3] = addr[3];
1877      intf->mac.ether_addr_octet[4] = addr[4];
1878      intf->mac.ether_addr_octet[5] = addr[5];
1879    }
1880
1881    rta = RTA_NEXT(rta, len);
1882  }
1883}
1884