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>
66 /* Old versions of PCAP defined it as D_IN */
68 #define PCAP_D_IN D_IN
73 #include <avahi-common/malloc.h>
74 #include <avahi-common/timeval.h>
75 #include <avahi-daemon/setproctitle.h>
77 #include <libdaemon/dfork.h>
78 #include <libdaemon/dsignal.h>
79 #include <libdaemon/dlog.h>
80 #include <libdaemon/dpid.h>
81 #include <libdaemon/dexec.h>
88 /* An implementation of RFC 3927 */
90 /* Constants from the RFC */
95 #define ANNOUNCE_WAIT 2
96 #define ANNOUNCE_NUM 2
97 #define ANNOUNCE_INTERVAL 2
98 #define MAX_CONFLICTS 10
99 #define RATE_LIMIT_INTERVAL 60
100 #define DEFEND_INTERVAL 10
102 #define IPV4LL_NETWORK 0xA9FE0000L
103 #define IPV4LL_NETMASK 0xFFFF0000L
104 #define IPV4LL_HOSTMASK 0x0000FFFFL
105 #define IPV4LL_BROADCAST 0xA9FEFFFFL
107 #define ETHER_ADDRLEN 6
108 #define ETHER_HDR_SIZE (2+2*ETHER_ADDRLEN)
109 #define ARP_PACKET_SIZE (8+4+4+2*ETHER_ADDRLEN)
111 typedef enum ArpOperation {
116 typedef struct ArpPacketInfo {
117 ArpOperation operation;
119 uint32_t sender_ip_address, target_ip_address;
120 uint8_t sender_hw_address[ETHER_ADDRLEN], target_hw_address[ETHER_ADDRLEN];
123 typedef struct ArpPacket {
124 uint8_t *ether_header;
125 uint8_t *ether_payload;
128 static State state = STATE_START;
129 static int n_iteration = 0;
130 static int n_conflict = 0;
132 static char *interface_name = NULL;
133 static char *pid_file_name = NULL;
134 static uint32_t start_address = 0;
135 static char *argv0 = NULL;
136 static int daemonize = 0;
137 static int wait_for_address = 0;
138 static int use_syslog = 0;
139 static int debug = 0;
140 static int modify_proc_title = 1;
141 static int force_bind = 0;
143 static int no_chroot = 0;
145 static int no_drop_root = 0;
146 static int wrote_pid_file = 0;
147 static char *action_script = NULL;
156 } command = DAEMON_RUN;
158 typedef enum CalloutEvent {
166 static const char * const callout_event_table[CALLOUT_MAX] = {
167 [CALLOUT_BIND] = "BIND",
168 [CALLOUT_CONFLICT] = "CONFLICT",
169 [CALLOUT_UNBIND] = "UNBIND",
170 [CALLOUT_STOP] = "STOP"
173 typedef struct CalloutEventInfo {
179 #define RANDOM_DEVICE "/dev/urandom"
181 #define DEBUG(x) do {\
187 static void init_rand_seed(void) {
191 /* Try to initialize seed from /dev/urandom, to make it a little
192 * less predictable, and to make sure that multiple machines
193 * booted at the same time choose different random seeds. */
194 if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
195 read(fd, &seed, sizeof(seed));
199 /* If the initialization failed by some reason, we add the time to the seed */
200 seed ^= (unsigned) time(NULL);
205 static uint32_t pick_addr(uint32_t old_addr) {
209 unsigned r = (unsigned) rand();
211 /* Reduce to 16 bits */
213 r = (r >> 16) ^ (r & 0xFFFF);
215 addr = htonl(IPV4LL_NETWORK | (uint32_t) r);
217 } while (addr == old_addr || !is_ll_address(addr));
222 static int load_address(const char *fn, uint32_t *addr) {
229 if (!(f = fopen(fn, "r"))) {
231 if (errno == ENOENT) {
236 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
240 if (fscanf(f, "%u.%u.%u.%u\n", &a, &b, &c, &d) != 4) {
241 daemon_log(LOG_ERR, "Parse failure");
247 *addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
257 static int save_address(const char *fn, uint32_t addr) {
265 if (!(f = fopen(fn, "w"))) {
266 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
271 fprintf(f, "%s\n", inet_ntop(AF_INET, &addr, buf, sizeof (buf)));
286 * Allocate a buffer with two pointers in front, one of which is
287 * guaranteed to point ETHER_HDR_SIZE bytes into it.
289 static ArpPacket* packet_new(size_t packet_len) {
293 assert(packet_len > 0);
296 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + packet_len);
298 p->ether_header = NULL;
299 p->ether_payload = b + sizeof(struct ArpPacket);
302 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + ETHER_HDR_SIZE + packet_len);
304 p->ether_header = b + sizeof(struct ArpPacket);
305 p->ether_payload = b + sizeof(struct ArpPacket) + ETHER_HDR_SIZE;
311 static ArpPacket* packet_new_with_info(const ArpPacketInfo *info, size_t *packet_len) {
316 assert(info->operation == ARP_REQUEST || info->operation == ARP_RESPONSE);
317 assert(packet_len != NULL);
319 *packet_len = ARP_PACKET_SIZE;
320 p = packet_new(*packet_len);
321 r = p->ether_payload;
323 r[1] = 1; /* HTYPE */
324 r[2] = 8; /* PTYPE */
325 r[4] = ETHER_ADDRLEN; /* HLEN */
327 r[7] = (uint8_t) info->operation;
329 memcpy(r+8, info->sender_hw_address, ETHER_ADDRLEN);
330 memcpy(r+14, &info->sender_ip_address, 4);
331 memcpy(r+18, info->target_hw_address, ETHER_ADDRLEN);
332 memcpy(r+24, &info->target_ip_address, 4);
337 static ArpPacket *packet_new_probe(uint32_t ip_address, const uint8_t*hw_address, size_t *packet_len) {
340 memset(&info, 0, sizeof(info));
341 info.operation = ARP_REQUEST;
342 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
343 info.target_ip_address = ip_address;
345 return packet_new_with_info(&info, packet_len);
348 static ArpPacket *packet_new_announcement(uint32_t ip_address, const uint8_t* hw_address, size_t *packet_len) {
351 memset(&info, 0, sizeof(info));
352 info.operation = ARP_REQUEST;
353 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
354 info.target_ip_address = ip_address;
355 info.sender_ip_address = ip_address;
357 return packet_new_with_info(&info, packet_len);
360 static int packet_parse(const ArpPacket *packet, size_t packet_len, ArpPacketInfo *info) {
364 p = (uint8_t *)packet->ether_payload;
367 if (packet_len < ARP_PACKET_SIZE)
370 /* Check HTYPE and PTYPE */
371 if (p[0] != 0 || p[1] != 1 || p[2] != 8 || p[3] != 0)
374 /* Check HLEN, PLEN, OPERATION */
375 if (p[4] != ETHER_ADDRLEN || p[5] != 4 || p[6] != 0 || (p[7] != 1 && p[7] != 2))
378 info->operation = p[7];
379 memcpy(info->sender_hw_address, p+8, ETHER_ADDRLEN);
380 memcpy(&info->sender_ip_address, p+14, 4);
381 memcpy(info->target_hw_address, p+18, ETHER_ADDRLEN);
382 memcpy(&info->target_ip_address, p+24, 4);
387 static void set_state(State st, int reset_counter, uint32_t address) {
388 static const char* const state_table[] = {
389 [STATE_START] = "START",
390 [STATE_WAITING_PROBE] = "WAITING_PROBE",
391 [STATE_PROBING] = "PROBING",
392 [STATE_WAITING_ANNOUNCE] = "WAITING_ANNOUNCE",
393 [STATE_ANNOUNCING] = "ANNOUNCING",
394 [STATE_RUNNING] = "RUNNING",
395 [STATE_SLEEPING] = "SLEEPING"
399 assert(st < STATE_MAX);
401 if (st == state && !reset_counter) {
403 DEBUG(daemon_log(LOG_DEBUG, "State iteration %s-%i", state_table[state], n_iteration));
405 DEBUG(daemon_log(LOG_DEBUG, "State transition %s-%i -> %s-0", state_table[state], n_iteration, state_table[st]));
410 if (state == STATE_SLEEPING)
411 avahi_set_proc_title(argv0, "%s: [%s] sleeping", argv0, interface_name);
412 else if (state == STATE_ANNOUNCING)
413 avahi_set_proc_title(argv0, "%s: [%s] announcing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
414 else if (state == STATE_RUNNING)
415 avahi_set_proc_title(argv0, "%s: [%s] bound %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
417 avahi_set_proc_title(argv0, "%s: [%s] probing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
420 static int interface_up(int iface) {
424 if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
425 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
429 memset(&ifreq, 0, sizeof(ifreq));
430 if (!if_indextoname(iface, ifreq.ifr_name)) {
431 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
435 if (ioctl(fd, SIOCGIFFLAGS, &ifreq) < 0) {
436 daemon_log(LOG_ERR, "SIOCGIFFLAGS failed: %s", strerror(errno));
440 ifreq.ifr_flags |= IFF_UP;
442 if (ioctl(fd, SIOCSIFFLAGS, &ifreq) < 0) {
443 daemon_log(LOG_ERR, "SIOCSIFFLAGS failed: %s", strerror(errno));
460 /* Linux 'packet socket' specific implementation */
462 static int open_socket(int iface, uint8_t *hw_address) {
464 struct sockaddr_ll sa;
467 if (interface_up(iface) < 0)
470 if ((fd = socket(PF_PACKET, SOCK_DGRAM, 0)) < 0) {
471 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
475 memset(&sa, 0, sizeof(sa));
476 sa.sll_family = AF_PACKET;
477 sa.sll_protocol = htons(ETH_P_ARP);
478 sa.sll_ifindex = iface;
480 if (bind(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
481 daemon_log(LOG_ERR, "bind() failed: %s", strerror(errno));
486 if (getsockname(fd, (struct sockaddr*) &sa, &sa_len) < 0) {
487 daemon_log(LOG_ERR, "getsockname() failed: %s", strerror(errno));
491 if (sa.sll_halen != ETHER_ADDRLEN) {
492 daemon_log(LOG_ERR, "getsockname() returned invalid hardware address.");
496 memcpy(hw_address, sa.sll_addr, ETHER_ADDRLEN);
507 static int send_packet(int fd, int iface, ArpPacket *packet, size_t packet_len) {
508 struct sockaddr_ll sa;
512 assert(packet_len > 0);
514 memset(&sa, 0, sizeof(sa));
515 sa.sll_family = AF_PACKET;
516 sa.sll_protocol = htons(ETH_P_ARP);
517 sa.sll_ifindex = iface;
518 sa.sll_halen = ETHER_ADDRLEN;
519 memset(sa.sll_addr, 0xFF, ETHER_ADDRLEN);
521 if (sendto(fd, packet->ether_payload, packet_len, 0, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
522 daemon_log(LOG_ERR, "sendto() failed: %s", strerror(errno));
529 static int recv_packet(int fd, ArpPacket **packet, size_t *packet_len) {
531 struct sockaddr_ll sa;
541 if (ioctl(fd, FIONREAD, &s) < 0) {
542 daemon_log(LOG_ERR, "FIONREAD failed: %s", strerror(errno));
549 *packet = packet_new(s);
552 if ((r = recvfrom(fd, (*packet)->ether_payload, s, 0, (struct sockaddr*) &sa, &sa_len)) < 0) {
553 daemon_log(LOG_ERR, "recvfrom() failed: %s", strerror(errno));
557 *packet_len = (size_t) r;
571 close_socket(int fd) {
575 #else /* !__linux__ */
576 /* PCAP-based implementation */
579 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
580 static uint8_t __lladdr[ETHER_ADDRLEN];
583 #define elementsof(array) (sizeof(array)/sizeof(array[0]))
587 __get_ether_addr(int ifindex, u_char *lladdr)
591 struct if_msghdr *ifm;
594 struct sockaddr_dl *sdl;
601 mib[4] = NET_RT_IFLIST;
604 if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
605 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
612 daemon_log(LOG_ERR, "malloc(%d): %s", len, strerror(errno));
616 if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
617 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
624 for (next = buf; next < lim; next += ifm->ifm_msglen) {
625 ifm = (struct if_msghdr *)next;
626 if (ifm->ifm_type == RTM_IFINFO) {
627 sdl = (struct sockaddr_dl *)(ifm + 1);
628 memcpy(lladdr, LLADDR(sdl), ETHER_ADDRLEN);
637 open_socket(int iface, uint8_t *hw_address)
639 struct bpf_program bpf;
640 char ifname[IFNAMSIZ];
645 assert(__pp == NULL);
647 if (interface_up(iface) < 0) {
650 if (__get_ether_addr(iface, __lladdr) == -1) {
653 if (if_indextoname(iface, ifname) == NULL) {
657 pp = pcap_open_live(ifname, 1500, 0, 0, __pcap_errbuf);
661 err = pcap_set_datalink(pp, DLT_EN10MB);
663 daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
667 err = pcap_setdirection(pp, PCAP_D_IN);
669 daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
674 fd = pcap_get_selectable_fd(pp);
680 /* XXX: can we use this with pcap_next_ex() ? */
681 err = pcap_setnonblock(pp, 1, __pcap_errbuf);
688 err = pcap_compile(pp, &bpf,
689 "arp and ether dst ff:ff:ff:ff:ff:ff", 1, 0);
691 daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
695 err = pcap_setfilter(pp, &bpf);
697 daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
703 /* Stash pcap-specific context away. */
704 memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
711 close_socket(int fd __unused)
714 assert(__pp != NULL);
720 * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
721 * and prepend the required ethernet header information before sending.
724 send_packet(int fd __unused, int iface __unused, ArpPacket *packet,
727 struct ether_header *eh;
729 assert(__pp != NULL);
730 assert(packet != NULL);
732 eh = (struct ether_header *)packet->ether_header;
733 memset(eh->ether_dhost, 0xFF, ETHER_ADDRLEN);
734 memcpy(eh->ether_shost, __lladdr, ETHER_ADDRLEN);
735 eh->ether_type = htons(0x0806);
737 return (pcap_inject(__pp, (void *)eh, packet_len + sizeof(*eh)));
741 recv_packet(int fd __unused, ArpPacket **packet, size_t *packet_len)
743 struct pcap_pkthdr *ph;
749 assert(__pp != NULL);
750 assert(packet != NULL);
751 assert(packet_len != NULL);
757 err = pcap_next_ex(__pp, &ph, (const u_char **)&pd);
758 if (err == 1 && ph->caplen <= ph->len) {
759 ap = packet_new(ph->caplen);
760 memcpy(ap->ether_header, pd, ph->caplen);
762 *packet_len = (ph->caplen - sizeof(struct ether_header));
766 daemon_log(LOG_ERR, "pcap len > caplen");
768 daemon_log(LOG_ERR, "pcap_next_ex: %s",
775 #endif /* __linux__ */
777 int is_ll_address(uint32_t addr) {
779 ((ntohl(addr) & IPV4LL_NETMASK) == IPV4LL_NETWORK) &&
780 ((ntohl(addr) & 0x0000FF00) != 0x0000) &&
781 ((ntohl(addr) & 0x0000FF00) != 0xFF00);
784 static struct timeval *elapse_time(struct timeval *tv, unsigned msec, unsigned jitter) {
787 gettimeofday(tv, NULL);
790 avahi_timeval_add(tv, (AvahiUsec) msec*1000);
793 avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
798 static FILE* fork_dispatcher(void) {
804 daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
808 if ((pid = fork()) < 0)
814 /* Please note that the signal pipe is not closed at this
815 * point, signals will thus be dispatched in the main
818 daemon_retval_done();
822 avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
826 if (!(f = fdopen(fds[0], "r"))) {
827 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
828 goto dispatcher_fail;
832 CalloutEventInfo info;
833 char name[IFNAMSIZ], buf[64];
836 if (fread(&info, sizeof(info), 1, f) != 1) {
840 daemon_log(LOG_ERR, "fread() failed: %s", strerror(errno));
841 goto dispatcher_fail;
844 assert(info.event <= CALLOUT_MAX);
846 if (!if_indextoname(info.ifindex, name)) {
847 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
851 if (daemon_exec("/", &k,
852 action_script, action_script,
853 callout_event_table[info.event],
855 inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
857 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
862 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
873 /* If the main process is trapped inside a chroot() we have to
874 * remove the PID file for it */
876 if (!no_chroot && wrote_pid_file)
877 daemon_pid_file_remove();
888 if (!(ret = fdopen(fds[1], "w"))) {
889 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
904 static int do_callout(FILE *f, CalloutEvent event, int iface, uint32_t addr) {
905 CalloutEventInfo info;
906 char buf[64], ifname[IFNAMSIZ];
908 daemon_log(LOG_INFO, "Callout %s, address %s on interface %s",
909 callout_event_table[event],
910 inet_ntop(AF_INET, &addr, buf, sizeof(buf)),
911 if_indextoname(iface, ifname));
914 info.ifindex = iface;
917 if (fwrite(&info, sizeof(info), 1, f) != 1 || fflush(f) != 0) {
918 daemon_log(LOG_ERR, "Failed to write callout event: %s", strerror(errno));
925 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
927 static int drop_privs(void) {
936 /* Get user/group ID */
940 if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
941 daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
945 if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
946 daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
950 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);
953 /* Create directory */
955 r = mkdir(AVAHI_IPDATA_DIR, 0755);
958 if (r < 0 && errno != EEXIST) {
959 daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
963 /* Convey working directory */
968 chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
970 if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
971 daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
975 if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
976 daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
984 if (chroot(AVAHI_IPDATA_DIR) < 0) {
985 daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
989 daemon_log(LOG_INFO, "Successfully called chroot().");
992 /* Since we are now trapped inside a chroot we cannot remove
993 * the pid file anymore, the helper process will do that for us. */
1001 if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
1002 daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
1006 #if defined(HAVE_SETRESGID)
1007 r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1008 #elif defined(HAVE_SETEGID)
1009 if ((r = setgid(gr->gr_gid)) >= 0)
1010 r = setegid(gr->gr_gid);
1011 #elif defined(HAVE_SETREGID)
1012 r = setregid(gr->gr_gid, gr->gr_gid);
1014 #error "No API to drop privileges"
1018 daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1022 #if defined(HAVE_SETRESUID)
1023 r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1024 #elif defined(HAVE_SETEUID)
1025 if ((r = setuid(pw->pw_uid)) >= 0)
1026 r = seteuid(pw->pw_uid);
1027 #elif defined(HAVE_SETREUID)
1028 r = setreuid(pw->pw_uid, pw->pw_uid);
1030 #error "No API to drop privileges"
1034 daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1038 set_env("USER", pw->pw_name);
1039 set_env("LOGNAME", pw->pw_name);
1040 set_env("HOME", pw->pw_dir);
1042 daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1048 static int loop(int iface, uint32_t addr) {
1056 int fd = -1, ret = -1;
1057 struct timeval next_wakeup;
1058 int next_wakeup_valid = 0;
1060 ArpPacket *in_packet = NULL;
1061 size_t in_packet_len;
1062 ArpPacket *out_packet = NULL;
1063 size_t out_packet_len;
1064 uint8_t hw_address[ETHER_ADDRLEN];
1065 struct pollfd pollfds[FD_MAX];
1067 Event event = EVENT_NULL;
1068 int retval_sent = !daemonize;
1070 FILE *dispatcher = NULL;
1071 char *address_fn = NULL;
1074 daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP,0);
1076 if (!(dispatcher = fork_dispatcher()))
1079 if ((fd = open_socket(iface, hw_address)) < 0)
1082 if ((iface_fd = iface_init(iface)) < 0)
1085 if (drop_privs() < 0)
1090 else if (iface_get_initial_state(&st) < 0)
1098 p = AVAHI_IPDATA_DIR;
1100 address_fn = avahi_strdup_printf(
1101 "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1102 hw_address[0], hw_address[1],
1103 hw_address[2], hw_address[3],
1104 hw_address[4], hw_address[5]);
1107 load_address(address_fn, &addr);
1109 if (addr && !is_ll_address(addr)) {
1110 daemon_log(LOG_WARNING, "Requested address %s is not from IPv4LL range 169.254/16 or a reserved address, ignoring.", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1118 for (i = 0; i < ETHER_ADDRLEN; i++)
1119 a += hw_address[i]*i;
1121 addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1124 set_state(st, 1, addr);
1126 daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1128 if (state == STATE_SLEEPING)
1129 daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1131 if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1132 daemon_retval_send(0);
1136 memset(pollfds, 0, sizeof(pollfds));
1137 pollfds[FD_ARP].fd = fd;
1138 pollfds[FD_ARP].events = POLLIN;
1139 pollfds[FD_IFACE].fd = iface_fd;
1140 pollfds[FD_IFACE].events = POLLIN;
1141 pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1142 pollfds[FD_SIGNAL].events = POLLIN;
1148 if (state == STATE_START) {
1150 /* First, wait a random time */
1151 set_state(STATE_WAITING_PROBE, 1, addr);
1153 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1154 next_wakeup_valid = 1;
1156 } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1157 (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1160 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1161 set_state(STATE_PROBING, 0, addr);
1163 elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1164 next_wakeup_valid = 1;
1166 } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1168 /* Send the last probe */
1169 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1170 set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1172 elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1173 next_wakeup_valid = 1;
1175 } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1176 (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1178 /* Send announcement packet */
1179 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1180 set_state(STATE_ANNOUNCING, 0, addr);
1182 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1183 next_wakeup_valid = 1;
1185 if (n_iteration == 0) {
1186 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1192 } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1194 daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1195 set_state(STATE_RUNNING, 0, addr);
1197 next_wakeup_valid = 0;
1199 save_address(address_fn, addr);
1202 daemon_retval_send(0);
1206 } else if (event == EVENT_PACKET) {
1211 if (packet_parse(in_packet, in_packet_len, &info) < 0)
1212 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1216 if (info.sender_ip_address == addr) {
1217 /* Normal conflict */
1219 daemon_log(LOG_INFO, "Received conflicting normal ARP packet.");
1220 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1221 /* Probe conflict */
1222 conflict = info.target_ip_address == addr && memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1225 daemon_log(LOG_INFO, "Received conflicting probe ARP packet.");
1230 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1231 if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1234 /* Pick a new address */
1235 addr = pick_addr(addr);
1237 daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1241 set_state(STATE_WAITING_PROBE, 1, addr);
1243 if (n_conflict >= MAX_CONFLICTS) {
1244 daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1245 elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1247 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1249 next_wakeup_valid = 1;
1251 DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1254 } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED) {
1256 daemon_log(LOG_INFO, "A routable address has been configured.");
1258 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1259 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1263 daemon_retval_send(0);
1267 set_state(STATE_SLEEPING, 1, addr);
1268 next_wakeup_valid = 0;
1270 } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1272 daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1274 set_state(STATE_WAITING_PROBE, 1, addr);
1276 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1277 next_wakeup_valid = 1;
1279 } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING && !force_bind) {
1281 /* The user requested a reannouncing of the address by a SIGHUP */
1282 daemon_log(LOG_INFO, "Reannouncing address.");
1284 /* Send announcement packet */
1285 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1286 set_state(STATE_ANNOUNCING, 1, addr);
1288 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1289 next_wakeup_valid = 1;
1293 DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1295 if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1298 avahi_free(out_packet);
1303 avahi_free(in_packet);
1310 if (next_wakeup_valid) {
1311 usec = avahi_age(&next_wakeup);
1312 timeout = usec < 0 ? (int) (-usec/1000) : 0;
1315 DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1317 while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1321 daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1323 } else if (r == 0) {
1324 event = EVENT_TIMEOUT;
1325 next_wakeup_valid = 0;
1329 if (pollfds[FD_ARP].revents) {
1331 if (pollfds[FD_ARP].revents == POLLERR) {
1332 /* The interface is probably down, let's recreate our socket */
1336 if ((fd = open_socket(iface, hw_address)) < 0)
1339 pollfds[FD_ARP].fd = fd;
1343 assert(pollfds[FD_ARP].revents == POLLIN);
1345 if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1349 event = EVENT_PACKET;
1353 if (event == EVENT_NULL &&
1354 pollfds[FD_IFACE].revents) {
1356 assert(pollfds[FD_IFACE].revents == POLLIN);
1358 if (iface_process(&event) < 0)
1362 if (event == EVENT_NULL &&
1363 pollfds[FD_SIGNAL].revents) {
1366 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1368 if ((sig = daemon_signal_next()) <= 0) {
1369 daemon_log(LOG_ERR, "daemon_signal_next() failed");
1376 daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1381 waitpid(-1, NULL, WNOHANG);
1385 event = EVENT_REFRESH_REQUEST;
1397 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1398 do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1400 avahi_free(out_packet);
1401 avahi_free(in_packet);
1409 if (daemonize && !retval_sent)
1410 daemon_retval_send(ret);
1416 avahi_free(address_fn);
1422 static void help(FILE *f, const char *a0) {
1424 "%s [options] INTERFACE\n"
1425 " -h --help Show this help\n"
1426 " -D --daemonize Daemonize after startup\n"
1427 " -s --syslog Write log messages to syslog(3) instead of STDERR\n"
1428 " -k --kill Kill a running daemon\n"
1429 " -r --refresh Request a running daemon refresh its IP address\n"
1430 " -c --check Return 0 if a daemon is already running\n"
1431 " -V --version Show version\n"
1432 " -S --start=ADDRESS Start with this address from the IPv4LL range\n"
1434 " -t --script=script Action script to run (defaults to\n"
1435 " "AVAHI_IPCONF_SCRIPT")\n"
1436 " -w --wait Wait until an address has been acquired before\n"
1438 " --force-bind Assign an IPv4LL address even if a routable address\n"
1439 " is already assigned\n"
1440 " --no-drop-root Don't drop privileges\n"
1442 " --no-chroot Don't chroot()\n"
1444 " --no-proc-title Don't modify process title\n"
1445 " --debug Increase verbosity\n",
1449 static int parse_command_line(int argc, char *argv[]) {
1453 OPTION_NO_PROC_TITLE = 256,
1456 OPTION_NO_DROP_ROOT,
1462 static const struct option long_options[] = {
1463 { "help", no_argument, NULL, 'h' },
1464 { "daemonize", no_argument, NULL, 'D' },
1465 { "syslog", no_argument, NULL, 's' },
1466 { "kill", no_argument, NULL, 'k' },
1467 { "refresh", no_argument, NULL, 'r' },
1468 { "check", no_argument, NULL, 'c' },
1469 { "version", no_argument, NULL, 'V' },
1470 { "start", required_argument, NULL, 'S' },
1471 { "script", required_argument, NULL, 't' },
1472 { "wait", no_argument, NULL, 'w' },
1473 { "force-bind", no_argument, NULL, OPTION_FORCE_BIND },
1474 { "no-drop-root", no_argument, NULL, OPTION_NO_DROP_ROOT },
1476 { "no-chroot", no_argument, NULL, OPTION_NO_CHROOT },
1478 { "no-proc-title", no_argument, NULL, OPTION_NO_PROC_TITLE },
1479 { "debug", no_argument, NULL, OPTION_DEBUG },
1480 { NULL, 0, NULL, 0 }
1483 while ((c = getopt_long(argc, argv, "hDskrcVS:t:w", long_options, NULL)) >= 0) {
1490 command = DAEMON_HELP;
1496 command = DAEMON_KILL;
1499 command = DAEMON_VERSION;
1502 command = DAEMON_REFRESH;
1505 command = DAEMON_CHECK;
1509 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1510 fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1515 avahi_free(action_script);
1516 action_script = avahi_strdup(optarg);
1519 wait_for_address = 1;
1522 case OPTION_NO_PROC_TITLE:
1523 modify_proc_title = 0;
1530 case OPTION_FORCE_BIND:
1534 case OPTION_NO_DROP_ROOT:
1539 case OPTION_NO_CHROOT:
1549 if (command == DAEMON_RUN ||
1550 command == DAEMON_KILL ||
1551 command == DAEMON_REFRESH ||
1552 command == DAEMON_CHECK) {
1554 if (optind >= argc) {
1555 fprintf(stderr, "Missing interface name.\n");
1559 interface_name = avahi_strdup(argv[optind++]);
1562 if (optind != argc) {
1563 fprintf(stderr, "Too many arguments\n");
1568 action_script = avahi_strdup(AVAHI_IPCONF_SCRIPT);
1573 static const char* pid_file_proc(void) {
1574 return pid_file_name;
1577 int main(int argc, char*argv[]) {
1579 char *log_ident = NULL;
1581 signal(SIGPIPE, SIG_IGN);
1583 if ((argv0 = strrchr(argv[0], '/')))
1584 argv0 = avahi_strdup(argv0 + 1);
1586 argv0 = avahi_strdup(argv[0]);
1588 daemon_log_ident = argv0;
1590 if (parse_command_line(argc, argv) < 0)
1593 if (modify_proc_title)
1594 avahi_init_proc_title(argc, argv);
1596 daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1597 daemon_pid_file_proc = pid_file_proc;
1598 pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1600 if (command == DAEMON_RUN) {
1606 if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1607 daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1611 if (getuid() != 0) {
1612 daemon_log(LOG_ERR, "This program is intended to be run as root.");
1616 if ((pid = daemon_pid_file_is_running()) >= 0) {
1617 daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1622 daemon_retval_init();
1624 if ((pid = daemon_fork()) < 0)
1626 else if (pid != 0) {
1630 if ((ret = daemon_retval_wait(20)) < 0) {
1631 daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1642 if (use_syslog || daemonize)
1643 daemon_log_use = DAEMON_LOG_SYSLOG;
1647 if (daemon_pid_file_create() < 0) {
1648 daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1651 daemon_retval_send(1);
1656 avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1658 if (loop(ifindex, start_address) < 0)
1662 } else if (command == DAEMON_HELP) {
1663 help(stdout, argv0);
1666 } else if (command == DAEMON_VERSION) {
1667 printf("%s "PACKAGE_VERSION"\n", argv0);
1670 } else if (command == DAEMON_KILL) {
1671 if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1672 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1677 } else if (command == DAEMON_REFRESH) {
1678 if (daemon_pid_file_kill(SIGHUP) < 0) {
1679 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1684 } else if (command == DAEMON_CHECK)
1685 r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1691 daemon_retval_done();
1694 daemon_pid_file_remove();
1696 avahi_free(log_ident);
1697 avahi_free(pid_file_name);
1699 avahi_free(interface_name);
1700 avahi_free(action_script);