4 This file is part of avahi.
6 avahi is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 avahi is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
14 Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with avahi; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
26 #include <sys/param.h>
27 #include <sys/types.h>
29 #include <sys/ioctl.h>
30 #include <sys/socket.h>
33 #include <sys/sysctl.h>
37 #include <netpacket/packet.h>
39 #include <net/ethernet.h>
42 #include <net/if_dl.h>
43 #include <net/route.h>
45 #include <arpa/inet.h>
67 #include <avahi-common/malloc.h>
68 #include <avahi-common/timeval.h>
69 #include <avahi-daemon/setproctitle.h>
71 #include <libdaemon/dfork.h>
72 #include <libdaemon/dsignal.h>
73 #include <libdaemon/dlog.h>
74 #include <libdaemon/dpid.h>
75 #include <libdaemon/dexec.h>
80 /* An implementation of RFC 3927 */
82 /* Constants from the RFC */
87 #define ANNOUNCE_WAIT 2
88 #define ANNOUNCE_NUM 2
89 #define ANNOUNCE_INTERVAL 2
90 #define MAX_CONFLICTS 10
91 #define RATE_LIMIT_INTERVAL 60
92 #define DEFEND_INTERVAL 10
94 #define IPV4LL_NETWORK 0xA9FE0000L
95 #define IPV4LL_NETMASK 0xFFFF0000L
96 #define IPV4LL_HOSTMASK 0x0000FFFFL
97 #define IPV4LL_BROADCAST 0xA9FEFFFFL
99 #define ETHER_ADDRLEN 6
100 #define ETHER_HDR_SIZE (2+2*ETHER_ADDRLEN)
101 #define ARP_PACKET_SIZE (8+4+4+2*ETHER_ADDRLEN)
103 typedef enum ArpOperation {
108 typedef struct ArpPacketInfo {
109 ArpOperation operation;
111 uint32_t sender_ip_address, target_ip_address;
112 uint8_t sender_hw_address[ETHER_ADDRLEN], target_hw_address[ETHER_ADDRLEN];
115 typedef struct ArpPacket {
116 uint8_t *ether_header;
117 uint8_t *ether_payload;
120 static State state = STATE_START;
121 static int n_iteration = 0;
122 static int n_conflict = 0;
124 static char *interface_name = NULL;
125 static char *pid_file_name = NULL;
126 static uint32_t start_address = 0;
127 static char *argv0 = NULL;
128 static int daemonize = 0;
129 static int wait_for_address = 0;
130 static int use_syslog = 0;
131 static int debug = 0;
132 static int modify_proc_title = 1;
133 static int force_bind = 0;
135 static int no_chroot = 0;
137 static int no_drop_root = 0;
138 static int wrote_pid_file = 0;
147 } command = DAEMON_RUN;
149 typedef enum CalloutEvent {
157 static const char * const callout_event_table[CALLOUT_MAX] = {
158 [CALLOUT_BIND] = "BIND",
159 [CALLOUT_CONFLICT] = "CONFLICT",
160 [CALLOUT_UNBIND] = "UNBIND",
161 [CALLOUT_STOP] = "STOP"
164 typedef struct CalloutEventInfo {
170 #define RANDOM_DEVICE "/dev/urandom"
172 #define DEBUG(x) do {\
178 static void init_rand_seed(void) {
182 /* Try to initialize seed from /dev/urandom, to make it a little
183 * less predictable, and to make sure that multiple machines
184 * booted at the same time choose different random seeds. */
185 if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
186 read(fd, &seed, sizeof(seed));
190 /* If the initialization failed by some reason, we add the time to the seed */
191 seed ^= (unsigned) time(NULL);
196 static uint32_t pick_addr(uint32_t old_addr) {
200 unsigned r = (unsigned) rand();
202 /* Reduce to 16 bits */
204 r = (r >> 16) ^ (r & 0xFFFF);
206 addr = htonl(IPV4LL_NETWORK | (uint32_t) r);
208 } while (addr == old_addr || !is_ll_address(addr));
213 static int load_address(const char *fn, uint32_t *addr) {
220 if (!(f = fopen(fn, "r"))) {
222 if (errno == ENOENT) {
227 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
231 if (fscanf(f, "%u.%u.%u.%u\n", &a, &b, &c, &d) != 4) {
232 daemon_log(LOG_ERR, "Parse failure");
238 *addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
248 static int save_address(const char *fn, uint32_t addr) {
254 if (!(f = fopen(fn, "w"))) {
255 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
259 fprintf(f, "%s\n", inet_ntop(AF_INET, &addr, buf, sizeof (buf)));
272 * Allocate a buffer with two pointers in front, one of which is
273 * guaranteed to point ETHER_HDR_SIZE bytes into it.
275 static ArpPacket* packet_new(size_t packet_len) {
279 assert(packet_len > 0);
282 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + packet_len);
284 p->ether_header = NULL;
285 p->ether_payload = b + sizeof(struct ArpPacket);
288 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + ETHER_HDR_SIZE + packet_len);
290 p->ether_header = b + sizeof(struct ArpPacket);
291 p->ether_payload = b + sizeof(struct ArpPacket) + ETHER_HDR_SIZE;
297 static ArpPacket* packet_new_with_info(const ArpPacketInfo *info, size_t *packet_len) {
302 assert(info->operation == ARP_REQUEST || info->operation == ARP_RESPONSE);
303 assert(packet_len != NULL);
305 *packet_len = ARP_PACKET_SIZE;
306 p = packet_new(*packet_len);
307 r = p->ether_payload;
309 r[1] = 1; /* HTYPE */
310 r[2] = 8; /* PTYPE */
311 r[4] = ETHER_ADDRLEN; /* HLEN */
313 r[7] = (uint8_t) info->operation;
315 memcpy(r+8, info->sender_hw_address, ETHER_ADDRLEN);
316 memcpy(r+14, &info->sender_ip_address, 4);
317 memcpy(r+18, info->target_hw_address, ETHER_ADDRLEN);
318 memcpy(r+24, &info->target_ip_address, 4);
323 static ArpPacket *packet_new_probe(uint32_t ip_address, const uint8_t*hw_address, size_t *packet_len) {
326 memset(&info, 0, sizeof(info));
327 info.operation = ARP_REQUEST;
328 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
329 info.target_ip_address = ip_address;
331 return packet_new_with_info(&info, packet_len);
334 static ArpPacket *packet_new_announcement(uint32_t ip_address, const uint8_t* hw_address, size_t *packet_len) {
337 memset(&info, 0, sizeof(info));
338 info.operation = ARP_REQUEST;
339 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
340 info.target_ip_address = ip_address;
341 info.sender_ip_address = ip_address;
343 return packet_new_with_info(&info, packet_len);
346 static int packet_parse(const ArpPacket *packet, size_t packet_len, ArpPacketInfo *info) {
350 p = (uint8_t *)packet->ether_payload;
353 if (packet_len < ARP_PACKET_SIZE)
356 /* Check HTYPE and PTYPE */
357 if (p[0] != 0 || p[1] != 1 || p[2] != 8 || p[3] != 0)
360 /* Check HLEN, PLEN, OPERATION */
361 if (p[4] != ETHER_ADDRLEN || p[5] != 4 || p[6] != 0 || (p[7] != 1 && p[7] != 2))
364 info->operation = p[7];
365 memcpy(info->sender_hw_address, p+8, ETHER_ADDRLEN);
366 memcpy(&info->sender_ip_address, p+14, 4);
367 memcpy(info->target_hw_address, p+18, ETHER_ADDRLEN);
368 memcpy(&info->target_ip_address, p+24, 4);
373 static void set_state(State st, int reset_counter, uint32_t address) {
374 static const char* const state_table[] = {
375 [STATE_START] = "START",
376 [STATE_WAITING_PROBE] = "WAITING_PROBE",
377 [STATE_PROBING] = "PROBING",
378 [STATE_WAITING_ANNOUNCE] = "WAITING_ANNOUNCE",
379 [STATE_ANNOUNCING] = "ANNOUNCING",
380 [STATE_RUNNING] = "RUNNING",
381 [STATE_SLEEPING] = "SLEEPING"
385 assert(st < STATE_MAX);
387 if (st == state && !reset_counter) {
389 DEBUG(daemon_log(LOG_DEBUG, "State iteration %s-%i", state_table[state], n_iteration));
391 DEBUG(daemon_log(LOG_DEBUG, "State transition %s-%i -> %s-0", state_table[state], n_iteration, state_table[st]));
396 if (state == STATE_SLEEPING)
397 avahi_set_proc_title(argv0, "%s: [%s] sleeping", argv0, interface_name);
398 else if (state == STATE_ANNOUNCING)
399 avahi_set_proc_title(argv0, "%s: [%s] announcing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
400 else if (state == STATE_RUNNING)
401 avahi_set_proc_title(argv0, "%s: [%s] bound %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
403 avahi_set_proc_title(argv0, "%s: [%s] probing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
406 static int interface_up(int iface) {
410 if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
411 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
415 memset(&ifreq, 0, sizeof(ifreq));
416 if (!if_indextoname(iface, ifreq.ifr_name)) {
417 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
421 if (ioctl(fd, SIOCGIFFLAGS, &ifreq) < 0) {
422 daemon_log(LOG_ERR, "SIOCGIFFLAGS failed: %s", strerror(errno));
426 ifreq.ifr_flags |= IFF_UP;
428 if (ioctl(fd, SIOCSIFFLAGS, &ifreq) < 0) {
429 daemon_log(LOG_ERR, "SIOCSIFFLAGS failed: %s", strerror(errno));
446 /* Linux 'packet socket' specific implementation */
448 static int open_socket(int iface, uint8_t *hw_address) {
450 struct sockaddr_ll sa;
453 if (interface_up(iface) < 0)
456 if ((fd = socket(PF_PACKET, SOCK_DGRAM, 0)) < 0) {
457 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
461 memset(&sa, 0, sizeof(sa));
462 sa.sll_family = AF_PACKET;
463 sa.sll_protocol = htons(ETH_P_ARP);
464 sa.sll_ifindex = iface;
466 if (bind(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
467 daemon_log(LOG_ERR, "bind() failed: %s", strerror(errno));
472 if (getsockname(fd, (struct sockaddr*) &sa, &sa_len) < 0) {
473 daemon_log(LOG_ERR, "getsockname() failed: %s", strerror(errno));
477 if (sa.sll_halen != ETHER_ADDRLEN) {
478 daemon_log(LOG_ERR, "getsockname() returned invalid hardware address.");
482 memcpy(hw_address, sa.sll_addr, ETHER_ADDRLEN);
493 static int send_packet(int fd, int iface, ArpPacket *packet, size_t packet_len) {
494 struct sockaddr_ll sa;
498 assert(packet_len > 0);
500 memset(&sa, 0, sizeof(sa));
501 sa.sll_family = AF_PACKET;
502 sa.sll_protocol = htons(ETH_P_ARP);
503 sa.sll_ifindex = iface;
504 sa.sll_halen = ETHER_ADDRLEN;
505 memset(sa.sll_addr, 0xFF, ETHER_ADDRLEN);
507 if (sendto(fd, packet, packet_len, 0, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
508 daemon_log(LOG_ERR, "sendto() failed: %s", strerror(errno));
515 static int recv_packet(int fd, ArpPacket **packet, size_t *packet_len) {
517 struct sockaddr_ll sa;
527 if (ioctl(fd, FIONREAD, &s) < 0) {
528 daemon_log(LOG_ERR, "FIONREAD failed: %s", strerror(errno));
535 *packet = packet_new(s);
538 if ((r = recvfrom(fd, (*packet)->ether_payload, s, 0, (struct sockaddr*) &sa, &sa_len)) < 0) {
539 daemon_log(LOG_ERR, "recvfrom() failed: %s", strerror(errno));
543 *packet_len = (size_t) r;
557 close_socket(int fd) {
561 #else /* !__linux__ */
562 /* PCAP-based implementation */
565 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
566 static uint8_t __lladdr[ETHER_ADDRLEN];
569 #define elementsof(array) (sizeof(array)/sizeof(array[0]))
573 __get_ether_addr(int ifindex, u_char *lladdr)
577 struct if_msghdr *ifm;
580 struct sockaddr_dl *sdl;
587 mib[4] = NET_RT_IFLIST;
590 if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
591 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
598 daemon_log(LOG_ERR, "malloc(%d): %s", len, strerror(errno));
602 if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
603 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
610 for (next = buf; next < lim; next += ifm->ifm_msglen) {
611 ifm = (struct if_msghdr *)next;
612 if (ifm->ifm_type == RTM_IFINFO) {
613 sdl = (struct sockaddr_dl *)(ifm + 1);
614 memcpy(lladdr, LLADDR(sdl), ETHER_ADDRLEN);
623 open_socket(int iface, uint8_t *hw_address)
625 struct bpf_program bpf;
626 char ifname[IFNAMSIZ];
631 assert(__pp == NULL);
633 if (interface_up(iface) < 0) {
636 if (__get_ether_addr(iface, __lladdr) == -1) {
639 if (if_indextoname(iface, ifname) == NULL) {
643 pp = pcap_open_live(ifname, 1500, 0, 0, __pcap_errbuf);
647 err = pcap_set_datalink(pp, DLT_EN10MB);
649 daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
653 err = pcap_setdirection(pp, PCAP_D_IN);
655 daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
660 fd = pcap_get_selectable_fd(pp);
666 /* XXX: can we use this with pcap_next_ex() ? */
667 err = pcap_setnonblock(pp, 1, __pcap_errbuf);
674 err = pcap_compile(pp, &bpf,
675 "arp and ether dst ff:ff:ff:ff:ff:ff", 1, 0);
677 daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
681 err = pcap_setfilter(pp, &bpf);
683 daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
689 /* Stash pcap-specific context away. */
690 memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
697 close_socket(int fd __unused)
700 assert(__pp != NULL);
706 * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
707 * and prepend the required ethernet header information before sending.
710 send_packet(int fd __unused, int iface __unused, ArpPacket *packet,
713 struct ether_header *eh;
715 assert(__pp != NULL);
716 assert(packet != NULL);
718 eh = (struct ether_header *)packet->ether_header;
719 memset(eh->ether_dhost, 0xFF, ETHER_ADDRLEN);
720 memcpy(eh->ether_shost, __lladdr, ETHER_ADDRLEN);
721 eh->ether_type = htons(0x0806);
723 return (pcap_inject(__pp, (void *)eh, packet_len + sizeof(*eh)));
727 recv_packet(int fd __unused, ArpPacket **packet, size_t *packet_len)
729 struct pcap_pkthdr *ph;
735 assert(__pp != NULL);
736 assert(packet != NULL);
737 assert(packet_len != NULL);
743 err = pcap_next_ex(__pp, &ph, (const u_char **)&pd);
744 if (err == 1 && ph->caplen <= ph->len) {
745 ap = packet_new(ph->caplen);
746 memcpy(ap->ether_header, pd, ph->caplen);
748 *packet_len = (ph->caplen - sizeof(struct ether_header));
752 daemon_log(LOG_ERR, "pcap len > caplen");
754 daemon_log(LOG_ERR, "pcap_next_ex: %s",
761 #endif /* __linux__ */
763 int is_ll_address(uint32_t addr) {
765 (ntohl(addr) & IPV4LL_NETMASK) == IPV4LL_NETWORK &&
766 ntohl(addr) != IPV4LL_NETWORK &&
767 ntohl(addr) != IPV4LL_BROADCAST;
771 static struct timeval *elapse_time(struct timeval *tv, unsigned msec, unsigned jitter) {
774 gettimeofday(tv, NULL);
777 avahi_timeval_add(tv, (AvahiUsec) msec*1000);
780 avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
785 static FILE* fork_dispatcher(void) {
791 daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
795 if ((pid = fork()) < 0)
801 /* Please note that the signal pipe is not closed at this
802 * point, signals will thus be dispatched in the main
805 daemon_retval_done();
809 avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
813 if (!(f = fdopen(fds[0], "r"))) {
814 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
815 goto dispatcher_fail;
819 CalloutEventInfo info;
820 char name[IFNAMSIZ], buf[64];
823 if (fread(&info, sizeof(info), 1, f) != 1) {
827 daemon_log(LOG_ERR, "fread() failed: %s", strerror(errno));
828 goto dispatcher_fail;
831 assert(info.event <= CALLOUT_MAX);
833 if (!if_indextoname(info.ifindex, name)) {
834 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
838 if (daemon_exec("/", &k,
839 AVAHI_IPCONF_SCRIPT, AVAHI_IPCONF_SCRIPT,
840 callout_event_table[info.event],
842 inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
844 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
849 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
860 /* If the main process is trapped inside a chroot() we have to
861 * remove the PID file for it */
863 if (!no_chroot && wrote_pid_file)
864 daemon_pid_file_remove();
875 if (!(ret = fdopen(fds[1], "w"))) {
876 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
891 static int do_callout(FILE *f, CalloutEvent event, int iface, uint32_t addr) {
892 CalloutEventInfo info;
893 char buf[64], ifname[IFNAMSIZ];
895 daemon_log(LOG_INFO, "Callout %s, address %s on interface %s",
896 callout_event_table[event],
897 inet_ntop(AF_INET, &addr, buf, sizeof(buf)),
898 if_indextoname(iface, ifname));
901 info.ifindex = iface;
904 if (fwrite(&info, sizeof(info), 1, f) != 1 || fflush(f) != 0) {
905 daemon_log(LOG_ERR, "Failed to write callout event: %s", strerror(errno));
912 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
914 static int drop_privs(void) {
923 /* Get user/group ID */
927 if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
928 daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
932 if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
933 daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
937 daemon_log(LOG_INFO, "Found user '"AVAHI_AUTOIPD_USER"' (UID %lu) and group '"AVAHI_AUTOIPD_GROUP"' (GID %lu).", (unsigned long) pw->pw_uid, (unsigned long) gr->gr_gid);
940 /* Create directory */
942 r = mkdir(AVAHI_IPDATA_DIR, 0755);
945 if (r < 0 && errno != EEXIST) {
946 daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
950 /* Convey working directory */
955 chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
957 if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
958 daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
962 if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
963 daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
971 if (chroot(AVAHI_IPDATA_DIR) < 0) {
972 daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
976 daemon_log(LOG_INFO, "Successfully called chroot().");
979 /* Since we are now trapped inside a chroot we cannot remove
980 * the pid file anymore, the helper process will do that for us. */
988 if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
989 daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
993 #if defined(HAVE_SETRESGID)
994 r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
995 #elif defined(HAVE_SETEGID)
996 if ((r = setgid(gr->gr_gid)) >= 0)
997 r = setegid(gr->gr_gid);
998 #elif defined(HAVE_SETREGID)
999 r = setregid(gr->gr_gid, gr->gr_gid);
1001 #error "No API to drop priviliges"
1005 daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1009 #if defined(HAVE_SETRESUID)
1010 r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1011 #elif defined(HAVE_SETEUID)
1012 if ((r = setuid(pw->pw_uid)) >= 0)
1013 r = seteuid(pw->pw_uid);
1014 #elif defined(HAVE_SETREUID)
1015 r = setreuid(pw->pw_uid, pw->pw_uid);
1017 #error "No API to drop priviliges"
1021 daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1025 set_env("USER", pw->pw_name);
1026 set_env("LOGNAME", pw->pw_name);
1027 set_env("HOME", pw->pw_dir);
1029 daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1035 static int loop(int iface, uint32_t addr) {
1043 int fd = -1, ret = -1;
1044 struct timeval next_wakeup;
1045 int next_wakeup_valid = 0;
1047 ArpPacket *in_packet = NULL;
1048 size_t in_packet_len;
1049 ArpPacket *out_packet = NULL;
1050 size_t out_packet_len;
1051 uint8_t hw_address[ETHER_ADDRLEN];
1052 struct pollfd pollfds[FD_MAX];
1054 Event event = EVENT_NULL;
1055 int retval_sent = !daemonize;
1057 FILE *dispatcher = NULL;
1058 char *address_fn = NULL;
1061 daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP,0);
1063 if (!(dispatcher = fork_dispatcher()))
1066 if ((fd = open_socket(iface, hw_address)) < 0)
1069 if ((iface_fd = iface_init(iface)) < 0)
1072 if (drop_privs() < 0)
1077 else if (iface_get_initial_state(&st) < 0)
1085 p = AVAHI_IPDATA_DIR;
1087 address_fn = avahi_strdup_printf(
1088 "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1089 hw_address[0], hw_address[1],
1090 hw_address[2], hw_address[3],
1091 hw_address[4], hw_address[5]);
1094 load_address(address_fn, &addr);
1096 if (addr && !is_ll_address(addr)) {
1097 daemon_log(LOG_WARNING, "Requested address %s is not from IPv4LL range 169.254/16, ignoring.", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1105 for (i = 0; i < ETHER_ADDRLEN; i++)
1106 a += hw_address[i]*i;
1108 addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1111 set_state(st, 1, addr);
1113 daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1115 if (state == STATE_SLEEPING)
1116 daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1118 if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1119 daemon_retval_send(0);
1123 memset(pollfds, 0, sizeof(pollfds));
1124 pollfds[FD_ARP].fd = fd;
1125 pollfds[FD_ARP].events = POLLIN;
1126 pollfds[FD_IFACE].fd = iface_fd;
1127 pollfds[FD_IFACE].events = POLLIN;
1128 pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1129 pollfds[FD_SIGNAL].events = POLLIN;
1135 if (state == STATE_START) {
1137 /* First, wait a random time */
1138 set_state(STATE_WAITING_PROBE, 1, addr);
1140 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1141 next_wakeup_valid = 1;
1143 } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1144 (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1147 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1148 set_state(STATE_PROBING, 0, addr);
1150 elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1151 next_wakeup_valid = 1;
1153 } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1155 /* Send the last probe */
1156 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1157 set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1159 elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1160 next_wakeup_valid = 1;
1162 } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1163 (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1165 /* Send announcement packet */
1166 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1167 set_state(STATE_ANNOUNCING, 0, addr);
1169 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1170 next_wakeup_valid = 1;
1172 if (n_iteration == 0) {
1173 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1179 } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1181 daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1182 set_state(STATE_RUNNING, 0, addr);
1184 next_wakeup_valid = 0;
1186 save_address(address_fn, addr);
1189 daemon_retval_send(0);
1193 } else if (event == EVENT_PACKET) {
1198 if (packet_parse(in_packet, in_packet_len, &info) < 0)
1199 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1203 if (info.sender_ip_address == addr) {
1204 /* Normal conflict */
1206 daemon_log(LOG_INFO, "Recieved conflicting normal ARP packet.");
1207 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1208 /* Probe conflict */
1209 conflict = info.target_ip_address == addr && memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1212 daemon_log(LOG_INFO, "Recieved conflicting probe ARP packet.");
1217 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1218 if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1221 /* Pick a new address */
1222 addr = pick_addr(addr);
1224 daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1228 set_state(STATE_WAITING_PROBE, 1, addr);
1230 if (n_conflict >= MAX_CONFLICTS) {
1231 daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1232 elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1234 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1236 next_wakeup_valid = 1;
1238 DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1241 } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED) {
1243 daemon_log(LOG_INFO, "A routable address has been configured.");
1245 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1246 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1250 daemon_retval_send(0);
1254 set_state(STATE_SLEEPING, 1, addr);
1255 next_wakeup_valid = 0;
1257 } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1259 daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1261 set_state(STATE_WAITING_PROBE, 1, addr);
1263 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1264 next_wakeup_valid = 1;
1266 } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING && !force_bind) {
1268 /* The user requested a reannouncing of the address by a SIGHUP */
1269 daemon_log(LOG_INFO, "Reannouncing address.");
1271 /* Send announcement packet */
1272 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1273 set_state(STATE_ANNOUNCING, 1, addr);
1275 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1276 next_wakeup_valid = 1;
1280 DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1282 if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1285 avahi_free(out_packet);
1290 avahi_free(in_packet);
1297 if (next_wakeup_valid) {
1298 usec = avahi_age(&next_wakeup);
1299 timeout = usec < 0 ? (int) (-usec/1000) : 0;
1302 DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1304 while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1308 daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1310 } else if (r == 0) {
1311 event = EVENT_TIMEOUT;
1312 next_wakeup_valid = 0;
1316 if (pollfds[FD_ARP].revents) {
1318 if (pollfds[FD_ARP].revents == POLLERR) {
1319 /* The interface is probably down, let's recreate our socket */
1323 if ((fd = open_socket(iface, hw_address)) < 0)
1326 pollfds[FD_ARP].fd = fd;
1330 assert(pollfds[FD_ARP].revents == POLLIN);
1332 if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1336 event = EVENT_PACKET;
1340 if (event == EVENT_NULL &&
1341 pollfds[FD_IFACE].revents) {
1343 assert(pollfds[FD_IFACE].revents == POLLIN);
1345 if (iface_process(&event) < 0)
1349 if (event == EVENT_NULL &&
1350 pollfds[FD_SIGNAL].revents) {
1353 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1355 if ((sig = daemon_signal_next()) <= 0) {
1356 daemon_log(LOG_ERR, "daemon_signal_next() failed");
1363 daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1368 waitpid(-1, NULL, WNOHANG);
1372 event = EVENT_REFRESH_REQUEST;
1384 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1385 do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1387 avahi_free(out_packet);
1388 avahi_free(in_packet);
1396 if (daemonize && !retval_sent)
1397 daemon_retval_send(ret);
1403 avahi_free(address_fn);
1409 static void help(FILE *f, const char *a0) {
1411 "%s [options] INTERFACE\n"
1412 " -h --help Show this help\n"
1413 " -D --daemonize Daemonize after startup\n"
1414 " -s --syslog Write log messages to syslog(3) instead of STDERR\n"
1415 " -k --kill Kill a running daemon\n"
1416 " -r --refresh Request a running daemon to refresh it's IP address\n"
1417 " -c --check Return 0 if a daemon is already running\n"
1418 " -V --version Show version\n"
1419 " -S --start=ADDRESS Start with this address from the IPv4LL range\n"
1421 " -w --wait Wait until an address has been acquired before\n"
1423 " --force-bind Assign an IPv4LL address even if a routable address\n"
1424 " is already assigned\n"
1425 " --no-drop-root Don't drop privileges\n"
1427 " --no-chroot Don't chroot()\n"
1429 " --no-proc-title Don't modify process title\n"
1430 " --debug Increase verbosity\n",
1434 static int parse_command_line(int argc, char *argv[]) {
1438 OPTION_NO_PROC_TITLE = 256,
1441 OPTION_NO_DROP_ROOT,
1447 static const struct option long_options[] = {
1448 { "help", no_argument, NULL, 'h' },
1449 { "daemonize", no_argument, NULL, 'D' },
1450 { "syslog", no_argument, NULL, 's' },
1451 { "kill", no_argument, NULL, 'k' },
1452 { "refresh", no_argument, NULL, 'r' },
1453 { "check", no_argument, NULL, 'c' },
1454 { "version", no_argument, NULL, 'V' },
1455 { "start", required_argument, NULL, 'S' },
1456 { "wait", no_argument, NULL, 'w' },
1457 { "force-bind", no_argument, NULL, OPTION_FORCE_BIND },
1458 { "no-drop-root", no_argument, NULL, OPTION_NO_DROP_ROOT },
1460 { "no-chroot", no_argument, NULL, OPTION_NO_CHROOT },
1462 { "no-proc-title", no_argument, NULL, OPTION_NO_PROC_TITLE },
1463 { "debug", no_argument, NULL, OPTION_DEBUG },
1464 { NULL, 0, NULL, 0 }
1467 while ((c = getopt_long(argc, argv, "hDskrcVS:w", long_options, NULL)) >= 0) {
1474 command = DAEMON_HELP;
1480 command = DAEMON_KILL;
1483 command = DAEMON_VERSION;
1486 command = DAEMON_REFRESH;
1489 command = DAEMON_CHECK;
1493 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1494 fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1499 wait_for_address = 1;
1502 case OPTION_NO_PROC_TITLE:
1503 modify_proc_title = 0;
1510 case OPTION_FORCE_BIND:
1514 case OPTION_NO_DROP_ROOT:
1519 case OPTION_NO_CHROOT:
1529 if (command == DAEMON_RUN ||
1530 command == DAEMON_KILL ||
1531 command == DAEMON_REFRESH ||
1532 command == DAEMON_CHECK) {
1534 if (optind >= argc) {
1535 fprintf(stderr, "Missing interface name.\n");
1539 interface_name = avahi_strdup(argv[optind++]);
1542 if (optind != argc) {
1543 fprintf(stderr, "Too many arguments\n");
1550 static const char* pid_file_proc(void) {
1551 return pid_file_name;
1554 int main(int argc, char*argv[]) {
1556 char *log_ident = NULL;
1558 signal(SIGPIPE, SIG_IGN);
1560 if ((argv0 = strrchr(argv[0], '/')))
1561 argv0 = avahi_strdup(argv0 + 1);
1563 argv0 = avahi_strdup(argv[0]);
1565 daemon_log_ident = argv0;
1567 if (parse_command_line(argc, argv) < 0)
1570 if (modify_proc_title)
1571 avahi_init_proc_title(argc, argv);
1573 daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1574 daemon_pid_file_proc = pid_file_proc;
1575 pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1577 if (command == DAEMON_RUN) {
1583 if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1584 daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1588 if (getuid() != 0) {
1589 daemon_log(LOG_ERR, "This program is intended to be run as root.");
1593 if ((pid = daemon_pid_file_is_running()) >= 0) {
1594 daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1599 daemon_retval_init();
1601 if ((pid = daemon_fork()) < 0)
1603 else if (pid != 0) {
1607 if ((ret = daemon_retval_wait(20)) < 0) {
1608 daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1619 if (use_syslog || daemonize)
1620 daemon_log_use = DAEMON_LOG_SYSLOG;
1624 if (daemon_pid_file_create() < 0) {
1625 daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1628 daemon_retval_send(1);
1633 avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1635 if (loop(ifindex, start_address) < 0)
1639 } else if (command == DAEMON_HELP) {
1640 help(stdout, argv0);
1643 } else if (command == DAEMON_VERSION) {
1644 printf("%s "PACKAGE_VERSION"\n", argv0);
1647 } else if (command == DAEMON_KILL) {
1648 if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1649 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1654 } else if (command == DAEMON_REFRESH) {
1655 if (daemon_pid_file_kill(SIGHUP) < 0) {
1656 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1661 } else if (command == DAEMON_CHECK)
1662 r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1668 daemon_retval_done();
1671 daemon_pid_file_remove();
1673 avahi_free(log_ident);
1674 avahi_free(pid_file_name);
1676 avahi_free(interface_name);